0

With Java, I am converting a String value to a hash using SHA1 on a MessageDigest instance. I am at the point where I have created a hash object:

MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] hash = md.digest(password.getBytes("UTF-8"));

The part I do not understand is what b & 0xff means in the following code:

StringBuilder sb = new StringBuilder(2*hash.length);
for(byte b : hash) {
   sb.append(String.format("%02x", b & 0xff));
}

I know that %02x means to specify a format where there are two characters using hexadecimal, but I've no idea what the second parameter is, what it does to each byte or what it means. A simple explanation would be great! :-)

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jonny Stewart
  • 161
  • 1
  • 5
  • 13
  • Random side note: if you can use third-party libraries, this whole thing is the one line `Hashing.sha1().hashString(password, Charsets.UTF_8).toString()` with [Guava](https://code.google.com/p/guava-libraries/). – Louis Wasserman Aug 13 '13 at 17:36

1 Answers1

2

That's the bitwise AND operator. b & 0xff gets the last byte of b. Since b is already a byte, I don't see any point to this: the result of the String.format is the same.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373