public static String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException, java.security.NoSuchAlgorithmException,
java.security.InvalidKeyException {
String result;
// get an hmac_sha1 key from the raw key bytes javax.crypto.spec.SecretKeySpec
signingKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), \"HmacSHA256\");
// get an hmac_sha1 Mac instance and initialize with the signing key javax.crypto.Mac
mac = javax.crypto.Mac.getInstance(\"HmacSHA256\"); mac .init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac .doFinal(data.getBytes());
// base64-encode the hmac
result = org.apache.commons.codec.binary.Base64.encodeBase64String(rawHmac);
result = java.net.URLEncoder.encode(result.trim(),\"UTF-8\");
return result;
}
我很难将此算法应用到Javascript中。 我有一个例子可以使用,但我一路上做错了,它永远不会输出正确的hash_code。
这是我必须使用的示例测试用例。
数据: V2 /资产ipGLN = 1234&安培; senderGLN = 1234&安培; APP_ID = 3cea2db2&安培; TIMESTAMP = 2012-12- 06T13:08:02Z
键:6b904a0c5ceefa991b2ebc9cfec202b6
生成的哈希码,即结果:4F7rjpsRpR0IEy12EfAFShjS9VOxpisVgb8ywavqRrI%3D
因此,使用hash_code参数的请求URL将为:
如果有人对正确实施上述内容有任何见解,我将不胜感激。
到目前为止,这是我的实施。
var temp_test_key = "";
var test_key_bytes = encodeTextToUtf8(test_key);
for(var i = 0;i<test_key_bytes.length;i++)
{
temp_test_key+= test_key_bytes[i];
}
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256,temp_test_key);
hmac.update(test_string);
var hash = hmac.finalize();
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
document.write(hashInBase64);
谢谢。
我甚至试图将其重做为vb.net ..但它仍然不是同样的结果..
Function SignMessage(key As String, message As String) As Byte()
Dim encText As New System.Text.UTF8Encoding
Dim btKey() As Byte, btMessage() As Byte
btKey = encText.GetBytes(key)
Dim myhmac As New HMACSHA256(btKey)
btMessage = encText.GetBytes(message)
Return myhmac.ComputeHash(btMessage)
End Function
Sub Main()
Dim testString As String = "V2/assets?ipGLN=1234&senderGLN=1234&app_id=3cea2db2&TIMESTAMP=2012-12-06T13:08:02Z"
Dim Hash() As Byte = SignMessage("6b904a0c5ceefa991b2ebc9cfec202b", testString)
MsgBox(System.Convert.ToBase64String(Hash, 0, Hash.Length))
End Sub