title: MessageDigest hashes differently on different machines
body: <p>I'm having a problem with MessageDigest returning different hash values on different computers.</p>
  
  <p>One computer is running 32-bit Java on Windows Vista and the other is running 64-bit Java on Mac OS.  I'm not sure if it is because MessageDigest is machine dependent, or I need to  explicitly specify a character encoding somewhere, or perhaps something else. Here's the
  code:</p>
  
  <pre><code>public static boolean authenticate(String salt, String encryptedPassword, 
      char[] plainTextPassword ) throws NoSuchAlgorithmException {
  
      // do I need to explcitly specify character encoding here? --&gt;
      String saltPlusPlainTextPassword = salt + new String(plainTextPassword);
  
      MessageDigest sha = MessageDigest.getInstance("SHA-512");
  
      // is this machine dependent? --&gt;
      sha.update(saltPlusPlainTextPassword.getBytes());
      byte[] hashedByteArray = sha.digest();
  
      // or... perhaps theres a translation problem here? --&gt;
      String hashed = new String(hashedByteArray);
  
      return hashed.equals(encryptedPassword);
  }
  </code></pre>
  
  <p>Should this code execute differently on these two different machines?
  If it is machine dependent the way I've written it, is there another way hash these passwords that is more portable?  Thanks!</p>
  
  <h2>Edit:::::</h2>
  
  <p>This is the code I'm using to generate the salts:</p>
  
  <pre><code>public static String getSalt() {
     int size = 16;
     byte[] bytes = new byte[size];
     new Random().nextBytes(bytes);
     return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(bytes);
  }
  </code></pre>
  
  <h2>Solution:::</h2>
  
  <p>Thanks to the accepted solution, I was able to fix my code:</p>
  
  <pre><code>public static boolean authenticate_(String salt, String encryptedPassword, 
          char[] plainTextPassword ) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  
          // This was ok
          String saltPlusPlainTextPassword = salt + new String(plainTextPassword);    
  
          MessageDigest sha = MessageDigest.getInstance("SHA-512");
  
          // must specify "UTF-8" encoding
          sha.update(saltPlusPlainTextPassword.getBytes("UTF-8"));
          byte[] hashedByteArray = sha.digest();
  
          // Use Base64 encoding here --&gt;
          String hashed = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(hashedByteArray);
  
          return hashed.equals(encryptedPassword);
      }
  </code></pre>