一个贸易伙伴要求我发送一个HMAC SHA1哈希作为小写的heaxits。我能找到的唯一参考是与PHP有关。我可以在 .NET 和 Java 中进行哈希处理,但是如何使用它们输出"小写 hexits"?小写十六进制似乎不等同于 Base64。
啊!我喜欢简单。这是解决方案。
Public Shared Function Encrypt(ByVal plainText As String, ByVal preSharedKey As String) As String
Dim preSharedKeyBytes() As Byte = Encoding.UTF8.GetBytes(preSharedKey)
Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
Dim hmac = New HMACSHA1(preSharedKeyBytes)
Dim cipherTextBytes As Byte() = hmac.ComputeHash(plainTextBytes)
Dim strTemp As New StringBuilder(cipherTextBytes.Length * 2)
For Each b As Byte In cipherTextBytes
strTemp.Append(Conversion.Hex(b).PadLeft(2, "0"c).ToLower)
Next
Dim cipherText As String = strTemp.ToString
Return cipherText
End Function
这与 raw_output 参数中带有 FALSE 的 PHP hash_hmac 函数兼容。
对于小写十六进制数字(hexits),请使用:
public static String toHex(byte[] bytes) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bi);
}
来自相关问题:在 Java 中,如何在保持前导零的同时将字节数组转换为十六进制数字字符串?
以下是莎草解决方案的 C# 翻译:
private static String toHex(byte[] cipherTextBytes)
{
var strTemp = new StringBuilder(cipherTextBytes.Length * 2);
foreach(Byte b in cipherTextBytes)
{
strTemp.Append(Microsoft.VisualBasic.Conversion.Hex(b).PadLeft(2, '0').ToLower());
}
String cipherText = strTemp.ToString();
return cipherText;
}