Convert ComputeHash using SHA1 algorithm in C# to Java
Convert ComputeHash using SHA1 algorithm in C# to Java
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;
}
Possible duplicate of Java String to SHA1
– M. Schena
Jun 29 at 9:52
What did you already try, and where are you stuck?
– Mark Rotteveel
Jun 29 at 14:50
Hi, and welcome to StackOverflow. If you want to understand why your Java code produces different output you should edit your post to include the Java code along with a simple test input string and the outputs you get from the two pieces of code. See How to Ask and Minimal, Complete, and Verifiable example for more hints on asking effective questions. On the other hand, if you just want some Java code that works there are many SO posts tagged with 'java' and 'sha1' … stackoverflow.com/questions/tagged/java+sha1
– Frank Boyne
2 days ago
1 Answer
1
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 !
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
just as side-note: SHA1 is no longer secure computerworld.com/article/3173616/security/…
– M. Schena
Jun 29 at 9:43