2017-11-24 5 views
2

2 바이트 배열을 비교하고 싶습니다. 하나는 평문에서 MessageDigest SHA1으로 계산되며, 다른 하나는 계산없이 바이트 배열의 16 진수 자체입니다.MessageDigest SHA1 결과와 원래 해시 값의 Java 바이트 배열 비교?

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 

답변

3

. 예를 들어 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(); 
}