Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SHA1 output not the same as Linux's sha1sum command

Tags:

java

linux

sha1

I've tried the following code to produce a SHA1 digest of a String:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class SHA1 {
    private static String encryptPassword(String password)
    {
        String sha1 = "";
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(password.getBytes("UTF-8"));
            sha1 = byteToHex(crypt.digest());
        }
        catch(NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return sha1;
    }

    private static String byteToHex(final byte[] hash)
    {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static void main(String args[]){
        System.out.println(SHA1.encryptPassword("test"));

    }
}

This code was based on this question and this other question. Note that this is not a duplicate of those questions since they are about formatting the output.

The problem is that it produces a different result than running the same input string through sha1sum command in Linux -> echo test|sha1sum.

Java code output for "test" -> a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 sha1sum in linux terminal for "test" -> 4e1243bd22c66e76c2ba9eddc1f91394e57f9f83

  • Why aren't they the same ?
  • Don't Java's MessageDigest class and Linux's sha1sum utility implement the same algorithm ?
like image 422
Tulains Córdova Avatar asked Dec 17 '14 13:12

Tulains Córdova


1 Answers

The problem is how you're using sha1sum under Linux with echo. It's including the line feed. To split it into steps:

echo test > somefile
sha1sum somefile

will show you the same result... but if you look at somefile you'll see it's 5 bytes long instead of 4. Edit it to get rid of the trailing line feed, run sha1sum again and you'll see the same answer that Java gives.

If you use the -n option for echo, it should be fine:

$ echo -n test | sha1sum
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3  -
like image 128
Jon Skeet Avatar answered Oct 02 '22 19:10

Jon Skeet