我想弄清楚为什么 openssl 中的 hmac 没有给我与 java 中的 hmac 相同的结果。
在开放的 ssl 中
echo -n "Hello" | openssl dgst -sha256 -hmac 04d6b077d60e323711b37813b3a68a71
输出: cc598d8840fe409d5fcc1c1c856f9e8c311d1c458850615555857b023f1cd94c
在Java中
String key = "04d6b077d60e323711b37813b3a68a71"
SecretKeySpec key2 = new SecretKeySpec(Hex.decode(key), "RAW");
String data = "Hello";
Mac hmac = Mac.getInstance("Hmac-SHA256", BouncyCastleProvider.PROVIDER_NAME);
hmac.init(key2)
byte[] bytes = hmac.doFinal(data.getBytes());
System.out.println(Hex.toHexString(bytes));
输出: 877f9c8eb44c20987e3978928fbfcea0f1cf99c88f9db904596921b7ecf0613b
我不知道为什么这些不同。
最佳答案
OpenSSL 将 -hmac key
选项视为 key 只是表示为相应 ASCII 字符的字节数组。因此, key 仅限于包含可打印字符。
您可以在 Java 中获得与在 OpenSSL 中相同的结果,方法是使用
SecretKeySpec key2 = new SecretKeySpec( key.getBytes("ASCII"), "RAW" );
或者,您可以使用 openssl dgst -sha256 -mac HMAC -macopt hexkey:string
,其中 string
将被视为 HEX 编码 key 。
关于java - OpenSSL Hmac 和 BouncyCaSTLe Hmac 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541465/