You are here

public function EncryptionTrait::decrypt in Encryption 2.x

Same name and namespace in other branches
  1. 8 src/EncryptionTrait.php \Drupal\encryption\EncryptionTrait::decrypt()

Decrypt a value using the encryption key from settings.php.

Parameters

string $value: An encrypted string.

bool $raw_input: Should be set to TRUE if the input value is not a base64 encoded/url safe string (Defaults to FALSE).

Return value

string|null The decrypted value or null if decryption fails.

File

src/EncryptionTrait.php, line 73

Class

EncryptionTrait
Provides basic encryption/decryption methods.

Namespace

Drupal\encryption

Code

public function decrypt($value, $raw_input = FALSE) {

  // Get the encryption key.
  if (!empty($value) && ($key = $this
    ->getEncryptionKey())) {

    // Reverse the urls-safe replacement and decode.
    $message = $raw_input ? $value : base64_decode(str_replace([
      '-',
      '_',
    ], [
      '+',
      '/',
    ], $value));

    // Get the cypher hash.
    $hmac = substr($message, 0, 32);

    // Decode the initialization vector.
    $iv = substr($message, 34, 16);

    // Re generate the HMAC key.
    $h_key = hash_hmac('sha256', hash('sha256', substr($key, 16), TRUE), hash('sha256', substr($iv, 8), TRUE), TRUE);
    if (hash_equals($hmac, hash_hmac('sha256', substr($message, 32), $h_key, TRUE))) {

      // Decrypt to supplied value.
      return openssl_decrypt(substr($message, 50), 'AES-256-CTR', $key, TRUE, $iv);
    }
  }
}