I want verify hash password that genearte in python in my Java code . but hash generate in java is not same python
python code
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 code
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
}
salt bytes is like this
java salt ---> -5,58,-106,90,0,-39,44,22
python salt ---> 251,58,150,90,0,217,44,22