512散列与salt的python sha-512代码不同

izj3ouym  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(249)

我想在java代码中验证python中genearte的哈希密码。但java中的hash generate和python不一样
python代码

def generate_ssha512_password(p: str) -> str:
    if isinstance(p, str):
        p = p.encode()

    p = p.strip()
    salt = urandom(8)
    pw = hashlib.sha512(p)
    pw.update(salt)
    return  b64encode(pw.digest() + salt).decode()

def verify_ssha512_password(challenge_password: Union[str, bytes],
                            plain_password: Union[str, bytes]) -> bool:
    if isinstance(challenge_password, bytes):
        challenge_password = challenge_password.decode()

    if isinstance(plain_password, str):
        plain_password = plain_password.encode()

    # everything after that 64 bytes is the salt.
    if len(challenge_password) < 64:
        return False

    try:
        challenge_bytes = b64decode(challenge_password)
        digest = challenge_bytes[:64]
        salt = challenge_bytes[64:]
        hr = hashlib.sha512(plain_password)
        hr.update(salt)

        return digest == hr.digest()
    except:
        return False
  verify_ssha512_password(
        '0F2/psc+tkd8KrWmoT/LOusFk7cH6mic8nmF4v+qVmVtoxYgJXVEWEfAFfYYLRPQkwRGjgIN5FyWM9ZYdn58Tvs6lloA2SwW',
        'Aa123!@#')
     // is valid

java代码

public static byte[] get_SHA_512_SecurePassword(String passwordToHash, byte[] salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            md.update(salt);
            byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
            return bytes;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static boolean verify_ssha512_password(String challenge_password, String plain_password) throws UnsupportedEncodingException {

        byte[] challenge_bytes = Base64.decodeBase64(challenge_password.getBytes(StandardCharsets.UTF_8));
        byte[] digest = Arrays.copyOfRange(challenge_bytes, 0, 64);
        byte[] salt = Arrays.copyOfRange(challenge_bytes, 64, challenge_bytes.length);
        return get_SHA_512_SecurePassword(plain_password, salt).equals(digest);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        boolean valid=verify_ssha512_password("0F2/psc+tkd8KrWmoT/LOusFk7cH6mic8nmF4v+qVmVtoxYgJXVEWEfAFfYYLRPQkwRGjgIN5FyWM9ZYdn58Tvs6lloA2SwW", "Aa123!@#");
    // is not valid

    }

盐字节是这样的
java 盐--->-5,58,-106,90,0,-39,44,22
Python盐--->251,58150,90,0217,44,22

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题