Exemple #1
0
 /**
  * Encrypt then authenticate using HMAC
  *
  * @param  string $data
  * @return string
  * @throws Exception\InvalidArgumentException
  */
 public function encrypt($data)
 {
     if (empty($data)) {
         throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty');
     }
     if (empty($this->key)) {
         throw new Exception\InvalidArgumentException('No key specified for the encryption');
     }
     if (empty($this->cipher)) {
         throw new Exception\InvalidArgumentException('No symmetric cipher specified');
     }
     $keySize = $this->cipher->getKeySize();
     $salt = $this->getSalt();
     // generate a random salt (IV) if empty
     if (empty($salt)) {
         $salt = Rand::getBytes($this->cipher->getSaltSize(), true);
     }
     $this->cipher->setSalt($salt);
     // generate the encryption key and the HMAC key for the authentication
     $hash = Pbkdf2::calc(self::KEY_DERIV_HMAC, $this->getKey(), $this->cipher->getSalt(), $this->keyIteration, $keySize * 2);
     // set the encryption key
     $this->cipher->setKey(substr($hash, 0, $keySize));
     // set the key for HMAC
     $keyHmac = substr($hash, $keySize);
     // encryption
     $ciphertext = $this->cipher->encrypt($data);
     // HMAC
     $hmac = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext);
     if (!$this->binaryOutput) {
         $ciphertext = base64_encode($ciphertext);
     }
     return $hmac . $ciphertext;
 }
 /**
  * Get the salt (IV) according to the size requested by the algorithm
  *
  * @return string
  */
 public function getSalt()
 {
     return $this->cipher->getSalt();
 }