java - char[] -> String -> bytes[] -> String...我迷路了

标签 java hash sha

我想做的是将输入到 jPasswordField 中的密码转换为 SHA-256 哈希值。我四处闲逛,发现如果我将密码保存为字符串,但我使用的字段返回 char[] ,该怎么做,所以我最终只是猜测该怎么做......起初,即使密码相同,我也会得到不同的结果,但现在我相信我更接近了,因为它是一个常量;但它仍然不是它的输出

echo -n 'abc' | sha256sum

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

而我的操作的输出(对于相同的输入)是

86900f25bd2ee285bc6c22800cfb8f2c3411e45c9f53b3ba5a8017af9d6b6b05

我的操作如下所示:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        NoSuchAlgorithmException noSuchAlgorithmException = null;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");

        } catch (NoSuchAlgorithmException ex) {
            noSuchAlgorithmException = ex;
        }
        if (noSuchAlgorithmException != null) {
            System.out.println(noSuchAlgorithmException.toString());
        }
        else {
            UnsupportedEncodingException unsupportedEncodingException = null;
            byte[] hash = null;
            char[] password = jPasswordField1.getPassword();
            StringBuffer stringBuffer = new StringBuffer();
            for (char c : password) {
                if (c > 0 && c < 16) {
                    stringBuffer.append("0");
                }
                stringBuffer.append(Integer.toHexString(c & 0xff));
            }
            String passwordString = stringBuffer.toString();
            try {
                hash = messageDigest.digest(passwordString.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                unsupportedEncodingException = ex;
            }
            if (unsupportedEncodingException != null) {
                System.out.println(unsupportedEncodingException.toString());
            }
            else {
                stringBuffer = new StringBuffer();
                for (byte b : hash) {
                    stringBuffer.append(String.format("%02x", b));
                }
                String passwordHashed = stringBuffer.toString();
                System.out.println(passwordHashed);
            }
        }

有什么想法吗?

最佳答案

你已经成功了。只是采取了从 char[] 转换为 String 的困难/错误的方式 -> new String(password) 就是你所需要的。 (提示,如果您发现自己在字节和字符之间手动转换,则可能做错了)。

顺便说一句,“抛出”异常是有原因的。这使得很容易跳过下面的代码,这些代码在引发异常时不应执行。通过捕获异常并将其转换为“if” block ,您可以使代码变得比需要的更复杂。

关于java - char[] -> String -> bytes[] -> String...我迷路了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802746/

相关文章:

java - 快速理论 : Way to create generator from a list

java - 使用涉及复杂标准的 JPA Criteria API 进行分页

java - 创建对象使 VM 更快?

scala - spark中的哈希函数

Perl "keys on reference is experimental"警告

c++ - MurmurHash 函数不具有确定性

java - 与 Guice 0 耦合获取多个新实例

elasticsearch - 什么 shasum : elasticsearch-5. 0.0.deb.sha1 : no properly formatted SHA1 checksum lines found means?

asp.net - ASP.NET 使用 SHA256 还是 SHA1?

java - 启用 Java sha1 原始模式,如 php sha1