【问题标题】:Java byte array comparison of MessageDigest SHA1 result and original hash value?MessageDigest SHA1结果和原始哈希值的Java字节数组比较?
【发布时间】:2018-05-08 05:46:59
【问题描述】:

我想比较两个字节数组。一个是用MessageDigestSHA1从明文计算出来的,另一个是字节数组中的hex本身,不计算。

MessageDigest 返回 20 字节长的结果,String.getBytes() 返回 40 字节长的数组。 bytesToHex() 功能与this answer 提供的功能相同,仅用于打印。

问题:

如何在没有额外开销的情况下将字符串转换为字节数组(然后与使用MessageDigest 计算的数组进行比较)?与bytesToHex().toUppercase() 的字符串比较有效,但不是一个选项,因为速度在应用程序中至关重要。

代码:

 MessageDigest md;

    try {
        md = MessageDigest.getInstance("SHA-1");

        byte[] toEncode = "test".getBytes();
        byte[] encoded = md.digest(toEncode);

        System.out.println("String to encode:\t\t" + new String(toEncode));
        System.out.println("Encoded in hex:\t\t\t" + bytesToHex(encoded));
        System.out.println("Encoded length:\t\t\t" + encoded.length);


        byte[] hash = new String("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3").getBytes(); // "test" representation in SHA1

        System.out.println("\nHash to compare with:\t\t" + new String(hash));
        System.out.println("Hash length:\t\t\t" + hash.length);
        System.out.println("Two byte array equals:\t\t" + Arrays.equals(hash, encoded));
        System.out.println("Two equals in string:\t\t" + new String(hash).equals(bytesToHex(encoded).toLowerCase()));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

结果:

String to encode:           test
Encoded in hex:             A94A8FE5CCB19BA61C4C0873D391E987982FBBD3
Encoded length:             20

Hash to compare with:       a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
Hash length:                40
Two byte array equals:      false
Two equals in string:       true

【问题讨论】:

    标签: java arrays compare message-digest


    【解决方案1】:

    您没有将十六进制表示解码为字节。如果您愿意,例如使用来自 this answer 的解决方案,这两个数组将匹配:

    try {
        byte[] encoded = MessageDigest.getInstance("SHA-1").digest("test".getBytes());
        byte[] hash = DatatypeConverter.parseHexBinary("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3");
    
        System.out.println("Two byte array equals:\t\t" + Arrays.equals(hash, encoded));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 2019-06-10
      • 2017-04-30
      • 2013-05-09
      • 1970-01-01
      相关资源
      最近更新 更多