Java and python do not get the same sha-1 value

I need your help. My java and python scripts do not get the aa sha-1 value of the string:

hash.py

# -*- coding: utf-8 -*- import hashlib username = raw_input('username:') timestamp = raw_input('timestamp:') app_id = 'dad' secret_key = 'dadda' print 'The hashed string is: ' , hashlib.sha1( username + timestamp + app_id + secret_key ).hexdigest() 

hash.java

  public static String generateSHA1(String password) { String sha1 = ""; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(password.getBytes("UTF-8")); sha1 = byteToHex(crypt.digest()); } catch(Exception e) { e.printStackTrace(); } return sha1; } private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } 

UPDATE: Assuming password is already connected: username, timestamp, app_id and secret_key

Is there something I missed? I think something is wrong with my java re code. UTF-8 outputs this: \ xe2 \ x80 \ x8b , but I could not figure it out. Any help would be appreciated. Thanks.

+5
source share
1 answer

Make sure that both inputs use the exact same format and encoding and try using the HMAC library.

Java:

 String key = "2b5ba589b618ff2485f3391e425f86f0f405fd8e"; String data = "Something you want to keep secret!"; byte[] decodedKey = Hex.decodeHex(key.toCharArray()); SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] dataBytes = data.getBytes("UTF-8"); byte[] signatureBytes = mac.doFinal(dataBytes); String signature = new String(Base64.encodeBase64(signatureBytes), "UTF-8"); System.out.println("key = " + key); System.out.println("data = " + data); System.out.println("signature = " + signature); 

Python:

 import hmac import hashlib key = "2b5ba589b618ff2485f3391e425f86f0f405fd8e" data = "Something you want to keep secret!" decodedKey = key.decode("hex") hmac = hmac.new(decodedKey, data.encode('UTF-8'), hashlib.sha1) signature = hmac.digest().encode('base64') print "key =", key print "data =", data print "signature =", signature 

Both signature outputs must be the same.

+1
source

Source: https://habr.com/ru/post/1236349/


All Articles