Java SHA1 output does not match Linux sha1sum command

I tried the following code to create 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 . Please note that this is not a duplicate of these questions, as they concern output formatting.

The problem is that it produces a different result than executing the same input line using the 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?
  • Does the Java MessageDigest class and Linux sha1sum utility use the same algorithm?
+6
source share
1 answer

The problem is how you use sha1sum on Linux with an echo. It includes a feed line. To break it down into stages:

 echo test > somefile sha1sum somefile 

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

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

 $ echo -n test | sha1sum a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 - 
+15
source

Source: https://habr.com/ru/post/979785/


All Articles