public function ConvertPaymentModules() { $this->Log('Convert payment modules'); // Clear tables $this->TruncateTable('pmodules', 'pmodules_config'); // Copy pmodules table $pmodule_rset = $this->DbOld->GetAll('SELECT * FROM pmodules'); foreach ($pmodule_rset as &$row) { if ($row['name'] == 'offline_payment') { $row['name'] = 'OfflineBank'; } } $this->BulkInsert('pmodules', $pmodule_rset); // For each pmodule copy config settings $pmodule_config = array(); $Crypto = $GLOBALS['Crypto']; foreach ($pmodule_rset as $pmodule) { // Get old config form for current pmodule $rset = $this->DbOld->GetAll('SELECT * FROM pmodules_config WHERE module_name = ?', array($pmodule['name'])); foreach ($rset as $row) { // Encrypt config value $row['value'] = $this->Crypto->Encrypt($row['key'], LICENSE_FLAGS::REGISTERED_TO); // Push it to pmodule config $pmodule_config[] = $row; } } $this->BulkInsert('pmodules_config', $pmodule_config); }
/** * [set_session 设置session] * @param [type] $user[用户信息] */ public function set_session($user) { session_start(); $_SESSION[$this->login_in_session_name] = $user; $key = Crypto::CreateNewRandomKey(); $safe_session_id = base64_encode($key . Crypto::Encrypt(session_id(), $key)); return $safe_session_id; }
/** * {@inheritdoc} * * Data encoded using json_encode method, only supported formats are allowed! */ public function encrypt($data) { $packed = json_encode($data); try { return base64_encode(\Crypto::Encrypt($packed, $this->key)); } catch (\CannotPerformOperationException $e) { throw new EncryptException($e->getMessage(), $e->getCode(), $e); } catch (\CryptoTestFailedException $e) { throw new EncrypterException($e->getMessage(), $e->getCode(), $e); } }
public function updateDocument(Document $document, $title, $plainContent, User $updater, $passPhrase) { $share = $document->getShareOf($updater); if ($share === null) { throw new AccessDeniedException('The user does not have access to this document'); } $encryptionKey = $this->getEncryptionKey($share, $passPhrase); $encryptedContent = base64_encode(\Crypto::Encrypt($plainContent, $encryptionKey)); $document->setTitle($title); $document->setEncryptedContent($encryptedContent); $this->documentRepository->save($document); }
/** * Method to encrypt a data string. * * @param string $data The data string to encrypt. * @param JCryptKey $key The key object to use for encryption. * * @return string The encrypted data string. * * @since 3.5 * @throws RuntimeException */ public function encrypt($data, JCryptKey $key) { // Validate key. if ($key->type != 'crypto') { throw new InvalidArgumentException('Invalid key of type: ' . $key->type . '. Expected crypto.'); } // Encrypt the data. try { return Crypto::Encrypt($data, $key->public); } catch (CryptoTestFailedException $ex) { throw new RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); } catch (CannotPerformOperationException $ex) { throw new RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); } }
/** * Encrypt a string using AES. * * @param string $plaintext * @param string $key (optional) * @param bool $force_compat (optional) * @return string|false */ public static function encrypt($plaintext, $key = null, $force_compat = false) { // Get the encryption key. $key = $key ?: config('crypto.encryption_key'); $key = substr(hash('sha256', $key, true), 0, 16); // Use defuse/php-encryption if possible. if (!$force_compat && function_exists('openssl_encrypt')) { try { return base64_encode(\Crypto::Encrypt($plaintext, $key)); } catch (\Exception $e) { return false; } } // Otherwise, use the CryptoCompat class. return base64_encode(\CryptoCompat::encrypt($plaintext, $key)); }
private static function TestEncryptDecrypt() { $key = Crypto::CreateNewRandomKey(); $data = "EnCrYpT EvErYThInG"; // Make sure encrypting then decrypting doesn't change the message. $ciphertext = Crypto::Encrypt($data, $key); try { $decrypted = Crypto::Decrypt($ciphertext, $key); } catch (InvalidCiphertextException $ex) { // It's important to catch this and change it into a // CryptoTestFailedException, otherwise a test failure could trick // the user into thinking it's just an invalid ciphertext! throw new CryptoTestFailedException(); } if ($decrypted !== $data) { throw new CryptoTestFailedException(); } // Modifying the ciphertext: Appending a string. try { Crypto::Decrypt($ciphertext . "a", $key); throw new CryptoTestFailedException(); } catch (InvalidCiphertextException $e) { /* expected */ } // Modifying the ciphertext: Changing an IV byte. try { $ciphertext[0] = chr((ord($ciphertext[0]) + 1) % 256); Crypto::Decrypt($ciphertext, $key); throw new CryptoTestFailedException(); } catch (InvalidCiphertextException $e) { /* expected */ } // Decrypting with the wrong key. $key = Crypto::CreateNewRandomKey(); $data = "abcdef"; $ciphertext = Crypto::Encrypt($data, $key); $wrong_key = Crypto::CreateNewRandomKey(); try { Crypto::Decrypt($ciphertext, $wrong_key); throw new CryptoTestFailedException(); } catch (InvalidCiphertextException $e) { /* expected */ } // Ciphertext too small (shorter than HMAC). $key = Crypto::CreateNewRandomKey(); $ciphertext = str_repeat("A", self::MAC_BYTE_SIZE - 1); try { Crypto::Decrypt($ciphertext, $key); throw new CryptoTestFailedException(); } catch (InvalidCiphertextException $e) { /* expected */ } }
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) { $errors = true; response(VALIDATION_DATE_INVALID, $errors, $logger); } // If all of the above validation checks pass, continue on if (!$errors) { // Create encryption key $length = 16; $iterations = 10000; $salt = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); $key = hash_pbkdf2("sha256", $password, $salt . PASSWORD_PEPPER, $iterations, $length); // Create an array of data to be encrypted $data = serialize(array("message" => $message, "email_sender" => $email_sender)); // Encrypt data, reference: https://github.com/defuse/php-encryption/ try { $data_encrypted = Crypto::Encrypt($data, $key); } catch (CryptoTestFailedException $ex) { response(ENCRYPTION_UNSAFE, true, $logger); } catch (CannotPerformOperationException $ex) { response(DECRYPTION_UNSAFE, true, $logger); } // Store the encrypted data $array = array('salt' => base64_encode($salt), 'secret' => base64_encode($data_encrypted), 'expiration_date' => strtotime($expiration_date . ' +1 day')); if ($use_orchestrate) { // Check if Orchestrate is enabled $item = $client->post(ORCHESTRATE_COLLECTION, $array); $id = $item->getKey(); $logger->info(LOG_ORCHESTRATE_POST); } else { // Fallback to Flywheel $item = new \JamesMoss\Flywheel\Document($array);
<?php require_once 'Crypto.php'; try { $key = Crypto::CreateNewRandomKey(); // WARNING: Do NOT encode $key with bin2hex() or base64_encode(), // they may leak the key to the attacker through side channels. } catch (CryptoTestFailedException $ex) { die('Cannot safely create a key'); } catch (CannotPerformOperationException $ex) { die('Cannot safely create a key'); } $message = "ATTACK AT DAWN"; try { $ciphertext = Crypto::Encrypt($message, $key); } catch (CryptoTestFailedException $ex) { die('Cannot safely perform encryption'); } catch (CannotPerformOperationException $ex) { die('Cannot safely perform decryption'); } try { $decrypted = Crypto::Decrypt($ciphertext, $key); } catch (InvalidCiphertextException $ex) { // VERY IMPORTANT // Either: // 1. The ciphertext was modified by the attacker, // 2. The key is wrong, or // 3. $ciphertext is not a valid ciphertext or was corrupted. // Assume the worst. die('DANGER! DANGER! The ciphertext has been tampered with!'); } catch (CryptoTestFailedException $ex) {
/** * Encrypts a message * @param string $message The message to encryept * @return string $ciphertext The encrypted message */ public static function encrypt($message, $key = NULL) { if ($key != NULL) { Yii::log('warning', 'Use of the `$key` parameter is deprecated', 'cii'); } $key = self::getEncryptionKey(); try { $ciphertext = Crypto::Encrypt($message, $key); } catch (CryptoTestFailedException $ex) { Yii::log('Cannot safely perfrom encryption', 'error', 'cii'); throw new Exception('Cannot safely perform encryption'); } catch (CannotPerformOperationException $ex) { Yii::log('Cannot safely perfrom encryption', 'error', 'cii'); throw new Exception('Cannot safely perform encryption'); } return bin2hex($ciphertext); }
<?php require_once 'Crypto.php'; // Note: By default, the runtime tests are "cached" and not re-executed for // every call. To disable this, look at the RuntimeTest() function. $start = microtime(true); for ($i = 0; $i < 1000; $i++) { $key = Crypto::CreateNewRandomKey(); } $end = microtime(true); showResults("CreateNewRandomKey()", $start, $end, 1000); $start = microtime(true); for ($i = 0; $i < 100; $i++) { $ciphertext = Crypto::Encrypt(str_repeat("A", 1024 * 1024), str_repeat("B", 16)); } $end = microtime(true); showResults("Encrypt(1MB)", $start, $end, 100); $start = microtime(true); for ($i = 0; $i < 1000; $i++) { $ciphertext = Crypto::Encrypt(str_repeat("A", 1024), str_repeat("B", 16)); } $end = microtime(true); showResults("Encrypt(1KB)", $start, $end, 1000); function showResults($type, $start, $end, $count) { $time = $end - $start; $rate = $count / $time; echo "{$type}: {$rate} calls/s\n"; }
<?php require __DIR__ . '/private/app.php'; $key = Crypto::CreateNewRandomKey(); $message = 'ATTACK AT DAWN'; $result = null; if (isset($_POST['key'])) { $key = base64url_decode(strval($_POST['key'])); } if (isset($_POST['message'])) { $message = strval($_POST['message']); } try { if (isset($_POST['encode'])) { $result = Crypto::Encrypt($message, $key); } else { if (isset($_POST['decode'])) { $message = Crypto::Decrypt(base64url_decode(strtr($message, array("\r" => '', "\n" => ''))), $key); } } } catch (\Exception $exception) { } // WARNING: Do NOT encode $key with bin2hex() or base64_encode(), // they may leak the key to the attacker through side channels. ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1">