/** * High-level tests of Crypto operations. * * @throws Ex\EnvironmentIsBrokenException */ private static function testEncryptDecrypt() { $key = Key::createNewRandomKey(); $data = "EnCrYpT EvErYThInG"; // Make sure encrypting then decrypting doesn't change the message. $ciphertext = Crypto::encrypt($data, $key, true); try { $decrypted = Crypto::decrypt($ciphertext, $key, true); } catch (Ex\WrongKeyOrModifiedCiphertextException $ex) { // It's important to catch this and change it into a // Ex\EnvironmentIsBrokenException, otherwise a test failure could trick // the user into thinking it's just an invalid ciphertext! throw new Ex\EnvironmentIsBrokenException(); } if ($decrypted !== $data) { throw new Ex\EnvironmentIsBrokenException(); } // Modifying the ciphertext: Appending a string. try { Crypto::decrypt($ciphertext . 'a', $key, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } // Modifying the ciphertext: Changing an HMAC byte. $indices_to_change = [0, Core::HEADER_VERSION_SIZE + 1, Core::HEADER_VERSION_SIZE + Core::SALT_BYTE_SIZE + 1, Core::HEADER_VERSION_SIZE + Core::SALT_BYTE_SIZE + Core::BLOCK_BYTE_SIZE + 1]; foreach ($indices_to_change as $index) { try { $ciphertext[$index] = \chr((\ord($ciphertext[$index]) + 1) % 256); Crypto::decrypt($ciphertext, $key, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } } // Decrypting with the wrong key. $key = Key::createNewRandomKey(); $data = 'abcdef'; $ciphertext = Crypto::encrypt($data, $key, true); $wrong_key = Key::createNewRandomKey(); try { Crypto::decrypt($ciphertext, $wrong_key, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } // Ciphertext too small. $key = Key::createNewRandomKey(); $ciphertext = \str_repeat('A', Core::MINIMUM_CIPHERTEXT_SIZE - 1); try { Crypto::decrypt($ciphertext, $key, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } }
public function testEmptyString() { $str = ''; $key = Key::createNewRandomKey(); $cipher = Crypto::encrypt($str, $key); $this->assertSame($str, Crypto::decrypt($cipher, $key)); }
/** * @see CryptofierCryptoInterface * * NB: Shouldn't be called externally/by derived classes as doesn't use the server key! * * @param $value * @param $friendlyKey * * @return string - maybe unfriendly * @throws CryptofierException */ protected final function decrypt_native($value, $friendlyKey) { try { return Crypto::decrypt($value, $this->unfriendly($friendlyKey)); } catch (Exception $e) { throw new CryptofierException("Failed to " . __METHOD__); } }
/** * {@inheritdoc} */ public function get() { if (!$this->isHit()) { return; } $item = json_decode(Crypto::decrypt($this->cacheItem->get(), $this->key), true); return $this->transform($item); }
/** * Key rotation method -- decrypt with your old key then re-encrypt with your new key * * @param string $ciphertext * @param string $oldKey - must be exactly 16 bytes * @param string $newKey - must be exactly 16 bytes * @return string */ public static function rotateKey($ciphertext, $oldKey, $newKey) { if (self::safeStrlen($oldKey) !== 16 || self::safeStrlen($newKey) !== 16) { throw new \Exception("Encryption keys must be 16 bytes long"); } $plaintext = Crypto::decrypt($ciphertext, $oldKey); return Crypto::encrypt($plaintext, $newKey); }
private function decrypt($resource) { if ($resource !== null) { $msg = stream_get_contents($resource); return Crypto::decrypt($msg, $this->key, true); } return null; }
/** * Decrypt with AES256. * This method relies on the settings in application config `AES_KEY256` which is generated at install to * a unique key for your application. You can use a different key by passing it in at `$key256`. * * * @param string $crypt Value to decrypt using AES256. * @param null|string $key256 An options key used to perform the decryption with instead of the `AES_KEY256`. * * @return string The decrypted value of $crypt. */ public function decrypt($crypt, $key256 = null) { if ($key256 === null) { $key256 = \App::config('AES_KEY256'); } //if $key256 = \Defuse\Crypto\Key::loadFromAsciiSafeString($key256); return \Defuse\Crypto\Crypto::decrypt($crypt, $key256); }
public static function encryptDataKeyAndPutIntoSession(Request $request, User $user, $password, $salt) { $key = Key::CreateKeyBasedOnPassword($password, $salt); $encryptedKey = $user->getDataKey(); $asciiDataKey = Crypto::decrypt($encryptedKey, $key, true); $dataKey = Key::LoadFromAsciiSafeString($asciiDataKey); $request->getSession()->set(AuthSuccessHandler::SESSION_KEY_DATA_KEY, $dataKey); return $dataKey; }
/** * Decrypts data * * @param string $data The data to encrypt * * @return string The encrypted data * * @throws \CodeCollab\Encryption\CryptoException When the message could not be decrypted * @throws \CodeCollab\Encryption\FraudException When the message is potentially tampered with */ public function decrypt(string $data) : string { try { return Crypto::decrypt($data, $this->key); } catch (WrongKeyOrModifiedCiphertextException $e) { throw new FraudException($e->getMessage(), $e->getCode(), $e); } catch (EnvironmentIsBrokenException $e) { throw new CryptoException($e->getMessage(), $e->getCode(), $e); } }
/** * Returns a cookie value thus also decrypting it * * @param mixed $key * @param mixed|boolean $default * @param string $domain * * @return mixed */ public static function get($key, $default = false, $domain = '/') { if (isset($_COOKIE[sha1($key)])) { try { return Crypto::decrypt($_COOKIE[sha1($key)], self::$_enckey); } catch (\Exception $e) { self::remove($key, $domain); } } return $default; }
public static function decrypt($ciphertext, $urlSafe = false) { if (!self::$key) { throw new Exception('Generate and set Encryption::$key before calling Encryption::encrypt()!'); } if ($urlSafe) { $ciphertext = base64_decode(str_replace(array('_', '-'), array('/', '+'), $ciphertext)); } try { return Crypto::decrypt($ciphertext, self::$key); } catch (Exception $e) { return ""; } }
/** * Method to decrypt a data string. * * @param string $data The encrypted string to decrypt. * @param Key $key The key object to use for decryption. * * @return string The decrypted data string. * * @since 1.3.0 * @throws \InvalidArgumentException * @throws \RuntimeException */ public function decrypt($data, Key $key) { // Validate key. if ($key->getType() != 'crypto') { throw new \InvalidArgumentException('Invalid key of type: ' . $key->getType() . '. Expected crypto.'); } // Decrypt the data. try { return DefuseCrypto::decrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (WrongKeyOrModifiedCiphertextException $ex) { throw new \RuntimeException('DANGER! DANGER! The ciphertext has been tampered with!', $ex->getCode(), $ex); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex); } }
protected function processAutoLoginCookie(array $cookieParts, Request $request) { $user = parent::processAutoLoginCookie($cookieParts, $request); try { $hash = $cookieParts[3]; $key = $this->createKey($hash); if ($cookieAppendum = $request->cookies->get($this->options['name'] . '_A')) { $this->logger->debug('cookieAppendum with name ' . $this->options['name'] . '_A found.'); $password = Crypto::decrypt($cookieAppendum, $key); AuthSuccessHandler::encryptDataKeyAndPutIntoSession($request, $user, $password, $this->saltKey); } else { throw new AuthenticationException("Unexpected exception occurred."); } } catch (Exception $ex) { $this->logger->error('unexpected exception occurred, while decrypting the rememberMe cookie' . "\n" . $ex->getTraceAsString()); throw new AuthenticationException("Unexpected exception occurred."); } return $user; }
private function decryptProtected($key, $encryptedField) { // Decrypt encrypted field with group key $plaintext = ""; try { $plaintext = Crypto::decrypt($encryptedField, $key); } catch (Ex\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. throw $ex; // Unable to decode encrypted field } catch (Ex\CryptoTestFailedException $ex) { throw $ex; // Cannot safely perform field } catch (Ex\CannotPerformOperationException $ex) { throw $ex; // Cannot safely perform field } return $plaintext; }
<div class="row"> <div class="input-field col s12 m6"> <input id="tel" type="text" value="<?php echo Crypto::decrypt($profile["PEOPLE_PHONE_NUMBER"], $user_key); ?> " required> <label for="tel">Telephone number</label> </div> </div> <div class="btn orange btn-large waves-effect waves-light" id="changeTel">Done</div> <div class="btn orange btn-large waves-effect waves-light" id="abortTelChange">Cancel</div> </div> <div id="tel-current" class="col s12"> <h4><?php // pretty phone number $phone_number = Crypto::decrypt($profile["PEOPLE_PHONE_NUMBER"], $user_key); $areaCode = substr($phone_number, 0, 3); $nextThree = substr($phone_number, 3, 3); $lastFour = substr($phone_number, 6, 4); echo '(' . $areaCode . ') ' . $nextThree . '-' . $lastFour; ?> </h4> </div> </div> </div> <div id="security" class="col s12"> <h2>Security</h2> <div class="row"> <div class="col s12"> <h3>Password <i id="edit-pw-button" class="edit-btn material-icons h3">edit</i></h3> </div>
/** * Decrypt the given time. * * @param mixed $time * @return string|null */ protected function decryptTime($time) { try { return Crypto::decrypt($time, $this->key); } catch (Ex\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. return false; //die('DANGER! DANGER! The ciphertext has been tampered with!'); } catch (Ex\CryptoTestFailedException $ex) { return false; //die('Cannot safely perform decryption'); } catch (Ex\CannotPerformOperationException $ex) { return false; //die('Cannot safely perform decryption2'); } }
$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 (Ex\CryptoTestFailed $ex) { die('Cannot safely create a key'); } catch (Ex\CannotPerformOperation $ex) { die('Cannot safely create a key'); } $message = "ATTACK AT DAWN"; try { $ciphertext = Crypto::encrypt($message, $key); } catch (Ex\CryptoTestFailed $ex) { die('Cannot safely perform encryption'); } catch (Ex\CannotPerformOperation $ex) { die('Cannot safely perform encryption'); } try { $decrypted = Crypto::decrypt($ciphertext, $key); } catch (Ex\InvalidCiphertext $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 (Ex\CryptoTestFailed $ex) { die('Cannot safely perform dencryption'); } catch (Ex\CannotPerformOperation $ex) { die('Cannot safely perform decryption'); }
</h6> <h4 class="profile-item"> <?php echo $profile["PEOPLE_EMAIL_ADDRESS"]; ?> </h4> </div> </div> <div class="row"> <div class="col s12"> <h6> Address </h6> <h4 class="profile-item"> <?php echo Crypto::decrypt($profile["PEOPLE_ADDR_FORMATTED_ADDR"], $user_key); ?> </h4> </div> </div> <div class="row"> <div class="col s12"> <h6> Last Login </h6> <h4 class="profile-item"> <?php echo $profile["PEOPLE_LAST_LOGIN_IP"]; ?> at <?php echo $profile["PEOPLE_LAST_LOGIN_TIMESTAMP"];
/** * Load notification record from database. * * <code> * $profileId = 1; * * $profile = new Socialcommunity\Profile\Profile(\JFactory::getDbo()); * $profile->load($profileId); * </code> * * @param int|array $keys * @param array $options */ public function load($keys, array $options = array()) { // Create a new query object. $query = $this->db->getQuery(true); $query->select('a.id, a.name, a.alias, a.image, a.image_icon, a.image_square, a.image_small, a.bio, a.phone, ' . 'a.address, a.birthday, a.gender, a.location_id, a.country_id, a.website, a.user_id, a.active, ' . $query->concatenate(array('a.user_id', 'a.alias'), '-') . ' AS slug')->from($this->db->quoteName('#__itpsc_profiles', 'a')); // Filter by keys. if (!is_array($keys)) { $query->where('a.id = ' . (int) $keys); } else { foreach ($keys as $key => $value) { $query->where($this->db->quoteName('a.' . $key) . ' = ' . $this->db->quote($value)); } } $this->db->setQuery($query); $result = (array) $this->db->loadAssoc(); $this->bind($result); // Decrypt phone and address. if ($this->secretKey) { $this->phone = !$this->phone ? null : $this->db->quote(Crypto::decrypt($this->phone, $this->secretKey)); $this->address = !$this->address ? null : $this->db->quote(Crypto::decrypt($this->address, $this->secretKey)); } }
/** * Decrypt something * * @param string $ciphertext The hexadecimal string * @return string cleartext string */ public function decrypt($ciphertext) { return Crypto::decrypt(Crypto::hexToBin($ciphertext), $this->getSecretKey()); }
/** * @param mixed $value * @return string */ public function reverseTransform($value) { return Crypto::decrypt($value, $this->key, $this->getBinary()); }
/** * {@inheritdoc} */ public function decrypt(string $ciphertext) : string { return Crypto::decrypt($ciphertext, $this->key); }
/** * */ public static function checkCookieToken() { $config = self::loadConfig(); if (isset($config['persistant_enable']) && $config['persistant_enable'] && !self::isConnected()) { if (trim($config['persistant_cookie_name']) != '' && trim($config['persistant_encryption_key']) != '') { $cookieName = $config['persistant_cookie_name']; if (isset($_COOKIE[$cookieName]) && is_string($_COOKIE[$cookieName]) && strlen($_COOKIE[$cookieName])) { $cryptokey = \Defuse\Crypto\Key::loadFromAsciiSafeString($config['persistant_encryption_key']); $decrypted = \Defuse\Crypto\Crypto::decrypt($_COOKIE[$cookieName], $cryptokey); $decrypted = json_decode($decrypted, true); if ($decrypted && is_array($decrypted) && count($decrypted) == 2) { list($login, $password) = $decrypted; self::login($login, $password, true); } } } } }
public function decrypt_password() { if ($this->logged_in !== true) { $this->debug->error("Not logged in!"); } if (empty($_COOKIE['nextpass_password']) or empty($_SESSION['nextpass']['key'])) { $this->debug->error("Password is not stored in Cookie or Session!"); } require_once 'php-encryption/autoload.php'; $encrypted_password = $_COOKIE['nextpass_password']; $encrypted_password = Crypto::hexToBin($encrypted_password); $key = $_SESSION['nextpass']['key']; try { $password = Crypto::decrypt($encrypted_password, $key); } catch (Ex\InvalidCiphertextException $ex) { // 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 (Ex\CryptoTestFailedException $ex) { die('Cannot safely perform decryption'); } catch (Ex\CannotPerformOperationException $ex) { die('Cannot safely perform decryption'); } return $password; }
/** * Key rotation method -- decrypt with your old key then re-encrypt with your new key * * @param string $ciphertext * @param Key $oldKey * @param Key $newKey * @return string */ public static function rotateKey(string $ciphertext, Key $oldKey, Key $newKey) : string { $plaintext = Crypto::decrypt($ciphertext, $oldKey); return Crypto::encrypt($plaintext, $newKey); }
/** * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException * @expectedExceptionMessage Bad version header */ public function testDecryptLegacyWithWrongMethodStraightUpBinary() { $cipher = Encoding::hexToBin('cfdad83ebd506d2c9ada8d48030d0bca' . '2ff94760e6d39c186adb1290d6c47e35' . '821e262673c5631c42ebbaf70774d6ef' . '29aa5eee0e412d646ae380e08189c85d' . '024b5e2009106870f1db25d8b85fd01f' . '00000000000000000000000000000000'); /* This time, treat the binary as binary. */ $plain = Crypto::decrypt($cipher, Key::loadFromRawBytesForTestingPurposesOnlyInsecure("\t\n\v\f\r" . "\t\n\v\f\r"), true); }