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

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

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

  1. def generate_ssha512_password(p: str) -> str:
  2. if isinstance(p, str):
  3. p = p.encode()
  4. p = p.strip()
  5. salt = urandom(8)
  6. pw = hashlib.sha512(p)
  7. pw.update(salt)
  8. return b64encode(pw.digest() + salt).decode()
  9. def verify_ssha512_password(challenge_password: Union[str, bytes],
  10. plain_password: Union[str, bytes]) -> bool:
  11. if isinstance(challenge_password, bytes):
  12. challenge_password = challenge_password.decode()
  13. if isinstance(plain_password, str):
  14. plain_password = plain_password.encode()
  15. # everything after that 64 bytes is the salt.
  16. if len(challenge_password) < 64:
  17. return False
  18. try:
  19. challenge_bytes = b64decode(challenge_password)
  20. digest = challenge_bytes[:64]
  21. salt = challenge_bytes[64:]
  22. hr = hashlib.sha512(plain_password)
  23. hr.update(salt)
  24. return digest == hr.digest()
  25. except:
  26. return False
  27. verify_ssha512_password(
  28. '0F2/psc+tkd8KrWmoT/LOusFk7cH6mic8nmF4v+qVmVtoxYgJXVEWEfAFfYYLRPQkwRGjgIN5FyWM9ZYdn58Tvs6lloA2SwW',
  29. 'Aa123!@#')
  30. // is valid

java代码

  1. public static byte[] get_SHA_512_SecurePassword(String passwordToHash, byte[] salt) {
  2. try {
  3. MessageDigest md = MessageDigest.getInstance("SHA-512");
  4. md.update(salt);
  5. byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
  6. return bytes;
  7. } catch (NoSuchAlgorithmException e) {
  8. e.printStackTrace();
  9. }
  10. return null;
  11. }
  12. private static boolean verify_ssha512_password(String challenge_password, String plain_password) throws UnsupportedEncodingException {
  13. byte[] challenge_bytes = Base64.decodeBase64(challenge_password.getBytes(StandardCharsets.UTF_8));
  14. byte[] digest = Arrays.copyOfRange(challenge_bytes, 0, 64);
  15. byte[] salt = Arrays.copyOfRange(challenge_bytes, 64, challenge_bytes.length);
  16. return get_SHA_512_SecurePassword(plain_password, salt).equals(digest);
  17. }
  18. public static void main(String[] args) throws UnsupportedEncodingException {
  19. boolean valid=verify_ssha512_password("0F2/psc+tkd8KrWmoT/LOusFk7cH6mic8nmF4v+qVmVtoxYgJXVEWEfAFfYYLRPQkwRGjgIN5FyWM9ZYdn58Tvs6lloA2SwW", "Aa123!@#");
  20. // is not valid
  21. }

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

暂无答案!

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

相关问题