public static String hmacsha256(String plainStr, String key) { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), "HmacSHA256"); Mac mac=null; try { mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } byte digest[] = mac.doFinal(plainStr.getBytes(Charset.forName("UTF- 8"))); return new StringBuilder().append(byte2HexStr(digest)).toString(); } public static String byte2HexStr(byte array[]) { return array != null ? new String(Hex.encodeHex(array)) : null; } java to PHP
时间: 2023-03-04 19:25:38 浏览: 299
Here's the PHP equivalent of the Java code for computing HMAC-SHA256:
```
function hmacsha256($plainStr, $key) {
$secretKey = utf8_encode($key);
$digest = hash_hmac('sha256', utf8_encode($plainStr), $secretKey, true);
return bin2hex($digest);
}
```
Note that in PHP, the `hash_hmac` function is used to compute the HMAC with SHA256. The third parameter of `hash_hmac` is set to `true` to get the output as raw binary data. The `bin2hex` function is then used to convert the binary data to a hexadecimal string, which is the same format as the output of the `byte2HexStr` function in the Java code.
Also note that in PHP, strings are already represented as Unicode, so there's no need to convert the key and plain string to UTF-8 encoding using the `Charset.forName("UTF-8")` method.
阅读全文