You are here

public function EncryptionTrait::encrypt in Encryption 2.x

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

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

Parameters

string $value: The value tobe encrypted.

bool $raw_output: Should be set to TRUE if a raw output value is required. Otherwise, a url safe base64 encoded encoded string will be returned.

Return value

string|null A Base64 encoded representation of the encrypted value or null if encryption fails for some reason.

File

src/EncryptionTrait.php, line 41

Class

EncryptionTrait
Provides basic encryption/decryption methods.

Namespace

Drupal\encryption

Code

public function encrypt($value, $raw_output = FALSE) {

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

    // Generates a random initialization vector.
    $iv = random_bytes(16);

    // Generate a HMAC key using the initialization vector as a salt.
    $h_key = hash_hmac('sha256', hash('sha256', substr($key, 16), TRUE), hash('sha256', substr($iv, 8), TRUE), TRUE);

    // Concatenate the initialization vector and the encrypted value.
    $cypher = '03' . $iv . openssl_encrypt($value, 'AES-256-CTR', $key, TRUE, $iv);

    // Encode and concatenate the hmac, format code and cypher.
    $message = hash_hmac('sha256', $cypher, $h_key, TRUE) . $cypher;

    // Modify the message so it's safe to use in URLs.
    return $raw_output ? $message : str_replace([
      '+',
      '/',
      '=',
    ], [
      '-',
      '_',
      '',
    ], base64_encode($message));
  }
}