You are here

public static function ParagonIE_Sodium_Crypto32::secretbox_xchacha20poly1305 in Automatic Updates 8

Same name and namespace in other branches
  1. 7 vendor/paragonie/sodium_compat/src/Crypto32.php \ParagonIE_Sodium_Crypto32::secretbox_xchacha20poly1305()

XChaCha20-Poly1305 authenticated symmetric-key encryption.

@internal Do not use this directly. Use ParagonIE_Sodium_Compat.

Parameters

string $plaintext:

string $nonce:

string $key:

Return value

string

Throws

SodiumException

TypeError

1 call to ParagonIE_Sodium_Crypto32::secretbox_xchacha20poly1305()
ParagonIE_Sodium_Compat::crypto_secretbox_xchacha20poly1305 in vendor/paragonie/sodium_compat/src/Compat.php
Authenticated symmetric-key encryption.

File

vendor/paragonie/sodium_compat/src/Crypto32.php, line 1092

Class

ParagonIE_Sodium_Crypto32
Class ParagonIE_Sodium_Crypto

Code

public static function secretbox_xchacha20poly1305($plaintext, $nonce, $key) {

  /** @var string $subkey */
  $subkey = ParagonIE_Sodium_Core32_HChaCha20::hChaCha20(ParagonIE_Sodium_Core32_Util::substr($nonce, 0, 16), $key);
  $nonceLast = ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8);

  /** @var string $block0 */
  $block0 = str_repeat("\0", 32);

  /** @var int $mlen - Length of the plaintext message */
  $mlen = ParagonIE_Sodium_Core32_Util::strlen($plaintext);
  $mlen0 = $mlen;
  if ($mlen0 > 64 - self::secretbox_xchacha20poly1305_ZEROBYTES) {
    $mlen0 = 64 - self::secretbox_xchacha20poly1305_ZEROBYTES;
  }
  $block0 .= ParagonIE_Sodium_Core32_Util::substr($plaintext, 0, $mlen0);

  /** @var string $block0 */
  $block0 = ParagonIE_Sodium_Core32_ChaCha20::streamXorIc($block0, $nonceLast, $subkey);

  /** @var string $c */
  $c = ParagonIE_Sodium_Core32_Util::substr($block0, self::secretbox_xchacha20poly1305_ZEROBYTES);
  if ($mlen > $mlen0) {
    $c .= ParagonIE_Sodium_Core32_ChaCha20::streamXorIc(ParagonIE_Sodium_Core32_Util::substr($plaintext, self::secretbox_xchacha20poly1305_ZEROBYTES), $nonceLast, $subkey, ParagonIE_Sodium_Core32_Util::store64_le(1));
  }
  $state = new ParagonIE_Sodium_Core32_Poly1305_State(ParagonIE_Sodium_Core32_Util::substr($block0, 0, self::onetimeauth_poly1305_KEYBYTES));
  try {
    ParagonIE_Sodium_Compat::memzero($block0);
    ParagonIE_Sodium_Compat::memzero($subkey);
  } catch (SodiumException $ex) {
    $block0 = null;
    $subkey = null;
  }
  $state
    ->update($c);

  /** @var string $c - MAC || ciphertext */
  $c = $state
    ->finish() . $c;
  unset($state);
  return $c;
}