0

I am hashing string using SHA-256. I want to find out if the any byte matches certain value. I am using

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(message.getBytes(StandardCharsets.UTF_8));
 for(byte c : hash) {
    if( String.format("%02X ",c) == "69" || String.format("%02X ",c) == "CB" ) {
        ...
    }
     System.out.println(String.format("%02X ",c));

 }    

Here i want to check if any of bytes equals 69 or CB in hexa. However this condition is never set to true even if those bytes actually represet those values. Is ther any special way how to compare bytes with certain value?

thanks for help.

Darlyn
  • 4,715
  • 12
  • 40
  • 90
  • 3
    Why would you format the value at all? Why not just use `if (hash[0] == (byte) 0x69 || hash[0] == (byte) 0xcb)`? (Note that your *text* talks about the first byte, but you're actually looking through *every* byte.) Basically, don't do string conversions unnecessarily. – Jon Skeet Mar 23 '17 at 13:32
  • It works , thanks! ( I noticed first sentence thanks for pointing out) – Darlyn Mar 23 '17 at 13:37
  • 2
    Jon is right, of course. But the reason why your original code doesn't work is because you are using `==` to compare strings. That does not do what you think it does in Java. See: [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jesper Mar 23 '17 at 13:44

0 Answers0