php和javahmac_sha1哈希不一样


php and java hmac_sha1 hashing are not the same

我正试图将一条消息散列到用php编写并由HMAC_SHA1算法编码的服务器端(我无法更改他的代码)。我正在用Java编写代码。php代码如下:

$utf8Str = mb_convert_encoding($strToSign, "UTF-8");
$hmac_sha1_str = base64_encode(hash_hmac("sha1", $utf8Str, KEY));
$signature = urlencode($hmac_sha1_str);

我的java代码是:

private static String HashStringSign(String toHash){
try {
    String afterUTF = new String(toHash.getBytes(), "UTF-8");
    String res = hmac_sha1(afterUTF, SecretAccessKey);
    String signature = new String(Base64.encode(res.getBytes()));
    String result = URLEncoder.encode(signature);
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
private static String hmac_sha1(String value, String key) {
    try {
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();           
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我遵循了php代码中使用的每一个哈希方法,并且按照与您所看到的相同的顺序。也许java中有一个函数在php中的工作方式不同?

我使用的是-com.sun.org.apache.xml.internal.security.utils.Base64java.net.URLEncoder、javax.crypto和org.apache.mons.codec.binary

谢谢!

hash_hmac函数中,您需要将第4个参数设置为true。

PHP代码不负责,仅限Java:

所以现在您说您不能更改PHP端,您可以对Java代码执行以下操作。

在Java代码的最后一步中,您将原始字节数组转换为六进制。然而,PHP生成一个base64编码的六进制,而不仅仅是六进制。

因此,在Java步骤结束时,只需对您的六进制进行base64编码,即可获得相同的值。https://stackoverflow.com/questions/9845767/base64-encoder-java#