C#vs Java HmacSHA1,然后是base64
我有一个java代码示例,使用HMAC-SHA1算法(RFC2104.)计算摘要,然后使用Base64编码(RFC2045)进行编码 下面是java代码C#vs Java HmacSHA1,然后是base64,c#,java,base64,hmacsha1,C#,Java,Base64,Hmacsha1,我有一个java代码示例,使用HMAC-SHA1算法(RFC2104.)计算摘要,然后使用Base64编码(RFC2045)进行编码 下面是java代码 public static String buildDigest(String key, String idString) throws SignatureException { try { String algorithm = "HmacSHA1"; Charset charset = Charset.forName("
public static String buildDigest(String key, String idString) throws SignatureException {
try {
String algorithm = "HmacSHA1";
Charset charset = Charset.forName("utf-8");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);
return new String(Base64.encodeBase64(mac.doFinal(idString.getBytes(charset))), charset);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
}
我在Stack Overflow中找到了答案,下面是C代码
我没有得到正确的结果,请尝试以下方法:
// This method will return the base 64 encoded string using the given input and key.
private string EncodeHMAC(string input, byte[] key)
{
HMACSHA1 hmac = new HMACSHA1(key);
byte[] stringBytes = Encoding.UTF8.GetBytes(input);
byte[] hashedValue = hmac.ComputeHash(stringBytes);
return Convert.ToBase64String(hashedValue);
}
我认为您没有正确地将散列值转换为64进制字符串 我使用此函数实现REST web服务调用的身份验证。 发送方和接收方使用相同的编码是很重要的 不幸的是,我花了一段时间才找到与此C#版本匹配的PHP Hamacim实现
private bool ValidateHash(字符串uid、字符串哈希、数据到签名数据){
StringBuilder strToSign=新建StringBuilder();
strToSign.Append(data.HttpMethod+'\n');
strToSign.Append(data.Date.ToString(“r”)+'\n');
strToSign.Append(data.Uri);
Byte[]secretBytes=UTF8Encoding.UTF8.GetBytes(this.\u secretKey);
HMACSHA1 hmac=新的HMACSHA1(secretBytes);
Byte[]dataBytes=UTF8Encoding.UTF8.GetBytes(strToSign.ToString());
字节[]calcHash=hmac.ComputeHash(数据字节);
字符串calcHashString=Convert.tobase64字符串(calcHash);
if(calcHashString.Equals(哈希)){
如果(log.IsDebugEnabled)log.Debug(uid+“-[ValidateHash]HMAC有效。”);
返回true;
}
返回false;
}
希望有帮助 为什么在Java版本中以字符串形式传递密钥?您确定Java方法
key.getBytes()
的结果与您在C版本中使用的字节数组等效吗?如果我正确理解了您的C#代码,它还会返回HMAC十六进制编码,而Java版本使用Base64。如果要使用字符串生成器,请不要在append方法中连接字符串!如果要在字符串末尾添加新行,请执行以下操作:strosign.AppendLine(data.HttpMethod)
@RobH你说得对-我写这篇文章已经有一段时间了。
// This method will return the base 64 encoded string using the given input and key.
private string EncodeHMAC(string input, byte[] key)
{
HMACSHA1 hmac = new HMACSHA1(key);
byte[] stringBytes = Encoding.UTF8.GetBytes(input);
byte[] hashedValue = hmac.ComputeHash(stringBytes);
return Convert.ToBase64String(hashedValue);
}