You are here

function _simple_ldap_encrypt_decrypt in Simple LDAP 7

Same name and namespace in other branches
  1. 7.2 simple_ldap_sso/simple_ldap_sso.inc \_simple_ldap_encrypt_decrypt()

Helper function to encrypt or decrypt data.

Parameters

string $text: A string of text to encrypt or decrypt.

bool $encrypt: TRUE if encrypting, FALSE if decrypting.

Return value

string A string of encrypted or decrypted text.

2 calls to _simple_ldap_encrypt_decrypt()
simple_ldap_sso_decrypt in simple_ldap_sso/simple_ldap_sso.inc
Decrypt a string to an array of session data.
simple_ldap_sso_encrypt in simple_ldap_sso/simple_ldap_sso.inc
Encrypt an array of session data.

File

simple_ldap_sso/simple_ldap_sso.inc, line 272
Simple LDAP SSO API functions.

Code

function _simple_ldap_encrypt_decrypt($text, $encrypt = TRUE) {

  // Hash the key to get a more secure key.
  $key = hash('sha256', variable_get('simple_ldap_sso_encryption_key'), TRUE);
  $cipher = 'rijndael-256';
  $mode = MCRYPT_MODE_CBC;
  $iv_size = mcrypt_get_iv_size($cipher, $mode);
  if ($encrypt) {

    // Create the IV.
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    // Generate an HMAC.
    $hmac = hash('sha256', trim($text));

    // Prepend the text with the HMAC.
    $text = $hmac . $text;

    // Now encrypt the text.
    $encrypted_text = mcrypt_encrypt($cipher, $key, $text, $mode, $iv);

    // Prepend the encrypted text with the IV before it is base64 encoded.
    $output = base64_encode($iv . $encrypted_text);
  }
  else {

    // Decode the string.
    $decoded = base64_decode($text);

    // Get the IV from the beginning of the string.
    $iv = substr($decoded, 0, $iv_size);

    // Get the encrypted data from the string.
    $data = substr($decoded, $iv_size);

    // Now, decrypt the string.
    $output = mcrypt_decrypt($cipher, $key, $data, $mode, $iv);

    // Get the HMAC from the front of this string.
    $hmac = substr($output, 0, 64);

    // Remove the HMAC from the output.
    $output = substr($output, 64);

    // If the hash doesn't match, log an error and return an empty string.
    if ($hmac != hash('sha256', trim($output))) {
      $message = 'Possible break-in attempted. The HMAC does not match on the encrypted text.';
      watchdog(__FUNCTION__, $message, array(), WATCHDOG_ALERT);
      $output = '';
    }
  }
  return $output;
}