title: How SHA-1 hashing works on Java on Android
body: <p>I searched around for how to hash device identifiers and stumbled on the following code.</p>
  
  <p>I don't really understand what it's doing.</p>
  
  <ol>
  <li>Why do I need to urlEncode the device id ?</li>
  <li>Why do I need to hash the bytes, couldn't I just do that on a String ?</li>
  <li>Why do I need to convert it to a BigInteger ?</li>
  <li>Why do I need to shift bits to get a String with the hashed id ?  </li>
  </ol>
  
  <p>Can anyone explain what's going on line by line? I hope this will help other people understand this snippet that's getting passed around in blogs and forums, too.</p>
  
  <pre><code>String hashedId = "";
  
  String deviceId = urlEncode(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID));
  
  try {
      MessageDigest digest = MessageDigest.getInstance("SHA-1");
  
      byte bytes[] = digest.digest(deviceId.getBytes());
  
      BigInteger b = new BigInteger(1, bytes);
      hashedId = String.format("%0" + (bytes.length &lt;&lt; 1) + "x", b);
  
  } catch (NoSuchAlgorithmException e) {
      //ignored
  }
  
  return hashedId;
  </code></pre>