You are here

public function SimpleLdap::hash in Simple LDAP 8

Hash a string for use in an LDAP password field.

File

src/SimpleLdap.php, line 115

Class

SimpleLdap
A wrapper for PHP's LDAP functions, with associated helper methods.

Namespace

Drupal\simple_ldap

Code

public function hash($string, $algorithm = NULL) {
  switch ($algorithm) {
    case 'crypt':
      $hash = '{CRYPT}' . crypt($string, substr($string, 0, 2));
      break;
    case 'salted crypt':
      $hash = '{CRYPT}' . crypt($string, self::salt(2));
      break;
    case 'extended des':
      $hash = '{CRYPT}' . crypt($string, '_' . self::salt(8));
      break;
    case 'md5crypt':
      $hash = '{CRYPT}' . crypt($string, '$1$' . self::salt(9));
      break;
    case 'blowfish':
      $hash = '{CRYPT}' . crypt($string, '$2a$12$' . self::salt(13));
      break;
    case 'md5':
      $hash = '{MD5}' . base64_encode(md5($string, TRUE));
      break;
    case 'salted md5':
      $salt = SimpleLdap::salt(8);
      $hash = '{SMD5}' . base64_encode(md5($string . $salt, TRUE) . $salt);
      break;
    case 'sha':
      $hash = '{SHA}' . base64_encode(sha1($string, TRUE));
      break;
    case 'salted sha':
      $salt = SimpleLdap::salt(8);
      $hash = '{SSHA}' . base64_encode(sha1($string . $salt, TRUE) . $salt);
      break;
    case 'unicode':
      $string = '"' . $string . '"';
      $length = drupal_strlen($string);
      $hash = NULL;
      for ($i = 0; $i < $length; $i++) {
        $hash .= "{$string[$i]}\0";
      }
      break;
    case 'none':
    default:
      $hash = $string;
  }
  return $hash;
}