title: Read Encrypted Password in Java
body: <p>I have the following code in javascript / nodejs that encrypt passwords. I need to read these passwords in java:</p>
  <pre><code>encryptPassword: function(password, salt) {
      var salt = new Buffer(salt, 'base64');
      return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64');
  }
  </code></pre>
  <p>I Used this method to create encrypted password for testing. this is the result (as java variables):</p>
  <pre><code>static String password = &quot;123456&quot;;
  static String salt = &quot;CPvFo+klD9Vh2iE07JEGXA==&quot;;
  public final String encrypted = &quot;LtStqkNQjrr+P4V8fGtnauNJNOIB7t35O5I4a4/I9lFUnMR3ckbZyT85g/wO0Da9318Wrql/y1bsY2XdpXqx+Q==&quot;; 
  </code></pre>
  <p>I tried to tranalte the encryption code above to java, using this <a href="http://www.javacodegeeks.com/2012/05/secure-password-storage-donts-dos-and.html" rel="nofollow noreferrer">http://www.javacodegeeks.com/2012/05/secure-password-storage-donts-dos-and.html</a>   :</p>
  <pre><code>public static byte[] getEncryptedPassword(String password, byte[] salt)
          throws NoSuchAlgorithmException, InvalidKeySpecException {
      String algorithm = &quot;PBKDF2WithHmacSHA1&quot;;
      int derivedKeyLength = 64;
      int iterations = 10000;
      KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
      SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
      return f.generateSecret(spec).getEncoded();
  }
  </code></pre>
  <p>Finally, I used apache codecs to set the 64 based string:</p>
  <pre><code>public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException
  {
      byte[] bytes = Base64.decodeBase64(salt);
      byte[] encryptedPassword = getEncryptedPassword(password, bytes);       
      return Base64.encodeBase64String(encryptedPassword);
  }
  </code></pre>
  <p>The tester is this:</p>
  <pre><code>public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
      System.out.println(encrypted);
      System.out.println(getEncryptedPassword(password, salt));       
  }
  </code></pre>
  <p>And the output is</p>
  <blockquote>
  <p>LtStqkNQjrr+P4V8fGtnauNJNOIB7t35O5I4a4/I9lFUnMR3ckbZyT85g/wO0Da9318Wrql/y1bsY2XdpXqx+Q==</p>
  <p>LtStqkNQjro=</p>
  </blockquote>
  <p>As you can see, the java code produce something that is pretty much a prefix of the encryped password produced by the javascript.
  I tested this on different complicated passwords, and got the same result: a string that is a prefix of the javascript encrypted password. Different passwords are not a prefix of each other.</p>
  <p>Therefore, I think I am pretty much close. But I can't figure out what is missing.</p>