Kev*_*vin 34 asp.net security android sha asp.net-web-api
我试图在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();
}
Run Code Online (Sandbox Code Playgroud)
以及这里的服务器代码(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();
}
Run Code Online (Sandbox Code Playgroud)
更新: 这是更正的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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10014 次 |
| 最近记录: |