Ejemplo n.º 1
0
Archivo: JWE.php Proyecto: sop/jwx
 /**
  * Encrypt content with explicit parameters.
  *
  * @param string $plaintext Plaintext content to encrypt
  * @param string $cek Content encryption key
  * @param string $iv Initialization vector
  * @param KeyManagementAlgorithm $key_algo Key management algorithm
  * @param ContentEncryptionAlgorithm $enc_algo Content encryption algorithm
  * @param Header $header Header
  * @throws \UnexpectedValueException
  * @return self
  */
 private static function _encryptContent($plaintext, $cek, $iv, KeyManagementAlgorithm $key_algo, ContentEncryptionAlgorithm $enc_algo, Header $header)
 {
     // check that content encryption key has correct size
     if (strlen($cek) != $enc_algo->keySize()) {
         throw new \UnexpectedValueException("Invalid key size.");
     }
     // check that initialization vector has correct size
     if (strlen($iv) != $enc_algo->ivSize()) {
         throw new \UnexpectedValueException("Invalid IV size.");
     }
     // add key and encryption algorithm parameters to the header
     $header = $header->withParameters(...$key_algo->headerParameters())->withParameters(...$enc_algo->headerParameters());
     // encrypt the content encryption key
     $encrypted_key = $key_algo->encrypt($cek, $header);
     // sanity check that header wasn't unset via reference
     if (!$header instanceof Header) {
         throw new \RuntimeException("Broken key algorithm.");
     }
     // additional authenticated data
     $aad = Base64::urlEncode($header->toJSON());
     // encrypt
     list($ciphertext, $auth_tag) = $enc_algo->encrypt($plaintext, $cek, $iv, $aad);
     return new self($header, $encrypted_key, $iv, $ciphertext, $auth_tag);
 }