为什么 PHP 的 hash_hmac('sha256') 给出的结果与 java sha256_HMAC 不同 [英] why PHP's hash_hmac('sha256') gives different result than java sha256_HMAC

查看:173
本文介绍了为什么 PHP 的 hash_hmac('sha256') 给出的结果与 java sha256_HMAC 不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中我有以下功能:

in PHP I have the following function:

base64_encode(hash_hmac('sha256', $data, $secret, false));

我正在尝试在 Java 中创建一个函数,该函数将为相同的数据"和秘密"参数提供相同的结果.

I'm trying to create a function in Java that will give the same result for the same "data" and "secret" parameters.

我尝试使用此功能:

public static String base64sha256(String data, String secret) {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    byte[] res = sha256_HMAC.doFinal(data.getBytes());
    return Base64.encodeToString(res, Base64.NO_WRAP);
}

但是对于相同的输入,我得到了不同的结果

But I get different results for the same input

更新:此功能有效.享受.

Update: This function works. Enjoy.

public static String base64sha256(String data, String secret) {
    String hash = null;
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] res = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        hash = getHex(res);
        hash = Base64.encodeToString(hash.getBytes("UTF-8"), Base64.NO_WRAP);
    } catch (Exception e){}
    return hash;
}

static final String HEXES = "0123456789abcdef";
public static String getHex( byte [] raw ) {
    if ( raw == null ) {
        return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
                .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

推荐答案

当第四个参数为false时,php函数的输出是小写的十六进制数字.但是,您的第二个 Java 版本会生成大写的十六进制数字.要么更正大小写差异,要么您可以将 hash_hmac 的第四个参数更改为 true,它可能会与您的第一个 Java 版本匹配.

The output of the php function are lowercase hex digits when the fourth parameter is false. Your second java version however produces uppercase hex digits. Either correct the case difference or you could change the fourth parameter of hash_hmac to true and it will probably match with your first Java version.

这篇关于为什么 PHP 的 hash_hmac('sha256') 给出的结果与 java sha256_HMAC 不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆