sodium_crypto_secretbox example

// create a nonce for this operation         $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes
        // add padding before we encrypt the data         if ($this->blockSize <= 0) {
            throw EncryptionException::forEncryptionFailed();
        }

        $data = sodium_pad($data$this->blockSize);

        // encrypt message and combine with nonce         $ciphertext = $nonce . sodium_crypto_secretbox($data$nonce$this->key);

        // cleanup buffers         sodium_memzero($data);
        sodium_memzero($this->key);

        return $ciphertext;
    }

    /** * {@inheritDoc} */
    
ParagonIE_Sodium_Core_Util::declareScalarType($key, 'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !== self::CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !== self::CRYPTO_SECRETBOX_KEYBYTES) {
            throw new SodiumException('Argument 3 must be CRYPTO_SECRETBOX_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_secretbox($plaintext$nonce$key);
        }
        if (self::use_fallback('crypto_secretbox')) {
            return (string) call_user_func('\\Sodium\\crypto_secretbox', $plaintext$nonce$key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::secretbox($plaintext$nonce$key);
        }
        return ParagonIE_Sodium_Crypto::secretbox($plaintext$nonce$key);
    }

    /** * Decrypts a message previously encrypted with crypto_secretbox(). * * @param string $ciphertext Ciphertext with Poly1305 MAC * @param string $nonce A Number to be used Once; must be 24 bytes * @param string $key Symmetric encryption key * @return string Original plaintext message * @throws SodiumException * @throws TypeError * @psalm-suppress MixedArgument * @psalm-suppress MixedInferredReturnType * @psalm-suppress MixedReturnStatement */
Home | Imprint | This part of the site doesn't use cookies.