Exemplo n.º 1
0
function AESDecrypt($ciphertext, $key, $IV)
{
    $aes = new Crypt_AES(CRYPT_MODE_ECB);
    $aes->setKey(characet($key));
    $aes->setIV(characet($IV));
    return $aes->decrypt(hex2bin($ciphertext));
}
Exemplo n.º 2
0
Arquivo: JWE.php Projeto: nask0/jose
 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 Crypt_AES(CRYPT_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;
 }
function _pugpig_bbappworld_decrypt($base64_encrypted, $password)
{
    $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB);
    // keys are null-padded to the closest valid size
    // longer than the longest key and it's truncated
    $cipher->setKey($password);
    return $cipher->decrypt(base64_decode($base64_encrypted));
}
 protected function decodeResponse($received)
 {
     $aes = new Crypt_AES();
     $aes->setKey($this->key);
     $data = $aes->decrypt(base64_decode(substr($received, 28)));
     $decoder = new XmlrpcDecoder();
     return $decoder->decodeResponse($data);
 }
Exemplo n.º 5
0
 /**
  * Returns an instance of the Crypto library
  * @return Crypt_AES
  */
 public function getApi()
 {
     if (is_null($this->api)) {
         $this->api = new AES();
         $this->api->setKey($this->getKey());
     }
     return $this->api;
 }
 /**
  * Decrypt the provided data using AES cryptography with the provided key and IV
  *
  * @param string $data Data to decrypt
  * @param string $key Cipher key used to encrypt the data
  * @param string $iv IV used to encrypt the data
  * @param bool $base64Encoded Is the provided data Base64 encoded (defaults to true)
  * @return string Unencrypted data
  */
 public function decryptAES($data, $key, $iv, $base64Encoded = true)
 {
     $data = $base64Encoded ? base64_decode($data) : $data;
     $cipher = new \Crypt_AES();
     $cipher->setKey($key);
     $cipher->setIV($iv);
     $cipher->disablePadding();
     $decrypted = rtrim($cipher->decrypt($data));
     return $decrypted;
 }
Exemplo n.º 7
0
 /**
  * @group github451
  */
 public function testKeyPaddingAES()
 {
     // same as the above - just with a different ciphertext
     $aes = new Crypt_AES();
     $aes->disablePadding();
     $aes->setKey(pack('H*', '2b7e151628aed2a6abf7158809cf4f3c762e7160'));
     // 160-bit key. AES should null pad to 192-bits
     $ciphertext = $aes->encrypt(pack('H*', '3243f6a8885a308d313198a2e0370734'));
     $this->assertEquals($ciphertext, pack('H*', 'c109292b173f841b88e0ee49f13db8c0'));
 }
Exemplo n.º 8
0
 public function create_message(model\api_message $message)
 {
     $payload = serialize($message);
     $key = $this->key;
     $salt = crypt(microtime() . mt_rand(0, mt_getrandmax()));
     $cipher = new \Crypt_AES(CRYPT_AES_MODE_ECB);
     $cipher->setPassword($key, 'pbkdf2', 'sha256', $salt, 1000);
     $payload_enc = $cipher->encrypt($payload);
     $message = base64_encode(serialize(array('s' => $salt, 'p' => $payload_enc, 't' => @gmmktime())));
     return $message;
 }
 public static function decrypt($secret, $password, ApiKeyEncryptionOptions $options)
 {
     $decodedSecret = self::base64url_decode($secret);
     $salt = self::base64url_decode($options->getEncryptionKeySalt());
     $iterations = $options->getEncryptionKeyIterations();
     $keyLengthBits = $options->getEncryptionKeySize();
     $iv = substr($decodedSecret, 0, 16);
     $aes = new \Crypt_AES();
     $aes->setPassword($password, 'pbkdf2', 'sha1', $salt, $iterations, $keyLengthBits / 8);
     $aes->setKeyLength($keyLengthBits);
     $aes->setIV($iv);
     return $aes->decrypt(substr($decodedSecret, 16));
 }
Exemplo n.º 10
0
/**
 * Checks whether a user has the right to enter on the platform or not
 * @param string The username, as provided in form
 * @param string The cleartext password, as provided in form
 * @param string The WS URL, as provided at the beginning of this script
 */
function loginWSAuthenticate($username, $password, $wsUrl)
{
    // check params
    if (empty($username) or empty($password) or empty($wsUrl)) {
        return false;
    }
    // Create new SOAP client instance
    $client = new SoapClient($wsUrl);
    if (!$client) {
        return false;
    }
    // Include phpseclib methods, because of a bug with AES/CFB in mcrypt
    include_once api_get_path(LIBRARY_PATH) . 'phpseclib/Crypt/AES.php';
    // Define all elements necessary to the encryption
    $key = '-+*%$({[]})$%*+-';
    // Complete password con PKCS7-specific padding
    $blockSize = 16;
    $padding = $blockSize - strlen($password) % $blockSize;
    $password .= str_repeat(chr($padding), $padding);
    $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
    $cipher->setKeyLength(128);
    $cipher->setKey($key);
    $cipher->setIV($key);
    $cipheredPass = $cipher->encrypt($password);
    // Mcrypt call left for documentation purposes - broken, see https://bugs.php.net/bug.php?id=51146
    //$cipheredPass = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $password,  MCRYPT_MODE_CFB, $key);
    // Following lines present for debug purposes only
    /*
    $arr = preg_split('//', $cipheredPass, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($arr as $char) {
        error_log(ord($char));
    }
    */
    // Change to base64 to avoid communication alteration
    $passCrypted = base64_encode($cipheredPass);
    // The call to the webservice will change depending on your definition
    try {
        $response = $client->validateUser(array('user' => $username, 'pass' => $passCrypted, 'system' => 'chamilo'));
    } catch (SoapFault $fault) {
        error_log('Caught something');
        if ($fault->faultstring != 'Could not connect to host') {
            error_log('Not a connection problem');
            throw $fault;
        } else {
            error_log('Could not connect to WS host');
        }
        return 0;
    }
    return $response->validateUserResult;
}
Exemplo n.º 11
0
function fileRead($key)
{
    $file = fopen("data.php", "r");
    $aes = new Crypt_AES();
    $aes->setKey($key);
    $tempdata = "";
    if ($file) {
        $tempdata = file_get_contents("data.php");
        $tempdata = substr($tempdata, strlen($GLOBALS["fileStart"]));
        $tempdata = $aes->decrypt(substr($tempdata, 0, -strlen($GLOBALS["fileEnd"])));
    }
    fclose($file);
    return $tempdata;
}
Exemplo n.º 12
0
 /**
  * Decrypts AES encrypted data
  * @param String $data Data to decrypt
  * @return String
  */
 public function symmetricDecrypt($data)
 {
     if (!$this->isAesInitialized) {
         $this->initSymmetric();
     }
     return $this->aes->decrypt($data);
 }
Exemplo n.º 13
0
 protected function initAes($key, $iv, $keySize)
 {
     $this->aes = new \Crypt_AES();
     $this->aes->setKeyLength($keySize);
     $this->aesKey = $key;
     $this->aesIV = $iv;
     $this->aes->setKey($this->aesKey);
     $this->aes->setIV($this->aesIV);
 }
Exemplo n.º 14
0
 public function pac_message_receiver()
 {
     $content = Req::post("content");
     if (!isset($content)) {
         $this->returnXML("false", "S09", "返回报文为空");
     }
     $signature = Req::post("data_digest");
     if (!isset($signature)) {
         $this->returnXML("false", "S09", "返回报文为空");
     }
     Tiny::log("异步审批结果回执信息【content:" . $content . "】data_digest【" . $signature . "】");
     // 测试密钥
     $aeskey = base64_decode($this->jkf['aes_key']);
     //AES解密,采用ECB模式
     $aes = new Crypt_AES(CRYPT_MODE_ECB);
     //设置AES密钥
     $aes->setKey($aeskey);
     //解密AES密文
     $plaintext = $aes->decrypt(base64_decode($content));
     //测试rsa公钥
     $publickey = $this->jkf['public_key'];
     $rsa = new Crypt_RSA();
     //设置RSA签名模式 CRYPT_RSA_SIGNATURE_PSS or CRYPT_RSA_SIGNATURE_PKCS1
     $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
     //使用RSA公钥验证签名
     $rsa->loadKey(base64_decode($publickey));
     //签名通过
     if ($rsa->verify($plaintext, base64_decode($signature))) {
         $contentXML = simplexml_load_string($plaintext);
         $businessType = (string) $contentXML->head->businessType;
         $model = new GatewayModel();
         if ($businessType == "RESULT") {
             $model->insertResult($contentXML, "1");
         } else {
             if ($businessType == "PRODUCT_RECORD") {
                 $model->insertExamineResult($contentXML);
             }
         }
         $this->returnXML();
     } else {
         $this->returnXML("false", "S02", "非法的数字签名");
     }
 }
Exemplo n.º 15
0
 function attendance()
 {
     require_once 'AES.php';
     $aes = new Crypt_AES();
     $aes->setKey($this->site->conf['AESKey']);
     switch ($_GET['page'] ? $_GET['page'] : 00) {
         case 00:
             if ($this->site->userPermit == '3') {
                 $auth = base64_encode($aes->encrypt($_COOKIE['email'] . '	' . $_COOKIE['pass']));
                 setcookie('email', $_POST['email'], 0, '/');
                 setcookie('pass', md5($_POST['password']), 0, '/');
                 $team = $this->mysql->get_rows('SELECT * FROM `team` WHERE `active` = YEAR(CURDATE()) ORDER BY `name` ASC ');
                 foreach ($team as $key => $i) {
                     $list[] = array('<% ID %>' => $i['id'], '<% NAME %>' => $i['name']);
                 }
                 $ret = $this->templates->process_between('attendance.html', '<% STUDENTS %>', $list);
                 $ret = $this->templates->process($ret, array('<% AUTH %>' => $auth));
                 echo $this->templates->template('Team Attendance', array(), $ret);
             } else {
                 $this->site->home_page();
             }
             break;
         case 01:
             list($email, $pass) = explode('	', $aes->decrypt(base64_decode($_POST['auth'])));
             if ($this->site->checkCredentials($email, $pass) && $this->site->userPermit == '3') {
                 die("1");
             } else {
                 die("0");
             }
             break;
         case 02:
             $pass = $this->mysql->get_row('SELECT `password` FROM `team` WHERE `id` = ' . $_POST['id'] . ' LIMIT 1');
             if ($pass['password'] == md5($_POST['pass'])) {
                 $this->mysql->query("INSERT INTO `attendence` (`id`, `date`, `teamid`) VALUES (NULL, CURDATE(), '" . $_POST['id'] . "')");
                 die("1");
             }
             break;
     }
 }
 /**
  * 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.º 17
0
 public function decrypt_data($input_str, $key = SEC_STR)
 {
     $aes = new Crypt_AES();
     $aes->setKey($key);
     return $aes->decrypt($input_str);
 }
Exemplo n.º 18
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 .= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
                 $ciphertext = preg_replace('#.+(\\r|\\n|\\r\\n)\\1|[\\r\\n]|-.+-| #s', '', $key);
                 $ciphertext = preg_match('#^[a-zA-Z\\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
                 if ($ciphertext === false) {
                     $ciphertext = $key;
                 }
                 switch ($matches[1]) {
                     case 'AES-128-CBC':
                         if (!class_exists('Crypt_AES')) {
                             require_once 'Crypt/AES.php';
                         }
                         $symkey = substr($symkey, 0, 16);
                         $crypto = new Crypt_AES();
                         break;
                     case 'DES-EDE3-CFB':
                         if (!class_exists('Crypt_TripleDES')) {
                             require_once 'Crypt/TripleDES.php';
                         }
                         $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
                         break;
                     case 'DES-EDE3-CBC':
                         if (!class_exists('Crypt_TripleDES')) {
                             require_once 'Crypt/TripleDES.php';
                         }
                         $crypto = new Crypt_TripleDES();
                         break;
                     case 'DES-CBC':
                         if (!class_exists('Crypt_DES')) {
                             require_once 'Crypt/DES.php';
                         }
                         $crypto = new Crypt_DES();
                         break;
                     default:
                         return false;
                 }
                 $crypto->setKey($symkey);
                 $crypto->setIV($iv);
                 $decoded = $crypto->decrypt($ciphertext);
             } else {
                 $decoded = preg_replace('#-.+-|[\\r\\n]| #', '', $key);
                 $decoded = preg_match('#^[a-zA-Z\\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
             }
             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 Math_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 Math_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 Math_BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
             $this->_string_shift($key);
             $length = $this->_decodeLength($key);
             $components['coefficients'] = array(2 => new Math_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 Math_BigInteger($this->_string_shift($key, $length), 256);
                     $this->_string_shift($key);
                     $length = $this->_decodeLength($key);
                     $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
                     $this->_string_shift($key);
                     $length = $this->_decodeLength($key);
                     $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
                 }
             }
             return $components;
         case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
             $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
             if ($key === false) {
                 return false;
             }
             $cleanup = substr($key, 0, 11) == "ssh-rsa";
             if (strlen($key) <= 4) {
                 return false;
             }
             extract(unpack('Nlength', $this->_string_shift($key, 4)));
             $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
             if (strlen($key) <= 4) {
                 return false;
             }
             extract(unpack('Nlength', $this->_string_shift($key, 4)));
             $modulus = new Math_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 Math_BigInteger($this->_string_shift($key, $length), -256);
                 return strlen($key) ? false : array('modulus' => $realModulus, 'publicExponent' => $modulus);
             } else {
                 return strlen($key) ? false : array('modulus' => $modulus, 'publicExponent' => $publicExponent);
             }
             // 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');
             if (!xml_parse($xml, $key)) {
                 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]));
             $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 Math_BigInteger($this->_string_shift($public, $length), -256);
             extract(unpack('Nlength', $this->_string_shift($public, 4)));
             $components['modulus'] = new Math_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':
                     if (!class_exists('Crypt_AES')) {
                         require_once 'Crypt/AES.php';
                     }
                     $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 Crypt_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 Math_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 Math_BigInteger($this->_string_shift($private, $length), -256));
             extract(unpack('Nlength', $this->_string_shift($private, 4)));
             if (strlen($private) < $length) {
                 return false;
             }
             $components['primes'][] = new Math_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 Math_BigInteger($this->_string_shift($private, $length), -256));
             return $components;
     }
 }
Exemplo n.º 19
0
    exit('Error: BoxID error.');
}
###
$return = 'boxgamefile.php?id=' . urlencode($boxid);
require "../configuration.php";
require "./include.php";
require_once "../includes/func.ssh2.inc.php";
require_once "../libs/phpseclib/Crypt/AES.php";
require_once "../libs/gameinstaller/gameinstaller.php";
$title = T_('Box Game File Repositories');
if (query_numrows("SELECT `name` FROM `" . DBPREFIX . "box` WHERE `boxid` = '" . $boxid . "'") == 0) {
    exit('Error: BoxID is invalid.');
}
$rows = query_fetch_assoc("SELECT * FROM `" . DBPREFIX . "box` WHERE `boxid` = '" . $boxid . "' LIMIT 1");
$games = mysql_query("SELECT * FROM `" . DBPREFIX . "game` ORDER BY `game`");
$aes = new Crypt_AES();
$aes->setKeyLength(256);
$aes->setKey(CRYPT_KEY);
// Get SSH2 Object OR ERROR String
$ssh = newNetSSH2($rows['ip'], $rows['sshport'], $rows['login'], $aes->decrypt($rows['password']));
if (!is_object($ssh)) {
    $_SESSION['msg1'] = T_('Connection Error!');
    $_SESSION['msg2'] = $ssh;
    $_SESSION['msg-type'] = 'error';
}
$gameInstaller = new GameInstaller($ssh);
include "./bootstrap/header.php";
/**
 * Notifications
 */
include "./bootstrap/notifications.php";
 function getPassword($pwd = null, $iv_field = "iv")
 {
     if (is_null($pwd)) {
         $pwd = $this->password;
         if (!$this->password) {
             return "";
         }
     }
     try {
         $master_key_filepath = CAppUI::conf("master_key_filepath");
         $master_key_filepath = rtrim($master_key_filepath, "/");
         if (CExchangeSource::checkMasterKeyFile($master_key_filepath)) {
             CAppUI::requireLibraryFile("phpseclib/phpseclib/Crypt/AES");
             CAppUI::requireLibraryFile("phpseclib/phpseclib/Crypt/Random");
             $cipher = new Crypt_AES(CRYPT_AES_MODE_CTR);
             $cipher->setKeyLength(256);
             $keyAB = file($master_key_filepath . "/.mediboard.key");
             if (count($keyAB) == 2) {
                 $cipher->setKey($keyAB[0] . $keyAB[1]);
                 $ivToUse = $this->{$iv_field};
                 if (!$ivToUse) {
                     $clear = $pwd;
                     $this->store();
                     return $clear;
                 }
                 $cipher->setIV($ivToUse);
                 $decrypted = rtrim(base64_decode($pwd), "");
                 $decrypted = $cipher->decrypt($decrypted);
                 if ($decrypted) {
                     return $decrypted;
                 }
             }
         }
     } catch (Exception $e) {
         return $pwd;
     }
     return $pwd;
 }
Exemplo n.º 21
0
require_once ABSPATH . 'db_config.php';
require_once ABSPATH . 'includes/autoload.php';
require_once ABSPATH . 'includes/errors.php';
$db = new MySQLidb(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT);
$encrypted_data = $_REQUEST['data'];
//debug_print("encrypted_data={$encrypted_data}", __FILE__, __LINE__,  __FUNCTION__,  __CLASS__, __METHOD__);
$binary_tx_hashes = decrypt_data($encrypted_data, $db, $decrypted_key);
if (substr($binary_tx_hashes, 0, 7) == '[error]') {
    die($binary_tx_hashes);
}
//debug_print("binary_tx_hashes={$binary_tx_hashes}", __FILE__, __LINE__,  __FUNCTION__,  __CLASS__, __METHOD__);
$binary_tx = '';
// Разбираем список транзакций
do {
    list(, $tx_hash) = unpack("H*", string_shift($binary_tx_hashes, 16));
    if (!$tx_hash) {
        continue;
    }
    $tx = $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\tSELECT `data`\n\t\t\tFROM `" . DB_PREFIX . "transactions`\n\t\t\tWHERE `hash` = 0x{$tx_hash}\n\t\t\t", 'fetch_one');
    if ($tx) {
        $binary_tx .= ParseData::encode_length_plus_data($tx);
    }
} while ($binary_tx_hashes);
// шифруем тр-ии
$aes = new Crypt_AES();
$aes->setKey($decrypted_key);
$encrypted_data = $aes->encrypt($binary_tx);
unset($aes);
//debug_print("decrypted_key={$decrypted_key}", __FILE__, __LINE__,  __FUNCTION__,  __CLASS__, __METHOD__);
//debug_print("encrypted_data={$encrypted_data}", __FILE__, __LINE__,  __FUNCTION__,  __CLASS__, __METHOD__);
print $encrypted_data;
Exemplo n.º 22
0
/**
 * Initialize LaunchKey WordPress Plugin
 *
 * This function will perform the entire initializaiton for the plugin.  The initialization is encapsulated into
 * a funciton to protect against global variable collision.
 *
 * @since 1.0.0
 * Enclose plug-in initialization to protect against global variable corruption
 */
function launchkey_plugin_init()
{
    /**
     * Language domain for the plugin
     */
    $language_domain = 'launchkey';
    /**
     * Register plugin text domain with language files
     *
     * @see load_plugin_textdomain
     * @link https://developer.wordpress.org/reference/hooks/plugins_loaded/
     */
    add_action('plugins_loaded', function () use($language_domain) {
        load_plugin_textdomain($language_domain, false, plugin_basename(__FILE__) . '/languages/');
    });
    /**
     * Get the WP global facade
     * @see LaunchKey_WP_Global_Facade
     */
    $facade = new LaunchKey_WP_Global_Facade();
    /**
     * Create an AES encryption class for encryption/decryption of the secret options
     * @link https://docs.launchkey.com/glossary.html#term-aes
     */
    $crypt_aes = new Crypt_AES();
    /**
     * Use an MD5 hash of the auth key as the crypto key.  The crypto key is used as it would normally affect all auth
     * procedures as it is used as a salt for passwords.  An md5 hash is used as it will be a constant value based on
     * the AUTH_KEY but guaranteed to be exactly thirty-two (32) characters as is needed by AES encryption.
     */
    $crypt_aes->setKey(md5(AUTH_KEY));
    // Create an options handler that will encrypt and decrypt the plugin options as necessary
    $options_handler = new LaunchKey_WP_Options($crypt_aes);
    /**
     * The pre_update_option_launchkey filter will process the "launchkey" option directly
     * before updating the data in the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/
     * @see LaunchKey_WP_Options::pre_update_option_filter
     */
    add_filter('pre_update_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    /**
     * The pre_update_option_filter filter will process the "launchkey" option directly
     * before adding the data in the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/
     * @see LaunchKey_WP_Options::pre_update_option_filter
     */
    add_filter('pre_add_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    /**
     * The option_launchkey filter will process the "launchkey" option directly
     * after retrieving the data from the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/option_option/
     * @see LaunchKey_WP_Options::post_get_option_filter
     */
    add_filter('option_launchkey', array($options_handler, 'post_get_option_filter'));
    /**
     * If the pre-1.0.0 option style was already used, create a 1.0.0 option and remove the old options.  They are
     * removed as the secret_key was stored plain text in the database.
     *
     * @since 1.0.0
     */
    if (get_option('launchkey_app_key') || get_option('launchkey_secret_key')) {
        $launchkey_options[LaunchKey_WP_Options::OPTION_ROCKET_KEY] = get_option('launchkey_app_key');
        $launchkey_options[LaunchKey_WP_Options::OPTION_SECRET_KEY] = get_option('launchkey_secret_key');
        $launchkey_options[LaunchKey_WP_Options::OPTION_SSL_VERIFY] = defined('LAUNCHKEY_SSLVERIFY') && LAUNCHKEY_SSLVERIFY || true;
        $launchkey_options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] = LaunchKey_WP_Implementation_Type::OAUTH;
        $launchkey_options[LaunchKey_WP_Options::OPTION_LEGACY_OAUTH] = true;
        if (update_option(LaunchKey_WP_Admin::OPTION_KEY, $launchkey_options)) {
            delete_option('launchkey_app_key');
            delete_option('launchkey_secret_key');
        } else {
            throw new RuntimeException('Unable to upgrade LaunchKey meta-data.  Failed to save setting ' . LaunchKey_WP_Admin::OPTION_KEY);
        }
    } elseif (!get_option(LaunchKey_WP_Admin::OPTION_KEY)) {
        add_option(LaunchKey_WP_Admin::OPTION_KEY, array());
    }
    /**
     * Create a templating object and point it at the correct directory for template files.
     *
     * @see LaunchKey_WP_Template
     */
    $template = new LaunchKey_WP_Template(__DIR__ . '/templates', $facade, $language_domain);
    // Prevent XXE Processing Vulnerability
    libxml_disable_entity_loader(true);
    // Get the plugin options to determine which authentication implementation should be utilized
    $options = get_option(LaunchKey_WP_Admin::OPTION_KEY);
    $logger = new LaunchKey_WP_Logger($facade);
    $launchkey_client = null;
    $client = null;
    // Only register the pieces that need to interact with LaunchKey if it's been configured
    if (LaunchKey_WP_Implementation_Type::SSO === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID])) {
        $container = new LaunchKey_WP_SAML2_Container($logger);
        SAML2_Compat_ContainerSingleton::setContainer($container);
        $securityKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public'));
        $securityKey->loadKey($options[LaunchKey_WP_Options::OPTION_SSO_CERTIFICATE], false, true);
        $client = new LaunchKey_WP_SSO_Client($facade, $template, $options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID], $securityKey, $options[LaunchKey_WP_Options::OPTION_SSO_LOGIN_URL], $options[LaunchKey_WP_Options::OPTION_SSO_LOGOUT_URL], $options[LaunchKey_WP_Options::OPTION_SSO_ERROR_URL]);
    } elseif (LaunchKey_WP_Implementation_Type::OAUTH === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) {
        /**
         * If the implementation type is OAuth, use the OAuth client
         * @see LaunchKey_WP_OAuth_Client
         */
        $client = new LaunchKey_WP_OAuth_Client($facade, $template);
    } elseif (!empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) {
        $launchkey_client = \LaunchKey\SDK\Client::wpFactory($options[LaunchKey_WP_Options::OPTION_ROCKET_KEY], $options[LaunchKey_WP_Options::OPTION_SECRET_KEY], $options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY], $options[LaunchKey_WP_Options::OPTION_SSL_VERIFY]);
        $client = new LaunchKey_WP_Native_Client($launchkey_client, $facade, $template, $language_domain);
        add_filter('init', function () use($facade) {
            wp_enqueue_script('launchkey-script', plugins_url('/public/launchkey-login.js', __FILE__), array('jquery'), '1.0.0', true);
        });
    }
    if ($client) {
        /**
         * Register the non-admin actions for authentication client.  These actions will handle all of the
         * authentication work for the plugin.
         *
         * @see LaunchKey_WP_Client::register_actions
         * @see LaunchKey_WP_OAuth_Client::register_actions
         * @see LaunchKey_WP_Native_Client::register_actions
         */
        $client->register_actions();
        /**
         * Create the a user profile object and register its actions.  These actions will handle all functionality
         * related to a user customizing their authentication related options.
         *
         * @see LaunchKey_WP_User_Profile
         */
        $profile = new LaunchKey_WP_User_Profile($facade, $template, $language_domain, $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE]);
        $profile->register_actions();
        /**
         * Hideous workaround for the wp-login.php page not printing styles in the header like it should.
         *
         * @since 1.0.0
         */
        if (!has_action('login_enqueue_scripts', 'wp_print_styles')) {
            add_action('login_enqueue_scripts', 'wp_print_styles', 11);
        }
    }
    if (is_admin()) {
        /**
         * If we are in the admin, create am admin object and register its actions.  These actions
         * will manage setting of options and user management for the plugin.
         *
         * @see is_admin
         * @see LaunchKey_WP_Admin
         */
        $launchkey_admin = new LaunchKey_WP_Admin($facade, $template, $language_domain);
        $launchkey_admin->register_actions();
        $config_wizard = new LaunchKey_WP_Configuration_Wizard($facade, $launchkey_admin, $launchkey_client);
        $config_wizard->register_actions();
    }
    /**
     * Add a filter to enqueue styles for the plugin
     *
     * @since 1.0.0
     *
     * @see add_filter
     * @see wp_enqueue_style
     * @link https://developer.wordpress.org/reference/functions/add_filter/
     * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
     */
    add_filter('init', function () use($facade) {
        wp_enqueue_style('launchkey-style', plugins_url('/public/launchkey.css', __FILE__), array(), '1.0.0', false);
    });
}
Exemplo n.º 23
0
 /**
  * Decrypt Session Credentials
  *
  * @param none
  * @return array
  * @access private
  */
 private function decryptSessionCredentials()
 {
     if (!empty($this->session) && array_key_exists('CREDENTIALS', $this->session)) {
         switch (CONF_SEC_SESSION_METHOD) {
             case 'aes256':
             default:
                 $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB);
                 $cipher->setKeyLength(256);
                 $cipher->setKey($this->session_key);
                 $credentials = unserialize($cipher->decrypt($this->session['CREDENTIALS']));
                 break;
         }
         return $credentials;
     }
     return array();
 }
Exemplo n.º 24
0
/**
 * Decrypt the given AES ciphertext
 *
 * The mode is CBC, the key is derived using pbkdf2
 *
 * @param string $ciphertext The encrypted data
 * @param string $secret     The secret/password that shall be used
 * @return string The decrypted data
 */
function auth_decrypt($ciphertext, $secret)
{
    $iv = substr($ciphertext, 0, 16);
    $cipher = new Crypt_AES();
    $cipher->setPassword($secret);
    $cipher->setIV($iv);
    return $cipher->decrypt(substr($ciphertext, 16));
}
Exemplo n.º 25
0
 static function ExtractDataPacket($data, $key, $options = array())
 {
     $data = (string) $data;
     if (!isset($options["mode"])) {
         $options["mode"] = "ECB";
     }
     if ($options["mode"] != "ECB" && (!isset($options["iv"]) || $options["iv"] == "")) {
         return false;
     }
     if (isset($options["key2"])) {
         $options2 = $options;
         if (isset($options["iv2"])) {
             $options["iv"] = $options["iv2"];
         } else {
             unset($options["iv"]);
         }
         if (self::IsMcryptAvailable()) {
             $data = self::McryptDecrypt($data, $options["key2"], $options);
         } else {
             if (class_exists("Crypt_AES")) {
                 $aes = new Crypt_AES($options["mode"] == "CBC" ? CRYPT_AES_MODE_CBC : CRYPT_AES_MODE_ECB);
                 $aes->setKey($options["key2"]);
                 if (isset($options["iv"])) {
                     $aes->setIV($options["iv"]);
                 }
                 $aes->disablePadding();
                 $data = $aes->decrypt($data);
             } else {
                 return false;
             }
         }
         $data = substr($data, 1) . substr($data, 0, 1);
         $options = $options2;
     }
     if (self::IsMcryptAvailable()) {
         $data = self::McryptDecrypt($data, $key, $options);
     } else {
         if (class_exists("Crypt_AES")) {
             $aes = new Crypt_AES($options["mode"] == "CBC" ? CRYPT_AES_MODE_CBC : CRYPT_AES_MODE_ECB);
             $aes->setKey($key);
             if (isset($options["iv"])) {
                 $aes->setIV($options["iv"]);
             }
             $aes->disablePadding();
             $data = $aes->decrypt($data);
         } else {
             return false;
         }
     }
     if ($data === false) {
         return false;
     }
     $pos = strpos($data, "\n");
     if ($pos === false) {
         return false;
     }
     $data = substr($data, $pos + 1);
     $pos = strpos($data, "\n");
     if ($pos === false) {
         return false;
     }
     $check = substr($data, 0, $pos);
     $data = substr($data, $pos + 1);
     $pos = strrpos($data, "\n");
     if ($pos === false) {
         return false;
     }
     $data = substr($data, 0, $pos);
     if (!isset($options["lightweight"]) || !$options["lightweight"]) {
         if ($check !== strtolower(sha1($data))) {
             return false;
         }
     } else {
         if ($check !== strtolower(dechex(crc32($data)))) {
             return false;
         }
     }
     return $data;
 }
Exemplo n.º 26
0
 */
 //---------------------------------------------------------+
 //---------------------------------------------------------+
 //Updating passphrase file if this one is the default one
 $line = file_get_contents("../.ssh/passphrase");
 if (preg_match('#isEmpty = TRUE;#', $line)) {
     $oldPassphrase = 'isEmpty = TRUE;';
     $newPassphrase = hash('sha512', md5(str_shuffle(time())));
     if (is_writable("../.ssh/passphrase")) {
         $handle = fopen('../.ssh/passphrase', 'w');
         fwrite($handle, $newPassphrase);
         fclose($handle);
     }
     //---------------------------------------------------------+
     require_once "../libs/phpseclib/Crypt/AES.php";
     $aes = new Crypt_AES();
     $aes->setKeyLength(256);
     //---------------------------------------------------------+
     $boxes = mysql_query("SELECT `boxid`, `password` FROM `" . DBPREFIX . "box`");
     while ($rowsBoxes = mysql_fetch_assoc($boxes)) {
         $aes->setKey($oldPassphrase);
         $password = $aes->decrypt($rowsBoxes['password']);
         $aes->setKey($newPassphrase);
         $password = $aes->encrypt($password);
         query_basic("UPDATE `" . DBPREFIX . "box` SET `password` = '" . mysql_real_escape_string($password) . "' WHERE `boxid` = '" . $rowsBoxes['boxid'] . "'");
         unset($password);
     }
     unset($boxes);
 }
 unset($line);
 //---------------------------------------------------------+
Exemplo n.º 27
0
debug_print('$encrypted_data=' . bin2hex($encrypted_data), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
$url = "{$host}/get_tx.php";
debug_print($url, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
// загружаем сами тр-ии
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'data=' . urlencode($encrypted_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$encrypted_tx_set = curl_exec($ch);
curl_close($ch);
debug_print('$encrypted_tx_set=' . $encrypted_tx_set, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
debug_print('$my_key=' . $my_key, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
$aes = new Crypt_AES();
$aes->setKey($my_key);
// теперь в $binary_tx будут обычные тр-ии
$binary_tx = $aes->decrypt($encrypted_tx_set);
unset($aes);
debug_print('$binary_tx=' . $binary_tx, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
// разберем полученные тр-ии
do {
    $tx_size = ParseData::decode_length($binary_tx);
    $tx_binary_data = ParseData::string_shift($binary_tx, $tx_size);
    debug_print('$tx_binary_data=' . $tx_binary_data, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
    list(, $tx_hex) = unpack("H*", $tx_binary_data);
    if (!$tx_binary_data) {
        continue;
    }
    // проверим размер
Exemplo n.º 28
0
 /**
  * Returns the encryption cipher
  */
 private static function getCipher()
 {
     if (!class_exists('Crypt_AES', false)) {
         include 'Crypt/AES.php';
     }
     $cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
     $cipher->setKey(\OCP\Config::getSystemValue('passwordsalt'));
     return $cipher;
 }
Exemplo n.º 29
0
<?php

$rootPath = realpath(__DIR__ . '/../');
set_include_path(get_include_path() . PATH_SEPARATOR . $rootPath . '/source/php/libs/phpseclib/');
include 'Crypt/AES.php';
$plaintext = 'This is the plain text to encrypt';
$aes = new Crypt_AES();
$aes->setKey('abcdefghijklmnop');
$ciphertext = $aes->encrypt($plaintext);
echo $aes->decrypt($ciphertext);
 /**
  * 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 (strlen($this->_cookie_iv) < $this->getIVSize()) {
         $this->createIV();
     }
     if ($this->_useOpenSSL()) {
         return openssl_decrypt($encdata, 'AES-128-CBC', $secret, 0, $this->_cookie_iv);
     } else {
         $cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
         $cipher->setIV($this->_cookie_iv);
         $cipher->setKey($secret);
         return $cipher->decrypt(base64_decode($encdata));
     }
 }