gpt4 book ai didi

Java SHA1 输出与 Linux 的 sha1sum 命令不同

转载 作者:IT王子 更新时间:2023-10-29 00:16:45 27 4
gpt4 key购买 nike

我已尝试使用以下代码来生成字符串的 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 questionthis other question .请注意,这不是那些问题的重复,因为它们是关于格式化输出的。

问题是它产生的结果与在 Linux -> echo test|sha1sum 中通过 sha1sum 命令运行相同的输入字符串产生的结果不同。

“测试”的 Java 代码输出 -> a94a8fe5ccb19ba61c4c0873d391e987982fbbd3用于“测试”的 linux 终端中的 sha1sum -> 4e1243bd22c66e76c2ba9eddc1f91394e57f9f83

  • 为什么它们不一样?
  • Java 的 MessageDigest 类和 Linux 的 sha1sum 实用程序不是实现相同的算法吗?

最佳答案

问题是您如何在 Linux 下使用带有 echo 的 sha1sum。它包括换行符。将其拆分为多个步骤:

echo test > somefile
sha1sum somefile

会显示相同的结果...但是如果您查看 somefile,您会看到它的长度是 5 个字节,而不是 4 个字节。编辑它以删除尾随换行符,再次运行 sha1sum,您将看到 Java 给出的相同答案。

如果你为 echo 使用 -n 选项,应该没问题:

$ echo -n test | sha1sum
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 -

关于Java SHA1 输出与 Linux 的 sha1sum 命令不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27527028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com