You are here

function _password_field_encrypt in Password Field 7

Encrypt the password.

1 string reference to '_password_field_encrypt'
password_field_field_widget_form in ./password_field.module
Implements hook_field_widget_form().

File

./password_field.module, line 203
Password Field Module

Code

function _password_field_encrypt($element, &$form_state) {

  // If no value to encrypt, get out of here.
  if (!isset($element['#value'])) {
    return;
  }

  // If password value exists, but is empty, load old value and store that. This
  // means that if the field is left blank, then the value will be unchanged.
  if (empty($element['#value']) && !empty($form_state['field'])) {
    $pwvalue = _password_field_load_current_value($element, $form_state);
    form_set_value($element, array(
      'password_field' => $pwvalue,
    ), $form_state);
    return;
  }

  // If a new password value has been entered, encrypt it before saving.
  if (!empty($element['#value'])) {
    define('ENCRYPT_METHOD', 'AES-256-CBC');
    $str = $element['#value'];
    $key = md5(drupal_get_hash_salt());

    // Generate the Initialization Vector.
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(ENCRYPT_METHOD));

    // Encrypt the password.
    $encrypted = openssl_encrypt($str, ENCRYPT_METHOD, $key, 0, $iv);

    // Save the IV with the data for the decrypt.
    $value = trim(base64_encode($encrypted . '::' . $iv));
    form_set_value($element, array(
      'password_field' => $value,
    ), $form_state);
  }
}