2013-11-01 23 views
0

貿易伙伴要求我發送HM​​AC SHA1哈希作爲小寫heaxits。我能找到的唯一參考是關於PHP的。我可以在.NET和Java中執行哈希,但是如何輸出「小寫hexits」?小寫hexits看起來不等於Base64。小寫六進制。 .NET和Java等效

回答

1

小寫的十六進制數字(hexits)使用方法:

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

從相關的問題: In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

+0

感謝堆了點。有誰知道如何在.NET 3.5中做到這一點? BigInteger僅在.NET中引入.NET。 – sedge

+0

完美地工作!謝謝! –

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

0

這裏的莎草科的解決方案的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; 
}