2017-11-24 9 views
2

2バイト配列を比較したいと思います。 1つは平文からMessageDigest SHA1で計算され、もう1つは計算なしでバイト配列の16進数です。MessageDigestのSHA1結果と元のハッシュ値のJavaバイト配列の比較?

MessageDigestは、20バイト長の結果を返します。String.getBytes()は、40バイト長の配列を返します。 bytesToHex()の機能は、this answerで提供されたものと同じで、印刷にのみ使用されます。

質問:

私は追加のオーバーヘッドなしに、配列をバイト(その後、MessageDigestで計算1と比較)する文字列を変換するにはどうすればよいですか? 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(); 
    } 

結果:あなたはバイトに、あなたの16進数表現をデコードしていない

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 

答えて

3

。たとえば、this answerのソリューションを使用する場合、2つの配列は一致します。

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(); 
} 
関連する問題