Author: Jim Wigginton (terrafrost@php.net)
Inheritance: extends Rijndael
Exemplo n.º 1
0
 public static function decrypt($data, $k, $iv)
 {
     $aes = new AES(MCRYPT_MODE_CBC);
     $aes->setKey($k);
     $aes->setIV($iv);
     return $aes->decrypt($data);
 }
Exemplo n.º 2
0
 private function cipher()
 {
     switch ($this->header['enc']) {
         case 'A128GCM':
         case 'A256GCM':
             throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');
         case 'A128CBC-HS256':
         case 'A256CBC-HS512':
             $cipher = new AES(AES::MODE_CBC);
             break;
         default:
             throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');
     }
     switch ($this->header['enc']) {
         case 'A128GCM':
         case 'A128CBC-HS256':
             $cipher->setBlockLength(128);
             break;
         case 'A256GCM':
         case 'A256CBC-HS512':
             $cipher->setBlockLength(256);
             break;
         default:
             throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');
     }
     return $cipher;
 }
Exemplo n.º 3
0
Arquivo: AES.php Projeto: mywin/mywin
 public static function decrypt($data)
 {
     $aes = new AES(AES::MODE_ECB);
     $aes->setKey(self::$key);
     $data = pack("H*", $data);
     $data = $aes->decrypt($data);
     return $data;
 }
Exemplo n.º 4
0
 /**
  * Decrypt a string.
  *
  * @param string $text The content for the decryption.
  *
  * @return string The decrypted string
  */
 public function Decrypt($text)
 {
     $text = $this->splitText($text);
     // Set the iv.
     $this->aes->setIV($text[0]);
     // Decrypt.
     return $this->aes->decrypt($text[1]);
 }
 /**
  * @return mixed
  */
 public function decrypt($text, $key, $options = array())
 {
     $processed_text = '';
     $disable_base64 = array_key_exists('base64', $options) && $options['base64'] == FALSE;
     // If base64 encoding is not disabled.
     if (!$disable_base64) {
         $text = base64_decode($text);
     }
     $aes = new AES();
     $aes->setKey($key);
     $processed_text = $aes->decrypt($text);
     return trim($processed_text);
 }
 /**
  * Process the launchkey option to prepare for usage within the plugin.  The option will have encrypted attributes
  * decrypted as well as set default values for any missing or unset attributes.
  *
  * @since 1.0.0
  *
  * @param $input
  *
  * @return array
  */
 public function post_get_option_filter($input)
 {
     // Define the defaults for attributes
     $defaults = static::get_defaults();
     // If the input is empty (null) set it to an empty array
     $input ?: array();
     // Merge the input array over the defaults array to set any know data to the response
     $output = array_merge($defaults, $input);
     // If the secret key attribute is not empty, decrypt it
     if (!empty($input[LaunchKey_WP_Options::OPTION_SECRET_KEY])) {
         $key = md5($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]);
         if (empty($this->cache[$key])) {
             /**
              * Use the rocket key as the IV. If null, use the static value.
              * @link https://docs.launchkey.com/glossary.html#term-iv
              */
             $iv = empty($output[LaunchKey_WP_Options::OPTION_ROCKET_KEY]) ? static::STATIC_IV : $output[LaunchKey_WP_Options::OPTION_ROCKET_KEY];
             $this->crypt_aes->setIV($iv);
             /**
              * Decrypt the Base64 decoded string and set it as the output value
              * @link https://docs.launchkey.com/glossary.html#term-base64
              */
             $this->cache[$key] = $this->crypt_aes->decrypt(base64_decode($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]));
         }
         $output[LaunchKey_WP_Options::OPTION_SECRET_KEY] = $this->cache[$key];
     }
     // If the private key attribute is not empty, decrypt it
     if (!empty($input[LaunchKey_WP_Options::OPTION_PRIVATE_KEY])) {
         $key = md5($input[LaunchKey_WP_Options::OPTION_PRIVATE_KEY]);
         if (empty($this->cache[$key])) {
             /**
              * Use the decrypted secret key as the IV. If null, use the static value.
              * @link https://docs.launchkey.com/glossary.html#term-iv
              */
             $iv = empty($output[LaunchKey_WP_Options::OPTION_SECRET_KEY]) ? static::STATIC_IV : $output[LaunchKey_WP_Options::OPTION_SECRET_KEY];
             $this->crypt_aes->setIV($iv);
             /**
              * Decrypt the Base64 decoded string and set it as the output value
              * @link https://docs.launchkey.com/glossary.html#term-base64
              *
              * We are suppressing errors as
              */
             $this->cache[$key] = @$this->crypt_aes->decrypt(base64_decode($input[LaunchKey_WP_Options::OPTION_PRIVATE_KEY]));
         }
         $output[LaunchKey_WP_Options::OPTION_PRIVATE_KEY] = $this->cache[$key];
     }
     return $output;
 }
Exemplo n.º 7
0
 /**
  * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  * @param string $authenticatedCiphertext
  * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  * @return string plaintext
  * @throws \Exception If the HMAC does not match
  */
 public function decrypt($authenticatedCiphertext, $password = '')
 {
     if ($password === '') {
         $password = $this->config->getSystemValue('secret');
     }
     $this->cipher->setPassword($password);
     $parts = explode('|', $authenticatedCiphertext);
     if (sizeof($parts) !== 3) {
         throw new \Exception('Authenticated ciphertext could not be decoded.');
     }
     $ciphertext = hex2bin($parts[0]);
     $iv = $parts[1];
     $hmac = hex2bin($parts[2]);
     $this->cipher->setIV($iv);
     if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $password), $hmac)) {
         throw new \Exception('HMAC does not match.');
     }
     return $this->cipher->decrypt($ciphertext);
 }
Exemplo n.º 8
0
 /**
  * Returns a SymmetricKey object baesd on a PBES2 $algo
  *
  * @access public
  * @param string $algo
  */
 static function getPBES2EncryptionObject($algo)
 {
     switch ($algo) {
         case 'desCBC':
             $cipher = new TripleDES(BlockCipher::MODE_CBC);
             break;
         case 'des-EDE3-CBC':
             $cipher = new TripleDES(BlockCipher::MODE_CBC);
             break;
         case 'rc2CBC':
             $cipher = new RC2(BlockCipher::MODE_CBC);
             // in theory this can be changed
             $cipher->setKeyLength(128);
             break;
         case 'rc5-CBC-PAD':
             throw new UnsupportedAlgorithmException('rc5-CBC-PAD is not supported for PBES2 PKCS#8 keys');
         case 'aes128-CBC-PAD':
         case 'aes192-CBC-PAD':
         case 'aes256-CBC-PAD':
             $cipher = new AES(BlockCipher::MODE_CBC);
             $cipher->setKeyLength(substr($algo, 3, 3));
             break;
         default:
             throw new UnsupportedAlgorithmException("{$algo} is not supported");
     }
     return $cipher;
 }
Exemplo n.º 9
0
 /**
  * Break a public or private key down into its constituant components
  *
  * @access private
  * @see _convertPublicKey()
  * @see _convertPrivateKey()
  * @param String $key        	
  * @param Integer $type        	
  * @return Array
  */
 function _parseKey($key, $type)
 {
     if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
         return false;
     }
     switch ($type) {
         case CRYPT_RSA_PUBLIC_FORMAT_RAW:
             if (!is_array($key)) {
                 return false;
             }
             $components = array();
             switch (true) {
                 case isset($key['e']):
                     $components['publicExponent'] = $key['e']->copy();
                     break;
                 case isset($key['exponent']):
                     $components['publicExponent'] = $key['exponent']->copy();
                     break;
                 case isset($key['publicExponent']):
                     $components['publicExponent'] = $key['publicExponent']->copy();
                     break;
                 case isset($key[0]):
                     $components['publicExponent'] = $key[0]->copy();
             }
             switch (true) {
                 case isset($key['n']):
                     $components['modulus'] = $key['n']->copy();
                     break;
                 case isset($key['modulo']):
                     $components['modulus'] = $key['modulo']->copy();
                     break;
                 case isset($key['modulus']):
                     $components['modulus'] = $key['modulus']->copy();
                     break;
                 case isset($key[1]):
                     $components['modulus'] = $key[1]->copy();
             }
             return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
         case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
         case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
             /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
                                "outside the scope" of PKCS#1.  PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
                                protect private keys, however, that's not what OpenSSL* does.  OpenSSL protects private keys by adding
                                two new "fields" to the key - DEK-Info and Proc-Type.  These fields are discussed here:
             
                                http://tools.ietf.org/html/rfc1421#section-4.6.1.1
                                http://tools.ietf.org/html/rfc1421#section-4.6.1.3
             
                                DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
                                DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
                                function.  As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
                                own implementation.  ie. the implementation *is* the standard and any bugs that may exist in that
                                implementation are part of the standard, as well.
             
                                * OpenSSL is the de facto standard.  It's utilized by OpenSSH and other projects */
             if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
                 $iv = pack('H*', trim($matches[2]));
                 $symkey = pack('H*', md5($this->password . substr($iv, 0, 8)));
                 // symkey is short for symmetric key
                 $symkey .= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
                 // remove the Proc-Type / DEK-Info sections as they're no longer needed
                 $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
                 $ciphertext = $this->_extractBER($key);
                 if ($ciphertext === false) {
                     $ciphertext = $key;
                 }
                 switch ($matches[1]) {
                     case 'AES-256-CBC':
                         $crypto = new AES();
                         break;
                     case 'AES-128-CBC':
                         $symkey = substr($symkey, 0, 16);
                         $crypto = new AES();
                         break;
                     case 'DES-EDE3-CFB':
                         $crypto = new TripleDES(CRYPT_DES_MODE_CFB);
                         break;
                     case 'DES-EDE3-CBC':
                         $symkey = substr($symkey, 0, 24);
                         $crypto = new TripleDES();
                         break;
                     case 'DES-CBC':
                         $crypto = new DES();
                         break;
                     default:
                         return false;
                 }
                 $crypto->setKey($symkey);
                 $crypto->setIV($iv);
                 $decoded = $crypto->decrypt($ciphertext);
             } else {
                 $decoded = $this->_extractBER($key);
             }
             if ($decoded !== false) {
                 $key = $decoded;
             }
             $components = array();
             if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
                 return false;
             }
             if ($this->_decodeLength($key) != strlen($key)) {
                 return false;
             }
             $tag = ord($this->_string_shift($key));
             /*
              * intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 631 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: INTEGER :00 7:d=1 hl=2 l= 13 cons: SEQUENCE 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 20:d=2 hl=2 l= 0 prim: NULL 22:d=1 hl=4 l= 609 prim: OCTET STRING
              */
             if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "0") {
                 $this->_string_shift($key, 3);
                 $tag = CRYPT_RSA_ASN1_SEQUENCE;
             }
             if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
                 /*
                  * intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 290 cons: SEQUENCE 4:d=1 hl=2 l= 13 cons: SEQUENCE 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 17:d=2 hl=2 l= 0 prim: NULL 19:d=1 hl=4 l= 271 prim: BIT STRING
                  */
                 $this->_string_shift($key, $this->_decodeLength($key));
                 $tag = ord($this->_string_shift($key));
                 // skip over the BIT STRING / OCTET STRING tag
                 $this->_decodeLength($key);
                 // skip over the BIT STRING / OCTET STRING length
                 // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
                 // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
                 // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
                 if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
                     $this->_string_shift($key);
                 }
                 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
                     return false;
                 }
                 if ($this->_decodeLength($key) != strlen($key)) {
                     return false;
                 }
                 $tag = ord($this->_string_shift($key));
             }
             if ($tag != CRYPT_RSA_ASN1_INTEGER) {
                 return false;
             }
             $length = $this->_decodeLength($key);
             $temp = $this->_string_shift($key, $length);
             if (strlen($temp) != 1 || ord($temp) > 2) {
                 $components['modulus'] = new BigInteger($temp, 256);
                 $this->_string_shift($key);
                 // skip over CRYPT_RSA_ASN1_INTEGER
                 $length = $this->_decodeLength($key);
                 $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
                 return $components;
             }
             if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
                 return false;
             }
             $length = $this->_decodeLength($key);
             $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256));
             if (!empty($key)) {
                 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
                     return false;
                 }
                 $this->_decodeLength($key);
                 while (!empty($key)) {
                     if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
                         return false;
                     }
                     $this->_decodeLength($key);
                     $key = substr($key, 1);
                     $length = $this->_decodeLength($key);
                     $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
                     $this->_string_shift($key);
                     $length = $this->_decodeLength($key);
                     $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
                     $this->_string_shift($key);
                     $length = $this->_decodeLength($key);
                     $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256);
                 }
             }
             return $components;
         case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
             $parts = explode(' ', $key, 3);
             $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
             if ($key === false) {
                 return false;
             }
             $comment = isset($parts[2]) ? $parts[2] : false;
             $cleanup = substr($key, 0, 11) == "ssh-rsa";
             if (strlen($key) <= 4) {
                 return false;
             }
             extract(unpack('Nlength', $this->_string_shift($key, 4)));
             $publicExponent = new BigInteger($this->_string_shift($key, $length), -256);
             if (strlen($key) <= 4) {
                 return false;
             }
             extract(unpack('Nlength', $this->_string_shift($key, 4)));
             $modulus = new BigInteger($this->_string_shift($key, $length), -256);
             if ($cleanup && strlen($key)) {
                 if (strlen($key) <= 4) {
                     return false;
                 }
                 extract(unpack('Nlength', $this->_string_shift($key, 4)));
                 $realModulus = new BigInteger($this->_string_shift($key, $length), -256);
                 return strlen($key) ? false : array('modulus' => $realModulus, 'publicExponent' => $modulus, 'comment' => $comment);
             } else {
                 return strlen($key) ? false : array('modulus' => $modulus, 'publicExponent' => $publicExponent, 'comment' => $comment);
             }
             // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
             // http://en.wikipedia.org/wiki/XML_Signature
         // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
         // http://en.wikipedia.org/wiki/XML_Signature
         case CRYPT_RSA_PRIVATE_FORMAT_XML:
         case CRYPT_RSA_PUBLIC_FORMAT_XML:
             $this->components = array();
             $xml = xml_parser_create('UTF-8');
             xml_set_object($xml, $this);
             xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
             xml_set_character_data_handler($xml, '_data_handler');
             // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
             if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
                 return false;
             }
             return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
             // from PuTTY's SSHPUBK.C
         // from PuTTY's SSHPUBK.C
         case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
             $components = array();
             $key = preg_split('#\\r\\n|\\r|\\n#', $key);
             $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
             if ($type != 'ssh-rsa') {
                 return false;
             }
             $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
             $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
             $publicLength = trim(preg_replace('#Public-Lines: (\\d+)#', '$1', $key[3]));
             $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
             $public = substr($public, 11);
             extract(unpack('Nlength', $this->_string_shift($public, 4)));
             $components['publicExponent'] = new BigInteger($this->_string_shift($public, $length), -256);
             extract(unpack('Nlength', $this->_string_shift($public, 4)));
             $components['modulus'] = new BigInteger($this->_string_shift($public, $length), -256);
             $privateLength = trim(preg_replace('#Private-Lines: (\\d+)#', '$1', $key[$publicLength + 4]));
             $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
             switch ($encryption) {
                 case 'aes256-cbc':
                     $symkey = '';
                     $sequence = 0;
                     while (strlen($symkey) < 32) {
                         $temp = pack('Na*', $sequence++, $this->password);
                         $symkey .= pack('H*', sha1($temp));
                     }
                     $symkey = substr($symkey, 0, 32);
                     $crypto = new AES();
             }
             if ($encryption != 'none') {
                 $crypto->setKey($symkey);
                 $crypto->disablePadding();
                 $private = $crypto->decrypt($private);
                 if ($private === false) {
                     return false;
                 }
             }
             extract(unpack('Nlength', $this->_string_shift($private, 4)));
             if (strlen($private) < $length) {
                 return false;
             }
             $components['privateExponent'] = new BigInteger($this->_string_shift($private, $length), -256);
             extract(unpack('Nlength', $this->_string_shift($private, 4)));
             if (strlen($private) < $length) {
                 return false;
             }
             $components['primes'] = array(1 => new BigInteger($this->_string_shift($private, $length), -256));
             extract(unpack('Nlength', $this->_string_shift($private, 4)));
             if (strlen($private) < $length) {
                 return false;
             }
             $components['primes'][] = new BigInteger($this->_string_shift($private, $length), -256);
             $temp = $components['primes'][1]->subtract($this->one);
             $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
             $temp = $components['primes'][2]->subtract($this->one);
             $components['exponents'][] = $components['publicExponent']->modInverse($temp);
             extract(unpack('Nlength', $this->_string_shift($private, 4)));
             if (strlen($private) < $length) {
                 return false;
             }
             $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($private, $length), -256));
             return $components;
     }
 }
Exemplo n.º 10
0
 /**
  * Decryption using openssl's AES or phpseclib's AES
  * (phpseclib uses mcrypt when it is available)
  *
  * @param string $encdata encrypted data
  * @param string $secret  the secret
  *
  * @return string|bool original data, false on error
  */
 public function cookieDecrypt($encdata, $secret)
 {
     $data = json_decode($encdata, true);
     if (!is_array($data) || !isset($data['mac']) || !isset($data['iv']) || !isset($data['payload']) || !is_string($data['mac']) || !is_string($data['iv']) || !is_string($data['payload'])) {
         return false;
     }
     $mac_secret = $this->getMACSecret($secret);
     $aes_secret = $this->getAESSecret($secret);
     $newmac = hash_hmac('sha1', $data['iv'] . $data['payload'], $mac_secret);
     if (!hash_equals($data['mac'], $newmac)) {
         return false;
     }
     if (self::useOpenSSL()) {
         return openssl_decrypt($data['payload'], 'AES-128-CBC', $secret, 0, base64_decode($data['iv']));
     } else {
         $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
         $cipher->setIV(base64_decode($data['iv']));
         $cipher->setKey($aes_secret);
         return $cipher->decrypt(base64_decode($data['payload']));
     }
 }
Exemplo n.º 11
0
 /**
  * @param string $encrypted
  *
  * @return bool|string
  */
 public function decrypt($encrypted)
 {
     return $this->aes->decrypt(base64_decode($encrypted));
 }
 /**
  * @inheritDoc
  */
 public function decrypt($encryptedValue, $key, $iv)
 {
     $this->aes->setKey($key);
     $this->aes->setIV($iv);
     return $this->aes->decrypt($encryptedValue);
 }
Exemplo n.º 13
0
 /**
  * Convert a private key to the appropriate format.
  *
  * @access private
  * @see    setPrivateKeyFormat()
  *
  * @param String $RSAPrivateKey
  *
  * @return String
  */
 function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
 {
     $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML;
     $num_primes = count($primes);
     $raw = array('version' => $num_primes == 2 ? chr(0) : chr(1), 'modulus' => $n->toBytes($signed), 'publicExponent' => $e->toBytes($signed), 'privateExponent' => $d->toBytes($signed), 'prime1' => $primes[1]->toBytes($signed), 'prime2' => $primes[2]->toBytes($signed), 'exponent1' => $exponents[1]->toBytes($signed), 'exponent2' => $exponents[2]->toBytes($signed), 'coefficient' => $coefficients[2]->toBytes($signed));
     // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
     // call _convertPublicKey() instead.
     switch ($this->privateKeyFormat) {
         case self::PRIVATE_FORMAT_XML:
             if ($num_primes != 2) {
                 return false;
             }
             return "<RSAKeyValue>\r\n" . '  <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" . '  <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" . '  <P>' . base64_encode($raw['prime1']) . "</P>\r\n" . '  <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" . '  <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" . '  <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" . '  <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" . '  <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" . '</RSAKeyValue>';
             break;
         case self::PRIVATE_FORMAT_PUTTY:
             if ($num_primes != 2) {
                 return false;
             }
             $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
             $encryption = !empty($this->password) || is_string($this->password) ? 'aes256-cbc' : 'none';
             $key .= $encryption;
             $key .= "\r\nComment: " . $this->comment . "\r\n";
             $public = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']);
             $source = pack('Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen($this->comment), $this->comment, strlen($public), $public);
             $public = base64_encode($public);
             $key .= "Public-Lines: " . (strlen($public) + 63 >> 6) . "\r\n";
             $key .= chunk_split($public, 64);
             $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']);
             if (empty($this->password) && !is_string($this->password)) {
                 $source .= pack('Na*', strlen($private), $private);
                 $hashkey = 'putty-private-key-file-mac-key';
             } else {
                 $private .= Random::string(16 - (strlen($private) & 15));
                 $source .= pack('Na*', strlen($private), $private);
                 $sequence = 0;
                 $symkey = '';
                 while (strlen($symkey) < 32) {
                     $temp = pack('Na*', $sequence++, $this->password);
                     $symkey .= pack('H*', sha1($temp));
                 }
                 $symkey = substr($symkey, 0, 32);
                 $crypto = new AES();
                 $crypto->setKey($symkey);
                 $crypto->disablePadding();
                 $private = $crypto->encrypt($private);
                 $hashkey = 'putty-private-key-file-mac-key' . $this->password;
             }
             $private = base64_encode($private);
             $key .= 'Private-Lines: ' . (strlen($private) + 63 >> 6) . "\r\n";
             $key .= chunk_split($private, 64);
             $hash = new Hash('sha1');
             $hash->setKey(pack('H*', sha1($hashkey)));
             $key .= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
             return $key;
         default:
             // eg. self::PRIVATE_FORMAT_PKCS1
             $components = array();
             foreach ($raw as $name => $value) {
                 $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
             }
             $RSAPrivateKey = implode('', $components);
             if ($num_primes > 2) {
                 $OtherPrimeInfos = '';
                 for ($i = 3; $i <= $num_primes; $i++) {
                     // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
                     //
                     // OtherPrimeInfo ::= SEQUENCE {
                     //     prime             INTEGER,  -- ri
                     //     exponent          INTEGER,  -- di
                     //     coefficient       INTEGER   -- ti
                     // }
                     $OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
                     $OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
                     $OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
                     $OtherPrimeInfos .= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
                 }
                 $RSAPrivateKey .= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
             }
             $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
             if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) {
                 $rsaOID = pack('H*', '300d06092a864886f70d0101010500');
                 // hex version of MA0GCSqGSIb3DQEBAQUA
                 $RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_INTEGER, "", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
                 $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
                 if (!empty($this->password) || is_string($this->password)) {
                     $salt = Random::string(8);
                     $iterationCount = 2048;
                     $crypto = new DES();
                     $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
                     $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
                     $parameters = pack('Ca*a*Ca*N', self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt, self::ASN1_INTEGER, $this->_encodeLength(4), $iterationCount);
                     $pbeWithMD5AndDES_CBC = "*†H†÷\r";
                     $encryptionAlgorithm = pack('Ca*a*Ca*a*', self::ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, self::ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters);
                     $RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
                     $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
                     $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END ENCRYPTED PRIVATE KEY-----';
                 } else {
                     $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END PRIVATE KEY-----';
                 }
                 return $RSAPrivateKey;
             }
             if (!empty($this->password) || is_string($this->password)) {
                 $iv = Random::string(8);
                 $symkey = pack('H*', md5($this->password . $iv));
                 // symkey is short for symmetric key
                 $symkey .= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
                 $des = new TripleDES();
                 $des->setKey($symkey);
                 $des->setIV($iv);
                 $iv = strtoupper(bin2hex($iv));
                 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: DES-EDE3-CBC,{$iv}\r\n" . "\r\n" . chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) . '-----END RSA PRIVATE KEY-----';
             } else {
                 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END RSA PRIVATE KEY-----';
             }
             return $RSAPrivateKey;
     }
 }
Exemplo n.º 14
0
 public static function getCipher($algo)
 {
     $cipher = NULL;
     switch ($algo) {
         case 2:
             $cipher = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
             $key_bytes = 24;
             $key_block_bytes = 8;
             break;
         case 3:
             /* Horde change
                if(defined('MCRYPT_CAST_128')) {
                  $cipher = new MCryptWrapper(MCRYPT_CAST_128);
                }
                */
             $cipher = new Horde_Pgp_Crypt_Cast128();
             /* End Horde Change */
             break;
             /* Horde change */
         /* Horde change */
         case 4:
             $cipher = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CFB);
             $key_bytes = 16;
             break;
             /* End Horde Change */
         /* End Horde Change */
         case 7:
             $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
             $cipher->setKeyLength(128);
             break;
         case 8:
             $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
             $cipher->setKeyLength(192);
             break;
         case 9:
             $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
             $cipher->setKeyLength(256);
             break;
             /* Horde change */
         /* Horde change */
         case 10:
             $cipher = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CFB);
             $key_bytes = 32;
             break;
             /* End Horde Change */
     }
     if (!$cipher) {
         return array(NULL, NULL, NULL);
     }
     // Unsupported cipher
     if (!isset($key_bytes)) {
         $key_bytes = isset($cipher->key_size) ? $cipher->key_size : $cipher->key_length;
     }
     if (!isset($key_block_bytes)) {
         $key_block_bytes = $cipher->block_size;
     }
     return array($cipher, $key_bytes, $key_block_bytes);
 }
Exemplo n.º 15
0
 /**
  * Returns a cipher object corresponding to a string
  *
  * @access public
  * @param string $algo
  * @return string
  * @throws \UnexpectedValueException if the encryption algorithm is unsupported
  */
 static function getEncryptionObject($algo)
 {
     $modes = '(CBC|ECB|CFB|OFB|CTR)';
     switch (true) {
         case preg_match("#^AES-(128|192|256)-{$modes}\$#", $algo, $matches):
             $cipher = new AES(self::getEncryptionMode($matches[2]));
             $cipher->setKeyLength($matches[1]);
             return $cipher;
         case preg_match("#^DES-EDE3-{$modes}\$#", $algo, $matches):
             return new TripleDES(self::getEncryptionMode($matches[1]));
         case preg_match("#^DES-{$modes}\$#", $algo, $matches):
             return new DES(self::getEncryptionMode($matches[1]));
         default:
             throw new \UnexpectedValueException('Unsupported encryption algorithmn');
     }
 }
Exemplo n.º 16
0
 /**
  * Convert a private key to the appropriate format.
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @param \phpseclib\Math\BigInteger $d
  * @param array $primes
  * @param array $exponents
  * @param array $coefficients
  * @param string $password optional
  * @return string
  */
 static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, $primes, $exponents, $coefficients, $password = '')
 {
     if (count($primes) != 2) {
         return false;
     }
     $raw = array('modulus' => $n->toBytes(true), 'publicExponent' => $e->toBytes(true), 'privateExponent' => $d->toBytes(true), 'prime1' => $primes[1]->toBytes(true), 'prime2' => $primes[2]->toBytes(true), 'exponent1' => $exponents[1]->toBytes(true), 'exponent2' => $exponents[2]->toBytes(true), 'coefficient' => $coefficients[2]->toBytes(true));
     $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
     $encryption = !empty($password) || is_string($password) ? 'aes256-cbc' : 'none';
     $key .= $encryption;
     $key .= "\r\nComment: " . self::$comment . "\r\n";
     $public = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']);
     $source = pack('Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen(self::$comment), self::$comment, strlen($public), $public);
     $public = Base64::encode($public);
     $key .= "Public-Lines: " . (strlen($public) + 63 >> 6) . "\r\n";
     $key .= chunk_split($public, 64);
     $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']);
     if (empty($password) && !is_string($password)) {
         $source .= pack('Na*', strlen($private), $private);
         $hashkey = 'putty-private-key-file-mac-key';
     } else {
         $private .= Random::string(16 - (strlen($private) & 15));
         $source .= pack('Na*', strlen($private), $private);
         $crypto = new AES();
         $crypto->setKey(static::generateSymmetricKey($password, 32));
         $crypto->setIV(str_repeat("", $crypto->getBlockLength() >> 3));
         $crypto->disablePadding();
         $private = $crypto->encrypt($private);
         $hashkey = 'putty-private-key-file-mac-key' . $password;
     }
     $private = Base64::encode($private);
     $key .= 'Private-Lines: ' . (strlen($private) + 63 >> 6) . "\r\n";
     $key .= chunk_split($private, 64);
     $hash = new Hash('sha1');
     $hash->setKey(sha1($hashkey, true));
     $key .= 'Private-MAC: ' . Hex::encode($hash->hash($source)) . "\r\n";
     return $key;
 }
Exemplo n.º 17
0
 /**
  * @param $encryptedMessage
  * @return String
  */
 public function decrypt($encryptedMessage)
 {
     return $this->cipher->decrypt(base64_decode($encryptedMessage));
 }
Exemplo n.º 18
0
 /**
  * Decryption using openssl's AES or phpseclib's AES
  * (phpseclib uses mcrypt when it is available)
  *
  * @param string $encdata encrypted data
  * @param string $secret  the secret
  *
  * @return string original data
  */
 public function cookieDecrypt($encdata, $secret)
 {
     if (is_null($this->_cookie_iv)) {
         $this->_cookie_iv = base64_decode($_COOKIE['pma_iv-' . $GLOBALS['server']], true);
     }
     if (mb_strlen($this->_cookie_iv, '8bit') < $this->getIVSize()) {
         $this->createIV();
     }
     if (self::useOpenSSL()) {
         return openssl_decrypt($encdata, 'AES-128-CBC', $secret, 0, $this->_cookie_iv);
     } else {
         $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
         $cipher->setIV($this->_cookie_iv);
         $cipher->setKey($secret);
         return $cipher->decrypt(base64_decode($encdata));
     }
 }
Exemplo n.º 19
0
 public function testGFSBox256()
 {
     $aes = new AES();
     $aes->setKey(pack('H*', '00000000000000000000000000000000' . '00000000000000000000000000000000'));
     $aes->setIV(pack('H*', '00000000000000000000000000000000'));
     $aes->disablePadding();
     $aes->setPreferredEngine($this->engine);
     $this->_checkEngine($aes);
     $result = bin2hex($aes->encrypt(pack('H*', '014730f80ac625fe84f026c60bfd547d')));
     $this->assertSame($result, '5c9d844ed46f9885085e5d6a4f94c7d7');
     $result = bin2hex($aes->encrypt(pack('H*', '0b24af36193ce4665f2825d7b4749c98')));
     $this->assertSame($result, 'a9ff75bd7cf6613d3731c77c3b6d0c04');
     $result = bin2hex($aes->encrypt(pack('H*', '761c1fe41a18acf20d241650611d90f1')));
     $this->assertSame($result, '623a52fcea5d443e48d9181ab32c7421');
     $result = bin2hex($aes->encrypt(pack('H*', '8a560769d605868ad80d819bdba03771')));
     $this->assertSame($result, '38f2c7ae10612415d27ca190d27da8b4');
     $result = bin2hex($aes->encrypt(pack('H*', '91fbef2d15a97816060bee1feaa49afe')));
     $this->assertSame($result, '1bc704f1bce135ceb810341b216d7abe');
 }
Exemplo n.º 20
0
 /**
  * Returns the encryption cipher
  */
 private static function getCipher()
 {
     $cipher = new AES(AES::MODE_CBC);
     $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
     return $cipher;
 }
Exemplo n.º 21
0
 /**
  */
 public function generateKey($opts)
 {
     $skey = $this->_generateSecretKeyPacket($opts['keylength'], 'OpenPGP_SecretKeyPacket');
     $id = new Horde_Mail_Rfc822_Address($opts['email']);
     if (strlen($opts['comment'])) {
         $id->comment[] = $opts['comment'];
     }
     if (strlen($opts['name'])) {
         $id->personal = $opts['name'];
     }
     /* This is the private key we are creating. */
     $key = new OpenPGP_Message(array($skey, new OpenPGP_UserIDPacket($id->writeAddress(array('comment' => true)))));
     $rsa = OpenPGP_Crypt_RSA::convert_private_key($skey);
     $rsa->setHash(Horde_String::lower($opts['hash']));
     $rsa_sign_func = array('RSA' => array($opts['hash'] => function ($data) use($rsa) {
         return array($rsa->sign($data));
     }));
     /* Create signature packet. */
     $sig = new OpenPGP_SignaturePacket($key, 'RSA', $opts['hash']);
     /* "Generic certification of a User ID and Public-Key packet." */
     $sig->signature_type = 0x10;
     /* Add subpacket information. */
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x3));
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_PreferredSymmetricAlgorithmsPacket(array(0x9, 0x8, 0x7, 0x2));
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_PreferredHashAlgorithmsPacket(array(0x8, 0x9, 0xa, 0xb, 0x2));
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_PreferredCompressionAlgorithmsPacket(array(0x2, 0x1));
     $ks_prefs = new OpenPGP_SignaturePacket_KeyServerPreferencesPacket();
     $ks_prefs->no_modify = true;
     $sig->hashed_subpackets[] = $ks_prefs;
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_FeaturesPacket(array(0x1));
     if (isset($opts['expire'])) {
         $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyExpirationTimePacket($opts['expire'] - time());
     }
     $sig->unhashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket(substr($skey->fingerprint, -16));
     $key[] = $sig;
     /* Create self-signature. */
     $sig->sign_data($rsa_sign_func);
     /* OpenPGP currently (as of April 2015) encrypts passphrases w/
      * AES-128 & SHA-1, so use this strategy. */
     if (strlen($opts['passphrase'])) {
         $cipher = new Crypt\AES(CRYPT_AES_MODE_CFB);
         $cipher->setKeyLength(128);
         $s2k = new OpenPGP_S2K(Crypt\Random::String(8), 2);
         $cipher->setKey($s2k->make_key($opts['passphrase'], 16));
         $iv = Crypt\Random::String(16);
         $this->_encryptPrivateKey($skey, $cipher, $s2k, $iv);
     }
     /* Encryption subkey. See RFC 4880 [5.5.1.2] (by convention, top-level
      * key is used for signing and subkeys are used for encryption) */
     $ekey = $this->_generateSecretKeyPacket($opts['keylength'], 'OpenPGP_SecretSubkeyPacket');
     /* Computing signature: RFC 4880 [5.2.4] */
     $sig = new OpenPGP_SignaturePacket(implode('', $skey->fingerprint_material()) . implode('', $ekey->fingerprint_material()), 'RSA', $opts['hash']);
     /* This is a "Subkey Binding Signature". */
     $sig->signature_type = 0x18;
     $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0xc));
     $sig->unhashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket(substr($skey->fingerprint, -16));
     $sig->sign_data($rsa_sign_func);
     if (strlen($opts['passphrase'])) {
         $this->_encryptPrivateKey($ekey, $cipher, $s2k, $iv);
     }
     $key[] = $ekey;
     $key[] = $sig;
     return new Horde_Pgp_Element_PrivateKey($key);
 }