Java HmacSHA256 with key

半腔热情 提交于 2019-12-04 21:38:31
    String key = "0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6";
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    sha256_HMAC.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
    byte[] result = sha256_HMAC.doFinal("example".getBytes());
    System.out.println (DatatypeConverter.printHexBinary(result));
    // ONLY CONVERT TO HEX (= SWIFT) NOT FIRST TO BASE64

result as requested

 27EFFB76C97022497E25D3A5D7E823462F212A82D9EBBA35F179071568B0C335

Your key contains values greater then the value 127 and, Mac and SecretKeySpec use bytes, which in Java can contain values from -128 to 127.


In the HmacSHA256 algorithm, the key is interpreted as a string of hexadecimal values. In the case of your secret, the decimal values of this key are: 3,147,233,68,238,129,8,187,102,252,159,164,249,159,156,134,36,129,233,224,81,158,24,35,43,166,27,7,103,238,232,198

As you can see, some of them have a value over 127. When creating the SecretKeySpec object and while doing calculations within the Mac class, Java uses byte[] to store this and related sequences. In Java, a byte can contain values from -128 to 127, which means that when storing this secret, the values > 127 will "flip" and will make sure the calculations following this will not go as you'd expect.

In the Swift case (and with C++, Ruby, and other languages), the conversion from hex to byte occurs without losing the actual value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!