Voting

: min(four, two)?
(Example: nine)

The Note You're Voting On

damien at groovey dot com
18 years ago
Here is how to add a user with a hashed MD5 password to OpenLDAP. I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result. You cannot just base64 encode what is returned by PHP's md5() or sha() hash functions, because they return a hexadecimal text string. First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password. You don't have to use {MD5}, you could pick a different hash if that is what you have. The output from one of these hashed passwords will look like this: {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats: This technique will not work if you hashed the password using a salt value (but Drupal does not). This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

---- snip ----

$ds = ldap_connect($serverAddress);
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
$r = ldap_bind($ds, $managerDN, $managerPassword);
$ldaprecord['cn'] = $newuser_username;
$ldaprecord['givenName'] = $newuser_firstname;
$ldaprecord['sn'] = $newuser_surname;
// put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
$ldaprecord['objectclass'][0] = "person";
$ldaprecord['objectclass'][1] = "organizationalPerson";
$ldaprecord['objectclass'][2] = "inetOrgPerson";
$ldaprecord['mail'] = $newuser_email_address;
$ldaprecord['telephoneNumber'] = $newuser_phone_number;
// and now the tricky part, base64 encode the binary hash result:
$ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',$newuser_md5hashed_password));
// If you have the plain text password instead, you could use:
// $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($newuser_plaintext_password)));
$r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }

<< Back to user notes page

To Top