我试图在android中生成SHA256哈希,然后将其传递给ASP.NET Web API Web服务并在那里比较哈希。这样,我需要在Android中构造一个哈希,因为ASP.NET中的相同输入将生成等效的哈希。我正在拔头发试图找出我做错了什么。
这是Android代码:
public String computeHash(String input) throws NoSuchAlgorithmException{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
try{
digest.update(input.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
byte[] byteData = digest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++){
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
这是服务器上的代码(C#):
private static string ComputeHash(string input, HashAlgorithm algorithm)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashedBytes.Length; i++)
{
sb.Append(String.Format("{0:x2}", hashedBytes[i]));
}
return sb.ToString();
}
更新:
这是更正的Android / Java实现(感谢Nikolay Elenkov):
public String computeHash(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] byteData = digest.digest(input.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++){
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
最佳答案
您的Java代码有误:您将输入字节相加两次。如果要一次性计算,则只需要调用digest(bytes)
或在digest()
之后调用update(bytes)
即可;