Java和python没有得到相同的sha-1值

时间:2015-11-19 15:17:35

标签: java python cryptography sha1

我需要你的帮助。我的java和python脚本没有得到字符串的ame sha-1值:

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;
}

更新 假设密码已经连接:用户名,时间戳,app_id和secret_key

我错过了什么吗?我认为我的java代码有问题。 UTF-8输出: \ xe2 \ x80 \ x8b ,但我无法弄明白。任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

确保两个输入使用完全相同的格式和编码,并尝试使用HMAC库。

爪哇:

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

两个signature输出应该相同。