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?
source share