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'ssha1sum
utility implement the same algorithm ?