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

Java SHA1 output not the same as Linux's sha1sum command

我尝试了以下代码来生成String的SHA1摘要:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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"));

    }
}

这段代码是基于这个问题和另一个问题的。 请注意,这不是这些问题的重复,因为它们与格式化输出有关。

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

"测试"的Java代码输出-> a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
Linux终端中的sha1sum用于"测试"-> 4e1243bd22c66e76c2ba9eddc1f91394e57f9f83

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

问题是您如何在Linux下使用带有回显的sha1sum。 其中包括换行符。 分成几个步骤:

1
2
echo test > somefile
sha1sum somefile

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

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

1
2
$ echo -n test | sha1sum
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3  -