Example #1
0
 function __construct()
 {
     $this->iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
     $this->Key = sha1("Patronato Santo Antonio");
     //NÃO ALTERAR ESSA LINHA
     $this->Method = 'AES-256-CBC';
 }
 /**
  * Decrypt a string.
  *
  * @access public
  * @static static method
  * @param  string $ciphertext
  * @return string
  * @throws Exception If $ciphertext is empty, or If functions don't exists
  */
 public static function decrypt($ciphertext)
 {
     if (empty($ciphertext)) {
         throw new Exception("the string to decrypt can't be empty");
     }
     if (!function_exists('openssl_cipher_iv_length') || !function_exists('openssl_decrypt')) {
         throw new Exception("Encryption function don't exists");
     }
     // generate key used for authentication using ENCRYPTION_KEY & HMAC_SALT
     $key = mb_substr(hash(self::HASH_FUNCTION, Config::get('ENCRYPTION_KEY') . Config::get('HMAC_SALT')), 0, 32, '8bit');
     // split cipher into: hmac, cipher & iv
     $macSize = 64;
     $hmac = mb_substr($ciphertext, 0, $macSize, '8bit');
     $iv_cipher = mb_substr($ciphertext, $macSize, null, '8bit');
     // generate original hmac & compare it with the one in $ciphertext
     $originalHmac = hash_hmac('sha256', $iv_cipher, $key);
     if (!function_exists("hash_equals")) {
         throw new Exception("Function hash_equals() doesn't exist!");
     }
     if (!hash_equals($hmac, $originalHmac)) {
         return false;
     }
     // split out the initialization vector and cipher
     $iv_size = openssl_cipher_iv_length(self::CIPHER);
     $iv = mb_substr($iv_cipher, 0, $iv_size, '8bit');
     $cipher = mb_substr($iv_cipher, $iv_size, null, '8bit');
     return openssl_decrypt($cipher, self::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
 }
Example #3
0
 /**
  * Increment a counter (prevent nonce reuse)
  *
  * @param string $ctr - raw binary
  * @param int $inc - how much?
  *
  * @return string (raw binary)
  */
 public static function incrementCounter($ctr, $inc, &$config)
 {
     static $ivsize = null;
     if ($ivsize === null) {
         $ivsize = \openssl_cipher_iv_length($config->cipherMethod());
         if ($ivsize === false) {
             throw new Ex\CannotPerformOperationException("Problem obtaining the correct nonce length.");
         }
     }
     if (self::ourStrlen($ctr) !== $ivsize) {
         throw new Ex\CannotPerformOperationException("Trying to increment a nonce of the wrong size.");
     }
     if (!is_int($inc)) {
         throw new Ex\CannotPerformOperationException("Trying to increment nonce by a non-integer.");
     }
     if ($inc < 0) {
         throw new Ex\CannotPerformOperationException("Trying to increment nonce by a negative amount.");
     }
     /**
      * We start at the rightmost byte (big-endian)
      * So, too, does OpenSSL: http://stackoverflow.com/a/3146214/2224584
      */
     for ($i = $ivsize - 1; $i >= 0; --$i) {
         $sum = \ord($ctr[$i]) + $inc;
         /* Detect integer overflow and fail. */
         if (!is_int($sum)) {
             throw new Ex\CannotPerformOperationException("Integer overflow in CTR mode nonce increment.");
         }
         $ctr[$i] = \chr($sum & 0xff);
         $inc = $sum >> 8;
     }
     return $ctr;
 }
Example #4
0
 /**
  * Check that IV is valid.
  *
  * @param string $iv
  * @throws \RuntimeException
  */
 protected final function _validateIV($iv)
 {
     $len = openssl_cipher_iv_length($this->_getCipherMethod());
     if ($len != strlen($iv)) {
         throw new \RuntimeException("Invalid IV length.");
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $key = openssl_random_pseudo_bytes(32);
     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
     $output->writeln("KEY: " . $this->strtohex($key));
     $output->writeln("IV: " . $this->strtohex($iv));
 }
Example #6
0
 /**
  * Decrypt a value using AES-256.
  *
  * @param string $cipher The ciphertext to decrypt.
  * @param string $key The 256 bit/32 byte key to use as a cipher key.
  * @return string Decrypted data. Any trailing null bytes will be removed.
  * @throws \InvalidArgumentException On invalid data or key.
  */
 public static function decrypt($cipher, $key)
 {
     $method = 'AES-256-CBC';
     $ivSize = openssl_cipher_iv_length($method);
     $iv = substr($cipher, 0, $ivSize);
     $cipher = substr($cipher, $ivSize);
     return openssl_decrypt($cipher, $method, $key, true, $iv);
 }
Example #7
0
 /**
  * Decrypts payload and returns original data.
  * @return string|false Original data as string or string containing binary data, false if unsuccessful.
  */
 public static function decrypt($payload, $cipherParams)
 {
     $raw = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
     $ivLength = openssl_cipher_iv_length($cipherParams->getAlgorithmString());
     $iv = substr($payload, 0, $ivLength);
     $ciphertext = substr($payload, $ivLength);
     return openssl_decrypt($ciphertext, $cipherParams->getAlgorithmString(), $cipherParams->key, $raw, $iv);
 }
Example #8
0
function decryptText($text)
{
    $secret = defined("ENCRYPT_SECRET") ? ENCRYPT_SECRET : "something";
    $text = base64_decode($text);
    $iv_size = openssl_cipher_iv_length("aes-256-cbc");
    $iv = substr($text, 0, $iv_size);
    return openssl_decrypt(substr($text, $iv_size), 'aes-256-cbc', $secret, 0, $iv);
}
Example #9
0
 private function decrypted(string $hash) : string
 {
     $binary = hex2bin($hash);
     $ivSize = openssl_cipher_iv_length(self::CIPHER);
     $iv = substr($binary, self::BEGIN, $ivSize);
     $cipherText = substr(substr($binary, $ivSize), self::BEGIN, self::MAC_LENGTH);
     return openssl_decrypt($cipherText, self::CIPHER, $this->key(), OPENSSL_RAW_DATA, $iv);
 }
Example #10
0
 /**
  * Decrypt a value using AES-256.
  *
  * @param string $cipher The ciphertext to decrypt.
  * @param string $key The 256 bit/32 byte key to use as a cipher key.
  * @return string Decrypted data. Any trailing null bytes will be removed.
  * @throws \InvalidArgumentException On invalid data or key.
  */
 public static function decrypt($cipher, $key)
 {
     $method = 'AES-256-CBC';
     $ivSize = openssl_cipher_iv_length($method);
     $iv = mb_substr($cipher, 0, $ivSize, '8bit');
     $cipher = mb_substr($cipher, $ivSize, null, '8bit');
     return openssl_decrypt($cipher, $method, $key, OPENSSL_RAW_DATA, $iv);
 }
Example #11
0
 /**
  * @test
  */
 public function testIv()
 {
     $algorithm = 'aes-256-cbc';
     $crypt = new OpenSSL($algorithm);
     $ivSize = openssl_cipher_iv_length($algorithm);
     $this->assertSame($ivSize, $crypt->getIvSize());
     $iv = $crypt->createIv();
     $this->assertEquals($ivSize, strlen($iv));
 }
Example #12
0
 private function encrypt($export, $output)
 {
     $key = base64_decode($export['encryptionKey']);
     if (strlen($key) != 32) {
         throw new \RuntimeException('The key must have the length of 32 bytes!');
     }
     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::ENCRYPTION_ALGORITHM));
     return base64_encode($iv . openssl_encrypt(json_encode($output), self::ENCRYPTION_ALGORITHM, $key, true, $iv));
 }
Example #13
0
 /**
  * Decrypt provided data using AES 256 algorithm and the security.encryption.key.
  *
  * @param string $data
  *
  * @return string
  *
  * @since 1.2.2
  */
 public static function decrypt($data)
 {
     $config = ConfigProvider::getInstance();
     $ivsize = openssl_cipher_iv_length('aes-256-ecb');
     $iv = mb_substr($data, 0, $ivsize, '8bit');
     $ciphertext = mb_substr($data, $ivsize, null, '8bit');
     $decryptedData = openssl_decrypt($ciphertext, 'aes-256-ecb', $config->get('security.encryption.key'), OPENSSL_RAW_DATA, $iv);
     return $decryptedData;
 }
Example #14
0
function encrypt($text)
{
    $fp = fopen('../other/key.txt', 'r');
    $key = fread($fp, filesize('../other/key'));
    fclose($fp);
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, 0, $iv);
    $encrypted = $encrypted . ':' . bin2hex($iv);
    return $encrypted;
}
 /**
  * {@inheritDoc}
  */
 public function decrypt($data, $salt)
 {
     $password = $this->generatePassword($salt);
     $vectorSize = openssl_cipher_iv_length($this->method);
     $decrypted = base64_decode($data);
     $initializationVector = substr($decrypted, 0, $vectorSize);
     $decrypted = substr($decrypted, $vectorSize);
     $decrypted = openssl_decrypt($decrypted, $this->method, $password, OPENSSL_RAW_DATA, $initializationVector);
     return $decrypted;
 }
Example #16
0
 /**
  *
  * @param string $cipher
  * @param string $password
  * @param string $salt
  * @param int $ivMaxChars null if you want a full iv. If you provide a number, the rest of the iv will be padded.
  * @param bool $useMd5NotRandom If true, the IV will be extracted from md5 of the data.
  * @param int $nonceChars
  * @param int $cipherIvLength If null, the iv length gets calculated with openssl_cipher_iv_length()
  * @param string $serializationFormat
  */
 public function __construct($cipher, $password, $salt, $ivMaxChars = 4, $useMd5NotRandom = false, $nonceChars = 5, $cipherIvLength = null, $serializationFormat = self::SERIALIZE_JSON)
 {
     parent::__construct($password, $salt, $serializationFormat);
     $this->cipher = $cipher;
     $cipherIvLength = (int) $cipherIvLength;
     $this->cipherIvLength = $cipherIvLength ? (int) $cipherIvLength : openssl_cipher_iv_length($this->cipher);
     $this->ivMaxChars = $ivMaxChars === null ? null : (int) $ivMaxChars;
     $this->nonceChars = (int) $nonceChars;
     $this->useMd5NotRandom = $useMd5NotRandom;
 }
Example #17
0
 public static function encrypt($key, $data, $method = null)
 {
     if ($method === null) {
         $method = app()->getEncryptionMethod();
     }
     $key = substr(hash('sha256', $key, true), 0, 16);
     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
     $data = openssl_encrypt($data, $method, $key, 0, $iv);
     return base64_encode($data . '|' . bin2hex($iv));
 }
Example #18
0
 /**
  * @inheritdoc
  */
 public function encrypt($data)
 {
     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher));
     $encryptedValue = openssl_encrypt(serialize($data), $this->cipher, $this->key, 0, $iv);
     if ($encryptedValue === false) {
         throw new EncryptionException("Failed to encrypt the data");
     }
     $iv = base64_encode($iv);
     $mac = $this->createHash($iv, $encryptedValue);
     $pieces = ["iv" => $iv, "value" => $encryptedValue, "mac" => $mac];
     return base64_encode(json_encode($pieces));
 }
Example #19
0
 /**
  * decrypts by using the given enc_method and hash_method.
  * @param $edata the encrypted string that we want to decrypt
  * @return the decrypted string.
  */
 public function decrypt($edata)
 {
     $e_arr = explode('$', $edata);
     if (count($e_arr) != 4) {
         throw new Exception('Given data is missing crucial sections.');
     }
     $this->config['enc_method'] = $e_arr[1];
     $this->config['hash_method'] = $e_arr[2];
     self::check_methods($this->config['enc_method'], $this->config['hash_method']);
     $iv = self::hashIV($this->config['key'], $this->config['hash_method'], openssl_cipher_iv_length($this->config['enc_method']));
     return openssl_decrypt($e_arr[3], $this->config['enc_method'], $this->config['key'], false, $iv);
 }
Example #20
0
 public static function encrypt($password, $secret, $data)
 {
     //Generate a key by hashing the secret and password
     $key = hash_pbkdf2("sha256", $password, $secret, 1000, 32);
     //Generate initialisation vector
     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
     //Encrypt data using the given secret and generated iv.
     $encrypted_data = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
     //Append iv to the encrypted data
     $encrypted_data .= '|' . base64_encode($iv);
     return $encrypted_data;
 }
Example #21
0
 /**
  * Decrypts (but does not verify) a message
  *
  * @param string $message - ciphertext message
  * @param string $key - encryption key (raw binary expected)
  * @param boolean $encoded - are we expecting an encoded string?
  * @return string
  * @throws Exception
  */
 public static function decrypt($message, $key, $encoded = false)
 {
     if ($encoded) {
         $message = base64_decode($message, true);
         if ($message === false) {
             throw new Exception('Encryption failure');
         }
     }
     $nonceSize = openssl_cipher_iv_length(self::METHOD);
     $nonce = mb_substr($message, 0, $nonceSize, '8bit');
     $ciphertext = mb_substr($message, $nonceSize, null, '8bit');
     $plaintext = openssl_decrypt($ciphertext, self::METHOD, $key, OPENSSL_RAW_DATA, $nonce);
     return $plaintext;
 }
Example #22
0
 /**
  * Decrypts (but does not verify) a message
  *
  * @param string $message - ciphertext message
  * @param string $key - encryption key (raw binary expected)
  * @param boolean $encoded - are we expecting an encoded string?
  * @return string
  * @throws \Exception
  */
 public static function Decrypt($message, $key, $encoded = self::BASE64_DEFAULT)
 {
     // base64 decode
     if ($encoded) {
         $message = base64_decode($message);
         if ($message === false) {
             throw new \Exception('Decoding failure');
         }
     }
     $ivSize = openssl_cipher_iv_length(self::METHOD);
     $iv = mb_substr($message, 0, $ivSize, '8bit');
     $ciphertext = mb_substr($message, $ivSize, null, '8bit');
     $plaintext = openssl_decrypt($ciphertext, self::METHOD, $key, OPENSSL_RAW_DATA, $iv);
     return $plaintext;
 }
 /**
  * Updates the underlying hash by encrypting it with the newest secret.
  *
  * @throws MWException If the configuration is not valid
  * @return bool True if the password was updated
  */
 public function update()
 {
     if (count($this->args) != 2 || $this->params == $this->getDefaultParams()) {
         // Hash does not need updating
         return false;
     }
     // Decrypt the underlying hash
     $underlyingHash = openssl_decrypt(base64_decode($this->args[1]), $this->params['cipher'], $this->config['secrets'][$this->params['secret']], 0, base64_decode($this->args[0]));
     // Reset the params
     $this->params = $this->getDefaultParams();
     // Check the key size with the new params
     $iv = MWCryptRand::generate(openssl_cipher_iv_length($this->params['cipher']), true);
     $this->hash = base64_encode(openssl_encrypt($underlyingHash, $this->params['cipher'], $this->config['secrets'][$this->params['secret']], 0, $iv));
     $this->args = array(base64_encode($iv));
     return true;
 }
Example #24
0
 /**
  * Cipher constructor.
  * @param string $cipherMethod
  * @throws CipherException
  */
 public function __construct(string $cipherMethod = "aes-256-cbc")
 {
     // Check requirements
     if (!extension_loaded("openssl") || !function_exists("hash")) {
         throw CipherException::initError();
     }
     // Cipher Method
     if (!in_array($cipherMethod, openssl_get_cipher_methods())) {
         throw CipherException::badCipherMethod($cipherMethod);
     }
     // Bootstrap
     $this->cipherMethod = $cipherMethod;
     $this->defaultSecret = $this->validateKey(self::createKey("comely", 1), __METHOD__);
     $this->defaultHashAlgo = $this->defaultHashAlgo("sha1");
     $this->ivSize = openssl_cipher_iv_length($this->cipherMethod);
 }
Example #25
0
 /**
  *	Включает отключает шифрование
  *
  *	@param	mixed	$encryption	NULL или boolean или string пароль
  *	@return	mixed
  */
 public function encryption($encryption = null)
 {
     if ($encryption === null) {
         return $this->encryption;
     }
     if ($this->encryption = (bool) $encryption) {
         if (!extension_loaded('openssl')) {
             throw new \RuntimeException('Для поддержки шифрования нужно PHP расширение OpenSSL.');
         }
         if (is_string($encryption)) {
             $this->phrase($encryption);
         }
         $this->ivSize = openssl_cipher_iv_length($this->cipher);
     }
     return $this;
 }
Example #26
0
 /**
  * @param string          $aad
  * @param string          $plainText
  * @param string|resource $cek
  *
  * @return array [iv, cipherText, authTag]
  */
 public function encrypt($aad, $plainText, $cek)
 {
     $cekLen = StringUtils::length($cek);
     if ($cekLen * 8 != $this->keySize) {
         throw new JoseJwtException(sprintf('AES-CBC with HMAC algorithm expected key of size %s bits, but was given %s bits', $this->keySize, $cekLen * 8));
     }
     if ($cekLen % 2 != 0) {
         throw new JoseJwtException('AES-CBC with HMAC encryption expected key of even number size');
     }
     $hmacKey = StringUtils::substring($cek, 0, $cekLen / 2);
     $aesKey = StringUtils::substring($cek, $cekLen / 2, $cekLen / 2);
     $method = sprintf('AES-%d-CBC', $this->keySize / 2);
     $ivLen = openssl_cipher_iv_length($method);
     $iv = $this->randomGenerator->get($ivLen);
     $cipherText = openssl_encrypt($plainText, $method, $aesKey, true, $iv);
     $authTag = $this->computeAuthTag($aad, $iv, $cipherText, $hmacKey);
     return [$iv, $cipherText, $authTag];
 }
 /**
  * @param string $string
  * @return array
  */
 public function parseDekInfo($string)
 {
     $dek = explode(",", $string);
     if (count($dek) !== 2) {
         throw new \RuntimeException('Malformed DEK-Info');
     }
     $cipher = $dek[0];
     $iv = $dek[1];
     if (!in_array($cipher, openssl_get_cipher_methods())) {
         throw new \RuntimeException('Unknown cipher method');
     }
     if (strlen($iv) / 2 !== openssl_cipher_iv_length($cipher)) {
         throw new \RuntimeException('Bad IV length');
     }
     if (!ctype_xdigit($iv)) {
         throw new \RuntimeException('Bad IV');
     }
     $iv = pack("H*", $iv);
     return [$cipher, $iv];
 }
Example #28
0
 public static function decrypt($message, $key = self::KEY, $encoded = false)
 {
     list($encKey, $authKey) = self::splitKeys($key);
     if ($encoded) {
         $hs = mb_strlen(base64_encode(hash_hmac(self::HASH_ALGO, '', $authKey, true)));
         $mac = base64_decode(mb_substr($message, 0, $hs));
         $ciphertext = base64_decode(mb_substr($message, $hs));
     } else {
         $hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
         $mac = mb_substr($message, 0, $hs, '8bit');
         $ciphertext = mb_substr($message, $hs, mb_strlen($message), '8bit');
     }
     $calculated = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
     if (!self::hashEquals($mac, $calculated)) {
         throw new Exception('Encryption failure');
     }
     $ivSize = openssl_cipher_iv_length(self::METHOD);
     $iv = mb_substr($ciphertext, 0, $ivSize, '8bit');
     $plaintext = @openssl_decrypt($ciphertext, self::METHOD, $encKey, 'OPENSSL_ZERO_PADDING', $iv);
     return mb_substr($plaintext, openssl_cipher_iv_length(self::METHOD));
     return $plaintext;
 }
Example #29
0
 /**
  * Switch storage algorithm backing
  *
  * @param  int $type one of BACKING_MCRYPT, BACKING_OPENSSL, BACKING_PLAINTEXT
  * @throws lang.IllegalArgumentException If illegal backing type was given
  * @throws lang.IllegalStateException If chosen backing missed a extension dependency
  * @return void
  */
 public static function useBacking($type)
 {
     switch ($type) {
         case self::BACKING_OPENSSL:
             if (!Runtime::getInstance()->extensionAvailable('openssl')) {
                 throw new IllegalStateException('Backing "openssl" required but extension not available.');
             }
             $key = md5(uniqid());
             $iv = substr(md5(uniqid()), 0, openssl_cipher_iv_length('des'));
             return self::setBacking(function ($value) use($key, $iv) {
                 return openssl_encrypt($value, 'DES', $key, 0, $iv);
             }, function ($value) use($key, $iv) {
                 return openssl_decrypt($value, 'DES', $key, 0, $iv);
             });
         case self::BACKING_MCRYPT:
             // Deprecated, see https://wiki.php.net/rfc/mcrypt-viking-funeral
             if (!Runtime::getInstance()->extensionAvailable('mcrypt')) {
                 throw new IllegalStateException('Backing "mcrypt" required but extension not available.');
             }
             $engine = mcrypt_module_open(MCRYPT_DES, '', 'ecb', '');
             $engineiv = mcrypt_create_iv(mcrypt_enc_get_iv_size($engine), MCRYPT_RAND);
             $key = substr(md5(uniqid()), 0, mcrypt_enc_get_key_size($engine));
             mcrypt_generic_init($engine, $key, $engineiv);
             return self::setBacking(function ($value) use($engine) {
                 return mcrypt_generic($engine, $value);
             }, function ($value) use($engine) {
                 return rtrim(mdecrypt_generic($engine, $value), "");
             });
         case self::BACKING_PLAINTEXT:
             return self::setBacking(function ($value) {
                 return base64_encode($value);
             }, function ($value) {
                 return base64_decode($value);
             });
         default:
             throw new IllegalArgumentException('Invalid backing given: ' . \xp::stringOf($type));
     }
 }
Example #30
0
 /**
  * Decrypts a string encoded with mcrypt.<br />
  * If mcrypt is not available, decrypts with xor
  * 
  * @param string $text      The text to decode
  * @param string $key       [optionnal] The key to use. Default is the application key
  * @return string           The decrypted string
  */
 public static function decrypt($text, $key = null)
 {
     // Get the application key if no key is given
     if ($key === null) {
         $key = self::_getKey();
     }
     // Use openssl_decrypt with PHP >= 5.3.0
     if (Config::get('general.crypt_method', 'openssl') === 'openssl' && function_exists('openssl_decrypt') && in_array('BF-ECB', openssl_get_cipher_methods())) {
         $method = 'BF-ECB';
         $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
         $msg = openssl_decrypt(strtr($text, '-_', '+/'), 'BF-ECB', $key);
     } else {
         if (function_exists('mcrypt_encrypt')) {
             $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
             $iv = mcrypt_create_iv($size, MCRYPT_RAND);
             $text = base64_decode(str_pad(strtr($text, '-_', '+/'), strlen($text) % 4, '=', STR_PAD_RIGHT));
             $msg = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv), "");
         } else {
             // ... else decrypt with xor technique
             $n = mb_strlen($text, '8bit');
             $m = mb_strlen($key, '8bit');
             if ($n !== $m) {
                 $key = mb_substr(str_repeat($key, ceil($n / $m)), 0, $n, '8bit');
             }
             $msg = base64_decode($text) ^ $key;
         }
     }
     // If zlib is active we uncompress the crypted value
     if (function_exists('gzinflate')) {
         $msg = @gzinflate($msg);
     }
     // To avoid truncated encoded strings
     @(list($hash, $value) = explode('~~~', $msg));
     if (self::check($value, $hash)) {
         return $value;
     }
     return false;
 }