0

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;
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
AcidBurn
  • 73
  • 2
  • 15
  • just as side-note: SHA1 is no longer secure https://www.computerworld.com/article/3173616/security/the-sha1-hash-function-is-now-completely-unsafe.html – M. Schena Jun 29 '18 at 09:43
  • Possible duplicate of [Java String to SHA1](https://stackoverflow.com/questions/4895523/java-string-to-sha1) – M. Schena Jun 29 '18 at 09:52
  • What did you already try, and where are you stuck? – Mark Rotteveel Jun 29 '18 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 [ask] and [mcve] 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' … https://stackoverflow.com/questions/tagged/java+sha1 – Frank Boyne Jun 29 '18 at 16:51

1 Answers1

0

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 !

AcidBurn
  • 73
  • 2
  • 15