Tuesday, May 29, 2012

Java program to encrypt password for LDAP entry


In the LDAP server, let's say oracle identity directory (OID) or OpenLDAP, we are allowed to configure the encoding algorithm, SHA,MD5,SHAA,etc, to hash the user password.

if the password is 'abcd1234', the password in ldap will be stored as '{SHA}fOA1nxKFfyqQx95GX0CpXwHLXak=' in userPassword attribute.

This is the java program to encrypt the password with SHA to simulate how LDAP to encrypt user password.

package test.ldap.sha;

import java.security.MessageDigest;

import sun.misc.BASE64Encoder;

public class PasswordEncryptor {

public static void main(String[] args) throws Exception {
String pwdPlainText = "abcd1234";

MessageDigest md = MessageDigest.getInstance("SHA");
md.update(pwdPlainText.getBytes());
byte raw[] = md.digest();

BASE64Encoder base64 = new BASE64Encoder();
String result = "{SHA}" + base64.encode(raw);
System.out.println("userpassword in LDAP:" + result);

String pwdGeneratedByLdap = "{SHA}fOA1nxKFfyqQx95GX0CpXwHLXak=";
System.out.println(pwdGeneratedByLdap.equals(result));

}
}

This is output:
userpassword in LDAP:{SHA}fOA1nxKFfyqQx95GX0CpXwHLXak=
true

No comments:

Post a Comment