/** * Encrypts data using AES * @param String $data Data to encrypt * @return String */ public function symmetricEncrypt($data) { if (!$this->isAesInitialized) { $this->initSymmetric(); } return $this->aes->encrypt($data); }
function AESEncrypt($text, $key, $IV) { $aes = new Crypt_AES(CRYPT_MODE_ECB); $aes->setKey(characet($key)); $aes->setIV(characet($IV)); return bin2hex($aes->encrypt($text)); }
protected function encodeRequest($method, $parameters) { $encoder = new XmlrpcEncoder(); $data = $encoder->encodeCall($method, $parameters); $aes = new Crypt_AES(); $aes->setKey($this->key); return 'comodojo_encrypted_request-' . base64_encode($aes->encrypt($data)); }
/** * Process the launchkey option to prepare for storage in the database. The method will encrypt the data and set * the current version so that the option may be programmatically updated in place in the future. * * @since 1.0.0 * * @param array $input * * @return array */ public function pre_update_option_filter(array $input) { $output = $input; $output['version'] = static::VERSION; 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($input[LaunchKey_WP_Options::OPTION_ROCKET_KEY]) ? static::STATIC_IV : $input[LaunchKey_WP_Options::OPTION_ROCKET_KEY]; $this->crypt_aes->setIV($iv); /** * Encrypt and Base64 encode the encrypted value and set it as the output value * @link https://docs.launchkey.com/glossary.html#term-base64 */ $this->cache[$key] = base64_encode($this->crypt_aes->encrypt($input[LaunchKey_WP_Options::OPTION_SECRET_KEY])); } $output[LaunchKey_WP_Options::OPTION_SECRET_KEY] = $this->cache[$key]; } else { $output[LaunchKey_WP_Options::OPTION_SECRET_KEY] = null; } 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($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]) ? static::STATIC_IV : $input[LaunchKey_WP_Options::OPTION_SECRET_KEY]; $this->crypt_aes->setIV($iv); /** * Encrypt and Base64 encode the encrypted value and set it as the output value * @link https://docs.launchkey.com/glossary.html#term-base64 */ $this->cache[$key] = base64_encode($this->crypt_aes->encrypt($input[LaunchKey_WP_Options::OPTION_PRIVATE_KEY])); } $output[LaunchKey_WP_Options::OPTION_PRIVATE_KEY] = $this->cache[$key]; } else { $output[LaunchKey_WP_Options::OPTION_PRIVATE_KEY] = null; } return $output; }
function _pugpig_bbappworld_encrypt($plaintext, $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); $encrypted = $cipher->encrypt($plaintext); $base64_encrypted = base64_encode($encrypted); return $base64_encrypted; }
/** * @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')); }
function fileWrite($data, $key) { $file = fopen("data.php", "w+"); $aes = new Crypt_AES(); $aes->setKey($key); if ($file) { fwrite($file, $GLOBALS["fileStart"] . $aes->encrypt($data) . $GLOBALS["fileEnd"]); } fclose($file); }
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; }
/** * 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; }
/** * Encrypt $plaintext with $secret, then date and sign the message. * * @param string $secret * @param string $plaintext * @return array * Array(string $body, string $signature). * Note that $body begins with an unencrypted envelope (ttl, iv). * @throws InvalidMessageException */ public static function encryptThenSign($secret, $plaintext) { $iv = crypt_random_string(Constants::AES_BYTES); $keys = AesHelper::deriveAesKeys($secret); $cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC); $cipher->setKeyLength(Constants::AES_BYTES); $cipher->setKey($keys['enc']); $cipher->setIV($iv); // JSON string; this will be signed but not encrypted $jsonEnvelope = json_encode(array('ttl' => Time::getTime() + Constants::REQUEST_TTL, 'iv' => BinHex::bin2hex($iv))); // JSON string; this will be signed and encrypted $jsonEncrypted = $cipher->encrypt($plaintext); $body = $jsonEnvelope . Constants::PROTOCOL_DELIM . $jsonEncrypted; $signature = hash_hmac('sha256', $body, $keys['auth']); return array($body, $signature); }
public function encrypt_data($input_str, $key = SEC_STR) { $aes = new Crypt_AES(); $aes->setKey($key); return $aes->encrypt($input_str); }
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); //---------------------------------------------------------+ //Updating structure for table "log" query_basic("ALTER TABLE `" . DBPREFIX . "log` ADD `scriptid` int(8) UNSIGNED NULL"); //---------------------------------------------------------+ //Updating structure for table "script" query_basic("ALTER TABLE `" . DBPREFIX . "script` CHANGE `daemon` `type` int(1) NOT NULL "); //Updating data for table "config" query_basic("UPDATE `" . DBPREFIX . "config` SET `value` = '0.3.5' WHERE `setting` = 'panelversion' LIMIT 1"); query_basic("\n\t\tINSERT INTO `" . DBPREFIX . "config` (`setting`, `value`)\n\t\tVALUES\n\t\t ('maintenance', '0') ; ");
/** * Encrypt data using the given secret using AES * * The mode is CBC with a random initialization vector, the key is derived * using pbkdf2. * * @param string $data The data that shall be encrypted * @param string $secret The secret/password that shall be used * @return string The ciphertext */ function auth_encrypt($data, $secret) { $iv = auth_randombytes(16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); /* this uses the encrypted IV as IV as suggested in http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C for unique but necessarily random IVs. The resulting ciphertext is compatible to ciphertext that was created using a "normal" IV. */ return $cipher->encrypt($iv . $data); }
function encryptData($data) { global $cryptkey; if (!$data) { return false; } $aes = new Crypt_AES(); $aes->setKey($cryptkey); $cryptdata = $aes->encrypt($data); return trim(base64_encode($cryptdata)); }
/** * Encryption using openssl's AES or phpseclib's AES * (phpseclib uses mcrypt when it is available) * * @param string $data original data * @param string $secret the secret * * @return string the encrypted result */ public function cookieEncrypt($data, $secret) { if ($this->_useOpenSSL()) { return openssl_encrypt($data, '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 base64_encode($cipher->encrypt($data)); } }
/** * Create A New Legit Session * * Note: should be called after Core_AuthService->setSessionInfo() * * @return void * @access public */ public function setSessionPerms() { if (!empty($this->username)) { $credentials = serialize(array('username' => $this->username, 'token' => session_id(), 'key' => $this->auth_key, 'salt' => md5(time()))); switch (CONF_SEC_SESSION_METHOD) { case 'aes256': default: $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKeyLength(256); $cipher->setKey($this->session_key); $this->session['CREDENTIALS'] = $cipher->encrypt($credentials); break; } $_SESSION = $this->session; } }
static function CreateDataPacket($data, $key, $options = array()) { $data = (string) $data; if (!isset($options["prefix"])) { $options["prefix"] = uniqid(mt_rand(), true); } $options["prefix"] = strtolower(dechex(crc32($options["prefix"]))); if (!isset($options["lightweight"]) || !$options["lightweight"]) { $data = $options["prefix"] . "\n" . strtolower(sha1($data)) . "\n" . $data . "\n"; } else { $data = $options["prefix"] . "\n" . strtolower(dechex(crc32($data))) . "\n" . $data . "\n"; } if (self::IsMcryptAvailable()) { $data = self::McryptEncrypt($data, $key, $options); } else { if (class_exists("Crypt_AES")) { if (!isset($options["mode"])) { $options["mode"] = "ECB"; } if (!isset($options["iv"])) { $options["iv"] = str_repeat("", 16); } $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(); if (strlen($data) % 16 != 0) { $data = str_pad($data, strlen($data) + (16 - strlen($data) % 16), ""); } $data = $aes->encrypt($data); } else { return false; } } if (isset($options["key2"])) { $data = substr($data, -1) . substr($data, 0, -1); if (isset($options["iv2"])) { $options["iv"] = $options["iv2"]; } else { unset($options["iv"]); } if (self::IsMcryptAvailable()) { $data = self::McryptEncrypt($data, $options["key2"], $options); } else { if (class_exists("Crypt_AES")) { if ($options["mode"] != "ECB" && (!isset($options["iv"]) || $options["iv"] == "")) { return false; } $aes->setKey($options["key2"]); if (isset($options["iv"])) { $aes->setIV($options["iv"]); } $data = $aes->encrypt($data); } } } return $data; }
/** * Encodes a string. * * By default, uses AES encryption from {@link http://phpseclib.sourceforge.net/ phpseclib}. * Licensed under the {@link http://www.opensource.org/licenses/mit-license.html MIT License}. * * Thanks phpseclib! :) * * @param array $args Array of arguments. See inline doc of function for full details. * @return string The encoded string * @since 1.0-beta */ function bp_rbe_encode($args = array()) { $r = wp_parse_args($args, array('string' => false, 'key' => bp_rbe_get_setting('key'), 'param' => false, 'mode' => 'aes')); if (empty($r['string']) || empty($r['key'])) { return false; } if ($r['param']) { $r['key'] = $r['param'] . $r['key']; } $encrypt = false; // default mode is AES // you can override this with the filter below to prevent the AES library from loading // to modify the return value, use the 'bp_rbe_encode' filter $r['mode'] = apply_filters('bp_rbe_encode_mode', $r['mode']); if ('aes' == $r['mode']) { if (!class_exists('Crypt_AES')) { require BP_RBE_DIR . '/includes/phpseclib/AES.php'; } $cipher = new Crypt_AES(); $cipher->setKey($r['key']); // converts AES binary string to hexadecimal $encrypt = bin2hex($cipher->encrypt($r['string'])); } return apply_filters('bp_rbe_encode', $encrypt, $r['string'], $r['mode'], $r['key'], $r['param']); }
$param['nopass']['y'] = 100; $param['nopass']['width'] = 100; $param['nopass']['bg_path'] = ABSPATH . 'img/k_bg.png'; $param['pass']['x'] = 167; $param['pass']['y'] = 93; $param['pass']['width'] = 118; $param['pass']['bg_path'] = ABSPATH . 'img/k_bg_pass.png'; $rsa = new Crypt_RSA(); extract($rsa->createKey(2048)); $publickey = clear_public_key($publickey); $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); if (!empty($_REQUEST['password'])) { $aes = new Crypt_AES(CRYPT_AES_MODE_ECB); $aes->setKey(md5($_REQUEST['password'])); $text = $privatekey; $aes_encr = $aes->encrypt($text); $private_key = chunk_split(base64_encode($aes_encr), 64); $param = $param['pass']; $k_bg_path = ABSPATH . 'img/k_bg.png'; } else { $private_key = str_replace(array('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----'), '', $privatekey); $param = $param['nopass']; } $iPod = stripos($_SERVER['HTTP_USER_AGENT'], "iPod"); $iPhone = stripos($_SERVER['HTTP_USER_AGENT'], "iPhone"); $iPad = stripos($_SERVER['HTTP_USER_AGENT'], "iPad"); if ($iPod || $iPhone || $iPad) { $gd = key_to_img($private_key, $param, $_SESSION['user_id']); header('Content-Disposition: attachment; filename="Dcoin-private-key-' . $_SESSION['user_id'] . '.png"'); header('Content-type: image/png'); imagepng($gd);
<?php // http://www.linux.org/threads/undelete-files-on-linux-systems.4316/ // NOTE: Delete ALL files using 'srm' (secure remove) apt-get install secure-delete // // Place this file in /etc/nginx to regenerate 'ckencoded' when needed. IMMEDIATELY remove // this script from your server and store it back in compressed and encrypted form elsewhere. // We recommend ccrypt to encrypt and password protect this file, so you can store it anywhere. // There are multiple levels of security deployed to ensure the Cipher Key can not be obtained, // even in the event the hardware is physically stolen. // Level 1 - 'ck', 'ckencoded' and 'ckgen.php' are delete from server after nginx reload. Cipher Key only // exists in memory. All tools and files do not exist on server. THis is the most secure level. // Level 2 - 'ckencoded' and 'ckgen.php' exist in /etc/nginx so 'ck' can be regenerated. This is secure // but not as secure as Level 1. However, a good balance of convience and security. // Level 3 - 'ck' is left in /etc/nginx and secure, as long as the server is not Physically stolen. // If server is stolen or hacker gets inside as root, will gain access to decrypt Database. // This is the most convienant, because nginx restart requires no extract steps. define('PANEL_BASE_PATH', '/home/nulled/www'); set_include_path(get_include_path() . PATH_SEPARATOR . PANEL_BASE_PATH . '/server/modules/core/phpseclib'); require_once PANEL_BASE_PATH . '/server/modules/core/phpseclib/Crypt/AES.php'; $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKey('jd74jdHS87SQNF7fHFS9639f'); $text = $cipher->encrypt('fastcgi_param CKEY zS7hgPk5fBhNZG64F87h6hfD;'); file_put_contents('./ckencoded', base64_encode($text));
function random($len) { if (CRYPT_IS_WINDOWS) { if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) { return openssl_random_pseudo_bytes($len); } // Looks like mcrypt_create_iv with MCRYPT_DEV_RANDOM is still // unreliable on 5.3.6: // https://bugs.php.net/bug.php?id=52523 if (function_exists('mcrypt_create_iv') && version_compare(PHP_VERSION, '5.3.7', '>=')) { return mcrypt_create_iv($len); } } else { if (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($len); } static $fp = null; if ($fp == null) { $fp = @fopen('/dev/urandom', 'rb'); } if ($fp) { return fread($fp, $len); } if (function_exists('mcrypt_create_iv')) { return mcrypt_create_iv($len, MCRYPT_DEV_URANDOM); } } $seed = session_id() . microtime() . getmypid(); $key = pack('H*', sha1($seed . 'A')); $iv = pack('H*', sha1($seed . 'C')); $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR); $crypto->setKey($key); $crypto->setIV($iv); $crypto->enableContinuousBuffer(); //Sliding iv. $start = mt_rand(5, PHP_INT_MAX); $output = ''; for ($i = $start; strlen($output) < $len; $i++) { $output .= $crypto->encrypt($i); } return substr($output, 0, $len); }
function encryptString($pwd = null, $iv_field = "iv") { if (is_null($pwd)) { $pwd = $this->password; } 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); // keys are null-padded to the closest valid size // longer than the longest key and it's truncated $cipher->setKeyLength(256); $keyAB = file($master_key_filepath . "/.mediboard.key"); if (count($keyAB) == 2) { $cipher->setKey($keyAB[0] . $keyAB[1]); $iv = bin2hex(crypt_random_string(16)); $this->{$iv_field} = $iv; $cipher->setIV($iv); $encrypted = rtrim(base64_encode($cipher->encrypt($pwd)), ""); if ($encrypted) { return $encrypted; } } } else { // Key is not available $this->{$iv_field} = ""; } } catch (Exception $e) { return $pwd; } return $pwd; }
function encryptFile($filename, $key) { include_once CL_ROOT . "/include/phpseclib/Crypt/AES.php"; $cipher = new Crypt_AES(); // could use CRYPT_AES_MODE_CBC $cipher->setPassword($key); $plaintext = file_get_contents($filename); //echo $cipher->decrypt($cipher->encrypt($plaintext)); return file_put_contents($filename, $cipher->encrypt($plaintext)); }
exitcron(); } $xmlapi->api1_query($backupserver['username'], 'Fileman', 'Empty Trash'); $deleteftp = json_decode($xmlapi->api2_query($backupserver['username'], 'Ftp', 'delftp', array('user' => $tempftpuser)), true); $log .= 'Deleting temporary FTP account for backup transfer' . PHP_EOL; if ($deleteftp['cpanelresult']['data'][0]['result'] == 1) { $log .= 'Temporary FTP Account deleted' . PHP_EOL; } else { $log .= 'Unable to delete FTP account. The error returned was: ' . $deleteftp['cpanelresult']['error'] . PHP_EOL; exitcron(); } if (isset($backupjob['encryption']) && ($backupjob['encryption'] = 'AES-256')) { $log .= 'Encrypting file with AES-256' . PHP_EOL; $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKey($backupjob['encryptionkey']); file_put_contents($config['path'] . '/files/' . $filename, $cipher->encrypt(file_get_contents($config['path'] . '/files/' . $filename))); } elseif (isset($backupjob['encryption']) && $backupjob['encryption'] == 'GPG') { $log .= 'Encrypting file with GPG' . PHP_EOL; require_once $config['path'] . '/libs/php-gpg-master/GPG.php'; $gpg = new GPG(); $pub_key = new GPG_Public_Key(file_get_contents($backupjob['encryptionkey'])); file_put_contents($config['path'] . '/files/' . $filename, $gpg->encrypt(file_get_contents($config['path'] . '/files/' . $filename))); } $backups[count($backups)] = array('id' => $backupjob['id'], 'file' => $filename, 'size' => filesize($config['path'] . '/files/' . $filename), 'time' => $cpstarttime); file_put_contents($config['path'] . '/db/db-backups.json', json_encode($backups)); } else { $log .= 'Backup failed'; exitcron(); } } else { $log .= 'Backup type not valid' . PHP_EOL;
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;
/** * Encryption using blowfish algorithm (mcrypt) * or phpseclib's AES if mcrypt not available * * @param string $data original data * @param string $secret the secret * * @return string the encrypted result */ public function blowfishEncrypt($data, $secret) { if (!function_exists('mcrypt_encrypt')) { /** * This library uses mcrypt when available, so * we could always call it instead of having an * if/then/else logic, however the include_once * call is costly */ include_once PHPSECLIB_INC_DIR . '/Crypt/AES.php'; $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKey($secret); return base64_encode($cipher->encrypt($data)); } else { return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, $secret, $data, MCRYPT_MODE_CBC, $this->_blowfish_iv)); } }
/** * Convert a private key to the appropriate format. * * @access private * @see setPrivateKeyFormat() * @param String $RSAPrivateKey * @return String */ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) { $num_primes = count($primes); $raw = array('version' => $num_primes == 2 ? chr(0) : chr(1), 'modulus' => $n->toBytes(true), 'publicExponent' => $e->toBytes(true), 'privateExponent' => $d->toBytes(true), 'prime1' => $primes[1]->toBytes(true), 'prime2' => $primes[2]->toBytes(true), 'exponent1' => $exponents[1]->toBytes(true), 'exponent2' => $exponents[2]->toBytes(true), 'coefficient' => $coefficients[2]->toBytes(true)); // if the format in question does not support multi-prime rsa and multi-prime rsa was used, // call _convertPublicKey() instead. switch ($this->privateKeyFormat) { case CRYPT_RSA_PRIVATE_FORMAT_XML: if ($num_primes != 2) { return false; } return "<RSAKeyValue>\r\n" . ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" . ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" . ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" . ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" . ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" . ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" . ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" . ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" . '</RSAKeyValue>'; break; case CRYPT_RSA_PRIVATE_FORMAT_PUTTY: if ($num_primes != 2) { return false; } $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: "; $encryption = !empty($this->password) || is_string($this->password) ? 'aes256-cbc' : 'none'; $key .= $encryption; $key .= "\r\nComment: " . CRYPT_RSA_COMMENT . "\r\n"; $public = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']); $source = pack('Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen(CRYPT_RSA_COMMENT), CRYPT_RSA_COMMENT, strlen($public), $public); $public = base64_encode($public); $key .= "Public-Lines: " . (strlen($public) + 32 >> 6) . "\r\n"; $key .= chunk_split($public, 64); $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']); if (empty($this->password) && !is_string($this->password)) { $source .= pack('Na*', strlen($private), $private); $hashkey = 'putty-private-key-file-mac-key'; } else { $private .= $this->_random(16 - (strlen($private) & 15)); $source .= pack('Na*', strlen($private), $private); if (!class_exists('Crypt_AES')) { require_once 'Crypt/AES.php'; } $sequence = 0; $symkey = ''; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey .= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new Crypt_AES(); $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->encrypt($private); $hashkey = 'putty-private-key-file-mac-key' . $this->password; } $private = base64_encode($private); $key .= 'Private-Lines: ' . (strlen($private) + 32 >> 6) . "\r\n"; $key .= chunk_split($private, 64); if (!class_exists('Crypt_Hash')) { require_once 'Crypt/Hash.php'; } $hash = new Crypt_Hash('sha1'); $hash->setKey(pack('H*', sha1($hashkey))); $key .= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n"; return $key; default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1 $components = array(); foreach ($raw as $name => $value) { $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value); } $RSAPrivateKey = implode('', $components); if ($num_primes > 2) { $OtherPrimeInfos = ''; for ($i = 3; $i <= $num_primes; $i++) { // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo // // OtherPrimeInfo ::= SEQUENCE { // prime INTEGER, -- ri // exponent INTEGER, -- di // coefficient INTEGER -- ti // } $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true)); $OtherPrimeInfo .= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true)); $OtherPrimeInfo .= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true)); $OtherPrimeInfos .= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo); } $RSAPrivateKey .= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos); } $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if (!empty($this->password) || is_string($this->password)) { $iv = $this->_random(8); $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key $symkey .= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8); if (!class_exists('Crypt_TripleDES')) { require_once 'Crypt/TripleDES.php'; } $des = new Crypt_TripleDES(); $des->setKey($symkey); $des->setIV($iv); $iv = strtoupper(bin2hex($iv)); $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: DES-EDE3-CBC,{$iv}\r\n" . "\r\n" . chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) . '-----END RSA PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey)) . '-----END RSA PRIVATE KEY-----'; } return $RSAPrivateKey; } }
/** * Crypt data using Phorum's secret key. * This is used to be able to send Spam Hurdles data to the client, * without allowing the client to read the data. * * @param mixed $data * The data to crypt. This can be an array. This function will * serialize the array. * * @return string * The encrypted data, safe to be sent to the client. */ function spamhurdles_encrypt($data) { global $PHORUM; $aes = new Crypt_AES(); $aes->setKey($PHORUM['private_key']); return base64_encode($aes->encrypt(serialize($data))); }
<?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);
function Encrypt($Cipher, $Val = false) { require_once "Crypt/AES.php"; $Cond = new Crypt_AES(); $Cond->setKey(AESKEY); if ($Val) { return $Cond->decrypt($Cipher); } else { return $Cond->encrypt($Cipher); } }