Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SodiumChachaIetf.php
Go to the documentation of this file.
1 <?php
7 declare(strict_types=1);
8 
10 
15 {
19  private $key;
20 
25  public function __construct(
26  string $key
27  ) {
28  $this->key = $key;
29  }
30 
37  public function encrypt(string $data): string
38  {
39  $nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES);
40  $cipherText = sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
41  (string)$data,
42  $nonce,
43  $nonce,
44  $this->key
45  );
46 
47  return $nonce . $cipherText;
48  }
49 
56  public function decrypt(string $data): string
57  {
58  $nonce = mb_substr($data, 0, SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES, '8bit');
59  $payload = mb_substr($data, SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES, null, '8bit');
60 
61  $plainText = sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
62  $payload,
63  $nonce,
64  $nonce,
65  $this->key
66  );
67 
68  return $plainText;
69  }
70 }