0

http://www.sha1-online.com/ , http://passwordsgenerator.net/sha1-hash-generator/ , http://www.miraclesalad.com/webtools/sha1.php

-all return 40BD001563085FC35165329EA1FF5C5ECBDBBEEF for the SHA-1 of 123

However, with my code:

public static String SHA1(String clearString)
{
    try
    {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.update(clearString.getBytes("UTF-8"));
        byte[] bytes = messageDigest.digest();
        StringBuilder buffer = new StringBuilder();
        for (byte b : bytes)
        {
            buffer.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return buffer.toString();
    }
    catch (Exception ignored)
    {
        ignored.printStackTrace();
        return null;
    }
}

and many other codes I've tried, I get something different. With the above code I get: 9c9598069a40434b500d862e1a13ab9d5a969fc8 for 123.

Seeing that all sites use the same algorithm, it seems like I'm doing something wrong.

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
  • 1
    Try [this approach for generating the output](https://stackoverflow.com/a/2197650/115145). – CommonsWare Jul 25 '17 at 21:48
  • Possible duplicate of [Java's MessageDigest SHA1-algorithm returns different result than SHA1-function of php](https://stackoverflow.com/questions/7605217/javas-messagedigest-sha1-algorithm-returns-different-result-than-sha1-function) – maszter Jul 25 '17 at 21:50
  • @CommonsWare but what if I want a String as a parameter? – Ali Bdeir Jul 25 '17 at 21:51
  • @maszter your comment points to an answer that 0s are being replaced with nothing. Which is not happening in my case. – Ali Bdeir Jul 25 '17 at 21:52
  • "but what if I want a String as a parameter?" -- I do not understand what you mean. That being said, j2ko's answer gets to my concern: replacing your `byte[]`-to-hex conversion with something else. BTW, I seriously hope that you are not using SHA-1 for anything related to security, as it's obsolete. – CommonsWare Jul 25 '17 at 22:09

1 Answers1

2

Looks like the problem is in the way you converting to String.

public static String byteArrayToString(byte[] bytes) {
    StringBuilder buffer = new StringBuilder();
    for (byte b : bytes) {
        buffer.append(String.format(Locale.getDefault(), "%02x", b));
    }
    return buffer.toString();
}

public static String SHA1(String clearString)
{
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.update(clearString.getBytes("UTF-8"));
        return byteArrayToString(messageDigest.digest());
    } catch (Exception ignored) {
        ignored.printStackTrace();
        return null;
    }
}

So SHA1("123") will result in : 40bd001563085fc35165329ea1ff5c5ecbdbbeef

j2ko
  • 2,479
  • 1
  • 16
  • 29