Exemple #1
1
print "AES-192 otv decrypted is ok: " . bool_str(Base16::encode($aes192tvd) == "00112233445566778899aabbccddeeff") . "<br/>\n";
print "AES-192 (CBC mode) encrypted in UTF-8: " . Base16::encode($aes192e) . "<br/>\n";
print "AES-192 (CBC mode) decrypted in UTF-8: " . $aes192d . "<br/><br/>\n";
/**
* Test AES-256 with one official test vector and custom input.
* Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf
*/
$aes256tvk = pack("c*", 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f);
$aes256tvt = pack("c*", 0x0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff);
$aes256tve = AES::encrypt($aes256tvk, $aes256tvt);
// ECB mode, no padding needed.
$aes256tvd = AES::decrypt($aes256tvk, $aes256tve);
// ECB mode, no padding needed.
//
$aes256i = "1234567890123456";
$aes256k = "12345678901234561234567890123456";
$aes256e = AES::encrypt($aes256k, PKCS7::pad($input, 16), "ctr", $aes256i);
// Needs padding.
$aes256d = PKCS7::unpad(AES::decrypt($aes256k, $aes256e, "ctr", $aes256i));
// Needs unpadding.
//
print "AES-256 otv encrypted is ok: " . bool_str(Base16::encode($aes256tve) == "8ea2b7ca516745bfeafc49904b496089") . "<br/>\n";
print "AES-256 otv decrypted is ok: " . bool_str(Base16::encode($aes256tvd) == "00112233445566778899aabbccddeeff") . "<br/>\n";
print "AES-256 (CTR mode) encrypted in UTF-8: " . Base16::encode($aes256e) . "<br/>\n";
print "AES-256 (CTR mode) decrypted in UTF-8: " . $aes256d . "<br/><br/>\n";
?>

</div>
</body>
</html>
function decryptText($input)
{
    global $IV, $key;
    $aes = new AES($input, $key, 256);
    $aes->setIV(base64_decode($IV));
    $aes->setMode(AES::M_CBC);
    return $aes->decrypt();
}
 /**
  * 撤销二维码
  *
  */
 public function cancel($info)
 {
     require_once str_replace("\\", '/', dirname(__FILE__)) . '/AES.class.php';
     $xml = "<?xml version='1.0' encoding='utf-8'?>\n            <business_trans>\n            \t<request_type>cancel_order</request_type>\n            \t<req_seq>" . $info['req_seq'] . "</req_seq>\n            \t<order>\n            \t\t<cancel_num>1</cancel_num>\n            \t</order>\n            </business_trans>";
     //xml的aes加密
     $aes = new AES($this->secret_key);
     $xml_aes = $aes->encrypt($xml);
     $xml_aes_str = base64_encode($xml_aes);
     //组织参数
     $paramters = array('organization' => $this->organization, 'xml' => $xml_aes_str);
     $result = $this->simulation_post($this->send_url, $paramters);
     $xml_result = $aes->decrypt(base64_decode($result));
     return $xml_result;
 }
Exemple #4
0
function decoder($x)
{
    $Cipher = new AES();
    $key_256bit = $keypass;
    $n = ceil(strlen($x) / 32);
    $decrypt = "";
    for ($i = 0; $i <= $n - 1; $i++) {
        $result = $Cipher->decrypt(substr($x, $i * 32, 32), $key_256bit);
        $decrypt .= $Cipher->hexToString($result);
    }
    $value = new hash_encryption($keypass1);
    $decrypted = $value->decrypt($decrypt);
    return $decrypted;
}
Exemple #5
0
function paramDecrypt($x)
{
    $Cipher = new AES();
    // kunci dekripsi (kunci ini harus sama dengan kunci enkripsi)
    $key_128bit = '2b7e151628aed2a6abf7158809cf4f3c';
    // karena string hasil enkripsi memiliki panjang 32 karakter, maka untuk proses dekripsi ini panjang string dipotong2 dulu menjadi 32 karakter
    $n = ceil(strlen($x) / 32);
    $decrypt = "";
    for ($i = 0; $i <= $n - 1; $i++) {
        // mendekrip setiap 32 karakter hasil enkripsi
        $result = $Cipher->decrypt(substr($x, $i * 32, 32), $key_128bit);
        // menggabung hasil dekripsi 32 karakter menjadi satu string dekripsi utuh
        $decrypt .= $Cipher->hexToString($result);
    }
    return $decrypt;
}
function decrypt($input, $key)
{
    // Split the input into its parts
    $cipherSplit = explode(" ", $input);
    $originalSize = intval($cipherSplit[0]);
    $iv = cryptoHelpers::toNumbers($cipherSplit[1]);
    $cipherText = $cipherSplit[2];
    // Set up encryption parameters
    $cipherIn = cryptoHelpers::toNumbers($cipherText);
    $keyAsNumbers = cryptoHelpers::toNumbers(bin2hex($key));
    $keyLength = count($keyAsNumbers);
    $decrypted = AES::decrypt($cipherIn, $originalSize, AES::modeOfOperation_CBC, $keyAsNumbers, $keyLength, $iv);
    // Byte-array to text.
    $hexDecrypted = cryptoHelpers::toHex($decrypted);
    $retVal = pack("H*", $hexDecrypted);
    return $retVal;
}
function wplc_decrypt_msg($input)
{
    $messages = maybe_unserialize($input);
    if (is_array($messages)) {
        if ($messages['e'] == 1) {
            /* This message was encrypted */
            $api_key = get_option('wplc_api_key');
            $api_key = substr($api_key, 0, 10);
            $cipherSplit = explode(" ", $messages['m']);
            $originalSize = intval($cipherSplit[0]);
            $iv = cryptoHelpers::toNumbers($cipherSplit[1]);
            $cipherText = $cipherSplit[2];
            $cipherIn = cryptoHelpers::toNumbers($cipherText);
            $keyAsNumbers = cryptoHelpers::toNumbers(bin2hex($api_key));
            $keyLength = count($keyAsNumbers);
            $decrypted = AES::decrypt($cipherIn, $originalSize, AES::modeOfOperation_CBC, $keyAsNumbers, $keyLength, $iv);
            $hexDecrypted = cryptoHelpers::toHex($decrypted);
            $retVal = pack("H*", $hexDecrypted);
            return stripslashes($retVal);
        } else {
            return stripslashes($messages['m']);
        }
    } else {
        return stripslashes($input);
    }
}
function paramDecrypt($x)
{
    $Cipher = new AES();
    $key_256bit = keypass();
    $n = ceil(strlen($x) / 32);
    $decrypt = "";
    for ($i = 0; $i <= $n - 1; $i++) {
        $result = $Cipher->decrypt(substr($x, $i * 32, 32), $key_256bit);
        $decrypt .= $Cipher->hexToString($result);
    }
    return $decrypt;
}
Exemple #9
0
<?php

include "./AES.class.php";
$z = "abcdefgh01234567";
// 128-bit key
//$z = "abcdefghijkl012345678901"; // 192-bit key
//$z = "abcdefghijuklmno0123456789012345"; // 256-bit key
$aes = new AES($z);
$data = file_get_contents("./example.txt");
$start = microtime(true);
//echo "\n\nCipher-Text:\n" . $aes->encrypt($data) . "\n";
echo "\n\nPlain-Text:\n" . $aes->decrypt($aes->encrypt($data)) . "\n";
$end = microtime(true);
echo "\n\nExecution time: " . ($end - $start);
<?php

require_once dirname(dirname(__FILE__)) . '/app.php';
$zhongyu_config = (include str_ireplace('\\', '/', dirname(__FILE__)) . '/config.php');
include str_ireplace('\\', '/', dirname(__FILE__)) . '/ZhongyuModel.class.php';
include str_ireplace('\\', '/', dirname(__FILE__)) . '/AES.class.php';
$aes = new AES($zhongyu_config['secret_key']);
//初始化aes加密
$zhongyuModel = new ZhongyuModel();
if (isset($_POST['is_encrypt']) && $_POST['is_encrypt'] == 1) {
    //xml数据位加密后
    $xml_array = xml_to_array($aes->decrypt(base64_decode(trim($_POST['xml']))));
} else {
    $xml_array = xml_to_array(trim($_POST['xml']));
}
//print_r($xml_array);exit;
$request_type = $xml_array['request_type'][0];
/* 同步项目 */
if ('sync_team' == $request_type) {
    $data = $xml_array['data'];
    die($zhongyuModel->sync_team($data));
} elseif ('edit_product_end_time' == $request_type) {
    $product_num = $xml_array['product_num'][0];
    //中娱平台产品ID
    $end_time = strtotime($xml_array['end_time'][0]);
    //接收到的项目结束时间(转化为unix时间戳)
    die($zhongyuModel->edit_product_end_time($product_num, $end_time));
}
function xml_to_array($xml)
{
    $array = (array) simplexml_load_string($xml, null, LIBXML_NOCDATA);
	public static function checkTANValidity_old_old ($emailId, $tanNo) {
		
		$imputText = $tanNo;
		$imputKey = $emailId;
		$blockSize = 256;

		$aes = new AES($imputText, $imputKey, $blockSize);

		$dec = $aes->decrypt();

		if (is_numeric($dec)) {
			if ($subs != self::num ($emailId))
				if (self::is_prime(bcsub ($dec, self::num ($emailId)))) {
					return true;
				}
		}
		else
			return false;
	}
Exemple #12
0
function admin_user()
{
    $username_md5 = md5('username');
    $username_cookie = $_COOKIE[$username_md5];
    $aes = new AES("abcdefgh12345678");
    $username = $aes->decrypt($username_cookie);
    echo $username;
}
Exemple #13
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 != self::PUBLIC_FORMAT_RAW && !is_string($key)) {
         return false;
     }
     switch ($type) {
         case self::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 self::PRIVATE_FORMAT_PKCS1:
         case self::PRIVATE_FORMAT_PKCS8:
         case self::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(Base::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)) != self::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
                ie. PKCS8 keys*/
             if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "0") {
                 $this->_string_shift($key, 3);
                 $tag = self::ASN1_SEQUENCE;
             }
             if ($tag == self::ASN1_SEQUENCE) {
                 $temp = $this->_string_shift($key, $this->_decodeLength($key));
                 if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) {
                     return false;
                 }
                 $length = $this->_decodeLength($temp);
                 switch ($this->_string_shift($temp, $length)) {
                     case "*†H†÷\r":
                         // rsaEncryption
                         break;
                     case "*†H†÷\r":
                         // pbeWithMD5AndDES-CBC
                         /*
                            PBEParameter ::= SEQUENCE {
                                salt OCTET STRING (SIZE(8)),
                                iterationCount INTEGER }
                         */
                         if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) {
                             return false;
                         }
                         if ($this->_decodeLength($temp) != strlen($temp)) {
                             return false;
                         }
                         $this->_string_shift($temp);
                         // assume it's an octet string
                         $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
                         if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) {
                             return false;
                         }
                         $this->_decodeLength($temp);
                         list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
                         $this->_string_shift($key);
                         // assume it's an octet string
                         $length = $this->_decodeLength($key);
                         if (strlen($key) != $length) {
                             return false;
                         }
                         $crypto = new DES();
                         $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
                         $key = $crypto->decrypt($key);
                         if ($key === false) {
                             return false;
                         }
                         return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1);
                     default:
                         return false;
                 }
                 /* 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 */
                 $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 == self::ASN1_BITSTRING) {
                     $this->_string_shift($key);
                 }
                 if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
                     return false;
                 }
                 if ($this->_decodeLength($key) != strlen($key)) {
                     return false;
                 }
                 $tag = ord($this->_string_shift($key));
             }
             if ($tag != self::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 self::ASN1_INTEGER
                 $length = $this->_decodeLength($key);
                 $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
                 return $components;
             }
             if (ord($this->_string_shift($key)) != self::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)) != self::ASN1_SEQUENCE) {
                     return false;
                 }
                 $this->_decodeLength($key);
                 while (!empty($key)) {
                     if (ord($this->_string_shift($key)) != self::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 self::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 self::PRIVATE_FORMAT_XML:
         case self::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 self::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;
     }
 }
Exemple #14
0
<?php

/**
 * Created by PhpStorm.
 * User: knowthis
 * Date: 15/11/13
 * Time: 下午9:59
 */
header("Content-Type: text/html; charset=UTF-8");
include "config/config.php";
include "class/AES.class.php";
// 获取用户名
$token_string = $_COOKIE['token'];
$username_md5 = md5('username');
$username_string = $_COOKIE[$username_md5];
$aes = new AES("abcdefgh12345678");
$username = $aes->decrypt($username_string);
if (strlen($token_string) == 32) {
    $now = date("Y-m-d");
    $sql = "select blog_token.id from blog_admin,blog_token\n            where bt_user = blog_admin.id\n            and  ba_username = '******'\n            and bt_token='{$token_string}'\n            and bt_start <= '{$now}'\n            and bt_end >= '{$now}' ";
    $re = mysqli_query($conn, $sql);
    $num = mysqli_num_rows($re);
    if ($num) {
        echo 1;
    } else {
        echo 0;
    }
}
<?php

require_once "AES.php";
header("Content-type: application/json");
$result = array("status" => "auth-failure", "num1" => "", "num2" => "");
$cookiePasswd = "CookiePassword";
$serverKey = "SecretKey";
$adminUserList = array("*****@*****.**", "*****@*****.**");
if (array_key_exists("redbox_auth", $_COOKIE)) {
    $userdata = json_decode(AES::decrypt($_COOKIE["redbox_auth"], $cookiePasswd));
    $userEmail = $userdata->email;
    $userFirstname = $userdata->first;
    $userLastname = $userdata->last;
    if (in_array($userEmail, $adminUserList)) {
        $result["status"] = "number-invalid";
        if (array_key_exists("num1", $_GET) == true && array_key_exists("num2", $_GET) == true) {
            // forward the call request to the redbox
            $num1 = $_GET["num1"];
            $num2 = $_GET["num2"];
            $secretKey = md5($num1 . $num2 . $serverKey);
            $result = json_decode(file_get_contents("http://MYASTERISKSERVERDOMAIN:8080/?num1=" . urlencode($num1) . "&num2=" . urlencode($num2) . "&key=" . $secretKey));
        }
    }
}
echo json_encode($result);
<?php

// ubsubscribe functionality. saves to a flat file.
// built by Jamie Kosoy (@jkosoy, jamie@arbitrary.io)
require_once '../config.php';
require_once BASEDIR . '/subscribe/AES.class.php';
// gets the aes key.
$aesKeyFilePath = BASEDIR . '../mailinglist/aes-key.txt';
$fh = fopen($aesKeyFilePath, 'r');
$aesKey = fread($fh, filesize($aesKeyFilePath));
fclose($fh);
// set the aes block size.
$aesBlockSize = 256;
// where the mailing list text file is located.
$listFilePath = BASEDIR . '../mailinglist/list.txt';
$aes = new AES('', $aesKey, $aesBlockSize);
$fh = fopen($listFilePath, 'r');
while (($line = fgets($fh)) !== false) {
    $aes->setData($line);
    $email = $aes->decrypt();
    error_log($email);
    echo "{$email}<br />";
}
fclose($fh);
 /**
  * @param stdClass $params
  * @return int
  */
 public function login(stdClass $params)
 {
     //-------------------------------------------
     // Check that the username do not pass
     // the maximum limit of the field.
     //
     // NOTE:
     // If this condition is met, the user did not
     // use the logon form. Possible hack.
     //-------------------------------------------
     if (strlen($params->authUser) >= 26) {
         return array('success' => false, 'type' => 'error', 'message' => 'Possible hack, please use the Logon Screen.');
     }
     //-------------------------------------------
     // Check that the username do not pass
     // the maximum limit of the field.
     //
     // NOTE:
     // If this condition is met, the user did not
     // use the logon form. Possible hack.
     //-------------------------------------------
     if (strlen($params->authPass) >= 11) {
         return array('success' => false, 'type' => 'error', 'message' => 'Possible hack, please use the Logon Screen.');
     }
     //-------------------------------------------
     // Simple check username
     //-------------------------------------------
     if (!$params->authUser) {
         return array('success' => false, 'type' => 'error', 'message' => 'The username field can not be in blank. Try again.');
     }
     //-------------------------------------------
     // Simple check password
     //-------------------------------------------
     if (!$params->authPass) {
         return array('success' => false, 'type' => 'error', 'message' => 'The password field can not be in blank. Try again.');
     }
     //-------------------------------------------
     // Find the AES key in the selected site
     // And include the rest of the remaining
     // variables to connect to the database.
     //-------------------------------------------
     define('_GaiaEXEC', 1);
     chdir($_SESSION['root']);
     include_once 'registry.php';
     include_once 'classes/AES.php';
     include_once 'classes/dbHelper.php';
     $fileConf = 'sites/' . $params->site . '/conf.php';
     if (file_exists($fileConf)) {
         /** @noinspection PhpIncludeInspection */
         include_once $fileConf;
         $db = new dbHelper();
         $err = $db->getError();
         if (!is_array($err)) {
             return array('success' => false, 'type' => 'error', 'message' => 'For some reason, I can\'t connect to the database.');
         }
         // Do not stop here!, continue with the rest of the code.
     } else {
         return array('success' => false, 'type' => 'error', 'message' => 'No configuration file found for site <span style="font-weight:bold">' . $params->site . '</span>.<br>Please double check URL or contact support desk.');
     }
     //-------------------------------------------
     // remove empty space from username and password
     //-------------------------------------------
     $params->authUser = str_replace(' ', '', $params->authUser);
     $params->authPass = str_replace(' ', '', $params->authPass);
     //-------------------------------------------
     // Convert the password to AES and validate
     //-------------------------------------------
     $aes = new AES($_SESSION['site']['AESkey']);
     //-------------------------------------------
     // Username & password match
     //-------------------------------------------
     $db->setSQL("SELECT id, username, title, fname, mname, lname, email, password\n                         FROM users\n        \t\t        WHERE username   = '******'\n        \t\t          AND authorized = '1'\n        \t\t        LIMIT 1");
     $user = $db->fetchRecord();
     if ($params->authPass != $aes->decrypt($user['password'])) {
         return array('success' => false, 'type' => 'error', 'message' => 'The username or password you provided is invalid.');
     } else {
         //-------------------------------------------
         // Change some User related variables and go
         //-------------------------------------------
         $_SESSION['user']['name'] = $user['title'] . " " . $user['lname'] . ", " . $user['fname'] . " " . $user['mname'];
         $_SESSION['user']['id'] = $user['id'];
         $_SESSION['user']['email'] = $user['email'];
         $_SESSION['user']['site'] = $params->site;
         $_SESSION['user']['auth'] = true;
         //-------------------------------------------
         // Also fetch the current version of the
         // Application & Database
         //-------------------------------------------
         $sql = "SELECT * FROM version LIMIT 1";
         $db->setSQL($sql);
         $version = $db->fetchRecord();
         $_SESSION['ver']['codeName'] = $version['v_tag'];
         $_SESSION['ver']['major'] = $version['v_major'];
         $_SESSION['ver']['rev'] = $version['v_patch'];
         $_SESSION['ver']['minor'] = $version['v_minor'];
         $_SESSION['ver']['database'] = $version['v_database'];
         $_SESSION['site']['localization'] = $params->lang;
         $_SESSION['site']['checkInMode'] = $params->checkInMode;
         $_SESSION['timeout'] = time();
         $session = new Sessions();
         $token = Crypt::encrypt('{"uid":' . $user['id'] . ',"sid":' . $session->loginSession() . ',"site":"' . $params->site . '"}');
         $_SESSION['inactive']['timeout'] = time();
         return array('success' => true, 'token' => $token, 'user' => array('id' => $_SESSION['user']['id'], 'name' => $_SESSION['user']['name'], 'email' => $_SESSION['user']['email']));
     }
 }
Exemple #18
0
function AESdecrypt($text, $password)
{
    require_once "phpAES/AES.class.php";
    $aes = new AES($password);
    return $aes->decrypt(base64_decode($text));
}
session_cache_limiter('private');
include_once $_SESSION['site']['root'] . "/classes/dbHelper.php";
require_once $_SESSION['site']['root'] . "/classes/AES.class.php";
//******************************************************************************
// Reset session count 10 secs = 1 Flop
//******************************************************************************
$_SESSION['site']['flops'] = 0;
//-------------------------------------------
// password to AES and validate
//-------------------------------------------
$aes = new AES($_SESSION['site']['AESkey']);
//------------------------------------------
// Database class instance
//------------------------------------------
$mitos_db = new dbHelper();
$user = $_SESSION['user']['id'];
$mitos_db->setSQL("SELECT *\n        \t\t\t FROM users\n        \t\t\tWHERE users.id = " . $user);
$total = $mitos_db->rowCount();
//---------------------------------------------------------------------------------------
// start the array
//---------------------------------------------------------------------------------------
$rows = array();
foreach ($mitos_db->execStatement(PDO::FETCH_ASSOC) as $row) {
    $row['password'] = $aes->decrypt($row['password']);
    $row['facility_id'] = intval($row['facility_id']);
    array_push($rows, $row);
}
//---------------------------------------------------------------------------------------
// here we are adding "totals" and the root "row" for sencha use
//---------------------------------------------------------------------------------------
print_r(json_encode(array('totals' => $total, 'row' => $rows)));
Exemple #20
0
<?php

header("Content-type: text/html; charset=utf-8");
class AES
{
    private static $key = "set_key_here";
    private static $iv = "setup_gIv_here11";
    public static function encrypt($string)
    {
        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::$key, $string, MCRYPT_MODE_CBC, self::$iv);
        return base64_encode($encrypted);
    }
    public static function decrypt($string)
    {
        $encryptedData = base64_decode($string);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::$key, $encryptedData, MCRYPT_MODE_CBC, self::$iv);
        return $decrypted;
    }
}
if (isset($_GET['data'])) {
    //解密客户端数据
    $decode_str = AES::decrypt($_GET['data']);
    //处理客户端数据
    $decode_str = trim($decode_str) . " append another data";
    //返回处理结果
    echo AES::encrypt($decode_str);
}
Exemple #21
0
include_once $_SESSION['site']['root'] . "/classes/AES.class.php";
include_once $_SESSION['site']['root'] . "/repo/global_functions/global_functions.php";
$aes = new AES($_SESSION['site']['AESkey']);
$mitos_db = new dbHelper();
$rawData = file_get_contents("php://input");
$foo = json_decode($rawData, true);
$data = $foo['row'];
$start = !$_REQUEST["start"] ? 0 : $_REQUEST["start"];
$limit = !$_REQUEST["limit"] ? 30 : $_REQUEST["limit"];
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        $mitos_db->setSQL("SELECT *\n\t\t\t\t             FROM users\n\t\t\t\t            WHERE users.authorized = 1 OR users.username != ''\n        \t\t         ORDER BY username\n        \t\t            LIMIT {$start},{$limit}");
        $total = $mitos_db->rowCount();
        $rows = array();
        foreach ($mitos_db->execStatement(PDO::FETCH_ASSOC) as $row) {
            $row['password'] = $aes->decrypt($row['password']);
            $row['pwd_history1'] = $aes->decrypt($row['pwd_history1']);
            $row['pwd_history2'] = $aes->decrypt($row['pwd_history2']);
            $row['fullname'] = fullname($row['fname'], $row['mname'], $row['lname']);
            $user_id = $row['id'];
            $mitos_db->setSQL("SELECT role_id FROM acl_user_roles WHERE user_id = {$user_id} ");
            $rec = $mitos_db->fetch();
            $row['role_id'] = $rec['role_id'];
            array_push($rows, $row);
        }
        print_r(json_encode(array('totals' => $total, 'row' => $rows)));
        exit;
    case 'POST':
        $role['role_id'] = $data['role_id'];
        unset($data['id'], $data['role_id'], $data['fullname']);
        $data['password'] = $aes->encrypt($data['password']);