【问题标题】:Java SHA1 output not the same as Linux's sha1sum commandJava SHA1 输出与 Linux 的 sha1sum 命令不同
【发布时间】: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 questionthis other question。请注意,这不是这些问题的重复,因为它们是关于格式化输出的。

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

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

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

【问题讨论】:

    标签: java linux sha1


    【解决方案1】:

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

    echo test > somefile
    sha1sum somefile
    

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

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

    $ echo -n test | sha1sum
    a94a8fe5ccb19ba61c4c0873d391e987982fbbd3  -
    

    【讨论】:

    • 5 分钟内回复你会得到一个秘密帽子吗?好一个:-)
    • 我自己对sha1sum也有同样的问题,与Java无关;我的问题是PHP。很高兴找到你的答案。
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2018-09-20
    • 2012-10-12
    • 2011-10-26
    相关资源
    最近更新 更多