我在Java中执行以下操作时遇到了问题。下面是我正在使用的工具的文档中的Fantom代码。
// compute salted hmac
hmac := Buf().print("$username:$userSalt").hmac("SHA-1", password.toBuf).toBase64
// now compute login digest using nonce
digest := "${hmac}:${nonce}".toBuf.toDigest("SHA-1").toBase64
// our example variables
username: "jack"
password: "pass"
userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU="
nonce: "3da210bdb1163d0d41d3c516314cbd6e"
hmac: "IjJOApgvDoVDk9J6NiyWdktItl0="
digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s="我已经通过Google搜索了各种示例,但它们都没有给出文档声称应该返回的结果。
有Fantom知识的人可以验证文档中的示例是否正确吗?
至于Java方面,这是我最新的尝试
public static String hmacSha1(String value, String key) {
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes("UTF-8"));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}但是,当我使用以下参数调用该方法时
jack:6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU=
pass我得到了
22324e02982f0e854393d27a362c96764b48b65d发布于 2011-07-16 02:19:38
事实证明,这只是我自己缺乏知识,通过足够的尝试和错误,我能够通过执行以下操作来解决这个问题:
//username: "jack"
//password: "pass"
//userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU="
//nonce: "3da210bdb1163d0d41d3c516314cbd6e"
//hmac: "IjJOApgvDoVDk9J6NiyWdktItl0="
//digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s="
...
// initialize a Mac instance using a signing key from the password
SecretKeySpec signingKey = new SecretKeySpec(password.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// compute salted hmac
byte[] hmacByteArray = mac.doFinal((username + ':' + userSalt).getBytes());
String hmacString = new String(Base64.encodeBase64(hmacByteArray));
// hmacString == hmac
// now compute login digest using nonce
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update((hmacString + ':' + nonce).getBytes());
byte[] digestByteArray = md.digest();
String digestString = new String(Base64.encodeBase64(digestByteArray));
// digestString == digest使用org.apache.commons.codec.binary.Base64对字节数组进行编码。
发布于 2011-07-14 05:35:11
不知道这些文档是从哪里来的--但它们可能是过时的--或者是错误的。我实际上会运行Fantom代码作为您的参考,以确保您测试的是正确的东西;)
您可以查看sys::Buf.hmac的Java源:MemBuf.java
我还建议将这3个转换分开。确保您的原始字节数组在Fantom和Java中都匹配,然后验证摘要匹配,最后验证Base64编码。验证代码中的每个阶段要容易得多。
https://stackoverflow.com/questions/6685727
复制相似问题