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; } 转为 PHP
时间: 2023-03-02 20:59:08 浏览: 161
HmacSHA256加密.rar
以下是将Java代码转换为PHP代码的实现:
```php
function hmacsha256($plainStr, $key) {
$secretKey = new \SecretKeySpec(utf8_encode($key), "HmacSHA256");
$mac = null;
try {
$mac = \Mac::getInstance($secretKey->getAlgorithm());
$mac->init($secretKey);
} catch (\NoSuchAlgorithmException | \InvalidKeyException $e) {
echo $e->getMessage();
}
$digest = $mac->doFinal(utf8_encode($plainStr));
return byte2HexStr($digest);
}
function byte2HexStr($array) {
return $array != null ? bin2hex($array) : null;
}
```
注意,该PHP代码需要使用PHP 7.1或更高版本,因为它使用了PHP 7.1中的二进制字面量语法。另外,还需要确保已经加载了Hex编码器。
阅读全文