我已经尝试了以下代码来生成String的SHA1摘要:
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
此代码基于此问题和另一个问题.请注意,这不是这些问题的重复,因为它们是关于格式化输出.
问题是它产生的结果与sha1sum在Linux中通过命令运行相同的输入字符串不同- > echo test|sha1sum.
Java代码输出为"test" - > a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
linux终端中的sha1sum为"test" - >4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
MessageDigest类和Linux的sha1sum实用程序是否实现相同的算法?Jon*_*eet 20
问题是你如何sha1sum在Linux下使用echo.它包括换行.将其拆分为以下步骤:
echo test > somefile
sha1sum somefile
Run Code Online (Sandbox Code Playgroud)
会显示相同的结果...但如果你看看somefile你会看到它长5个字节而不是4个.编辑它以摆脱拖尾换行,sha1sum再次运行你会看到Java给出的相同答案.
如果你使用的-n选项echo,它应该是好的:
$ echo -n test | sha1sum
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 -
Run Code Online (Sandbox Code Playgroud)