PHP: How to calculate the SSHA value of a string

Articles may may have files attached at the end of the post

This bit of code allow one to generate SSHA password as accepted by 'ldapmodify' userPassword entry.
unlike SHA, SSHA is using a random seed, increasing the security of your passwords.

These function are based on the explanation provided at OpenLDAP's What are {SHA} and {SSHA} passwords and how do I generate them? page.

  1. <?php
  2.  
  3. function make_ssha_password($password){
  4.   mt_srand((double)microtime()*1000000);
  5.   $salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand());
  6.   $hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $salt)) . $salt);
  7.   return $hash;
  8. }
  9.  
  10. function ssha_password_verify($hash, $password){
  11.   // Verify SSHA hash
  12.   $ohash = base64_decode(substr($hash, 6));
  13.   $osalt = substr($ohash, 20);
  14.   $ohash = substr($ohash, 0, 20);
  15.   $nhash = pack("H*", sha1($password . $osalt));
  16.   if ($ohash == $nhash) {
  17.     return True;
  18.   } else {
  19.     return False;
  20.   }
  21. }
  22.  
  23. $encpass = make_ssha_password($argv[1]);
  24. print("Encoded password is: $encpass\n");
  25.  
  26. if(ssha_password_verify($encpass, $argv[1])){
  27.   print("Password could be verified\n");
  28. }else{
  29.   print("Password could  not be verified\n");
  30. }
  31. ?>

will produce:

$ php -f ssha.php foobar
Encoded password is: {SSHA}Q7cMTL+eSfOygiBxzrwfpaFhtRyl8JII
Password could be verified

AttachmentSize
ssha.php.txt794 bytes