0

一个贸易伙伴要求我发送一个 HMAC SHA1 哈希作为小写 heaxits。我能找到的唯一参考是关于 PHP。我可以在 .NET 和 Java 中进行散列,但是如何用它们输出“小写十六进制”?小写十六进制似乎不等同于 Base64。

4

3 回答 3

2

啊! 我喜欢简单。这是解决方案。

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 函数兼容。

于 2013-11-04T01:13:00.600 回答
1

对于小写十六进制数字(hexits),请使用:

public static String toHex(byte[] bytes) {
    BigInteger bi = new BigInteger(1, bytes);
    return String.format("%0" + (bytes.length << 1) + "x", bi);
}

来自相关问题: 在 Java 中,如何将字节数组转换为十六进制数字字符串,同时保持前导零?

于 2013-11-01T08:07:09.460 回答
0

这是 sedge 解决方案的 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;
}
于 2015-11-29T15:18:43.097 回答