【发布时间】:2015-02-16 02:04:11
【问题描述】:
我已尝试使用以下代码生成字符串的 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"));
}
}
此代码基于this question 和this other question。请注意,这不是这些问题的重复,因为它们是关于格式化输出的。
问题在于它产生的结果与在 Linux 中通过 sha1sum 命令运行相同的输入字符串不同 -> echo test|sha1sum。
“测试”的 Java 代码输出 -> a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
用于“测试”的 Linux 终端中的 sha1sum -> 4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
- 为什么它们不一样?
- Java 的
MessageDigest类和 Linux 的sha1sum实用程序不实现相同的算法吗?
【问题讨论】: