title: Which SHA-256 is correct? The Java SHA-256 digest or the Linux commandline tool
body: <p>When I calculate in Java an SHA-256 of a string with the following method </p>
  
  <pre><code>public static void main(String[] args) throws NoSuchAlgorithmException {
  
      MessageDigest md = MessageDigest.getInstance("SHA-256");
  
      byte[] hash = md.digest("password".getBytes());
  
      StringBuffer sb = new StringBuffer();
      for(byte b : hash) {
          sb.append(Integer.toHexString(b &amp; 0xff));
      }
  
      System.out.println(sb.toString());
  }
  </code></pre>
  
  <p>I get :</p>
  
  <pre><code>5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d8
  </code></pre>
  
  <p>on the commandline I do the following (I need the <code>-n</code> to not add a newline) :</p>
  
  <pre><code>echo -n "password" | sha256sum
  </code></pre>
  
  <p>and get</p>
  
  <pre><code>5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
  </code></pre>
  
  <p>if we compare these more closely I find 2 subtle differences</p>
  
  <pre><code>5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d8
  5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
  </code></pre>
  
  <p>or :</p>
  
  <pre><code>5e884898da28   47151d0e56f8dc6292773603d   d6aabbdd62a11ef721d1542d8
  5e884898da28 0 47151d0e56f8dc6292773603d 0 d6aabbdd62a11ef721d1542d8
  </code></pre>
  
  <p>Which of the 2 is correct here?</p>
  
  <p><strong>Result:</strong> Both are but I was wrong...</p>
  
  <p>fixed it by using :</p>
  
  <pre><code>    StringBuffer sb = new StringBuffer();
      for(byte b : hash) {
          sb.append(String.format("%02x", b));
      }
  </code></pre>
  
  <p>Thanks!</p>