我试图在android中生成一个SHA256哈希,然后将其传递给ASP.NET API Web服务,并比较其中的哈希值.因此,我需要在Android中构造一个哈希,在ASP中提供相同的输入.NET将生成一个等价的哈希.我拼命想弄清楚我做错了什么.
以下是Android代码:
public String computeHash(String input) throws NoSuch算法rithmException{
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, Hash算法rithm 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();
}
UPDATE:
public String computeHash(String input) throws NoSuch算法rithmException, 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();
}