I have a function to encrypt a string with the SHA1 algorithm in C#. And now I would like to convert exactly it to Java language. I have tried, but I don't get the same output for C# and Java.
Someone kindly please help me convert it. I'm really grateful for this. Thanks.
Here is C# code :
public static string ComputeHash(string inString) {
SHA1 sh = SHA1.Create();
byte[] data = UTF8Encoding.UTF8.GetBytes(inString);
byte[] result = sh.ComputeHash(data);
return ToHexString(result);
}
public static string ToHexString(byte[] data) {
string s = "";
for (int i = 0, n = data.Length; i < n; i++) {
s += String.Format("{0:X2}", data[i]);
}
return s;
}
I've changed code and get same output for C# and Java. Here is my Java Code :
public static String ComputeHash(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(password.getBytes("UTF-8"));
return toHexString(md.digest());
}
private static String toHexString(byte[] data){
Formatter formatter = new Formatter();
for(byte b : data){
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
With same string input : "abc123", I got same result : 6367C48DD193D56EA7B0BAAD25B19455E529F5EE
Thanks M. Schena , I got my solution in your comment. Thank so much !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.