Java和Python生成不同的Hmac-SHA256输出

时间:2016-04-23 20:08:12

标签: java python hmac

我试图在Python中生成与我的Java模板中相同的Hmac-SHA256签名。但Python脚本生成的输出不同。我找不到我的错误。任何人都可以帮助我吗?

爪哇

public class Main {
    public static void main(String[] args) {
        String paramString = "teststring";
        calculateSignature(hash(paramString));
    }

    private static byte[] hash(String paramString)
    {
        MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
        localMessageDigest.update(paramString.getBytes("UTF-8"));
        byte[] paramByte = localMessageDigest.digest();
        System.out.println("Hash: " + DatatypeConverter.printBase64Binary(paramByte));
        return paramByte;
    }

    public static void calculateSignature(byte[] paramArrayOfByte)
    {
        String Algor = "HmacSHA256";
        Mac localMac = Mac.getInstance(Algor);
        byte [] key = "secretkey".getBytes();
        localMac.init(new SecretKeySpec(key, Algor));
        paramArrayOfByte = localMac.doFinal(paramArrayOfByte);
        System.out.println("Signature: " + DatatypeConverter.printBase64Binary(paramArrayOfByte));
    }
}
  

哈希:PIcn4BmkK0RGZ6WHtgASUb7K2ruza / 7YCHqSwYiC0RE =

     

签名:X8V4RA7qaoVGz5K2l61gAXNPuLkAI7NZ9 / 9d7WnblbA =

的Python

# -*- coding: utf-8 -*-
import hashlib
import base64
import hmac

secretkey = 'secretkey'
stringToSign = "teststring"

def hash(paramstring):
    x = base64.b64encode(hashlib.sha256(paramstring).digest())
    print('Hash: ' + x)
    return x

def calculate_signature(hashvalue):
    x = base64.b64encode(hmac.new(secretkey, hashvalue, hashlib.sha256).digest())
    print('Signature: ' + x)

calculate_signature(hash(stringToSign))
  

哈希:PIcn4BmkK0RGZ6WHtgASUb7K2ruza / 7YCHqSwYiC0RE =

     

签名:NE8RtuFsOtafWrwDdlzILMgqCDm2huJ9A3IO6iy44Jc =

1 个答案:

答案 0 :(得分:1)

问题在于你返回base64编码的python代码,但是在java中你只需将其打印为base64编码但不返回。

尝试:

private static byte[] hash(String paramString)
{
    MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
    localMessageDigest.update(paramString.getBytes("UTF-8"));
    byte[] paramByte = localMessageDigest.digest();
    String base64Binary = DatatypeConverter.printBase64Binary(paramByte);
    System.out.println("Hash: " + base64Binary);
    return base64Binary.getBytes();
}

或者将python代码修改为:

def hash(paramstring):
    x = hashlib.sha256(paramstring).digest()
    return x