/** * 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)); }
private function encrypt($msg) { if ($msg !== null && $msg != "") { return Crypto::encrypt($msg, $this->key, true); } return null; }
/** * @param mixed $key * @param mixed $value */ public static function set($key, $value) { try { $_SESSION[sha1($key)] = Crypto::encrypt($value, self::$_enckey); } catch (\Exception $e) { self::remove($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 encrypt_native($value, $friendlyKey) { try { return Crypto::encrypt($value, $this->unfriendly($friendlyKey)); } catch (Exception $e) { throw new CryptofierException("Failed to " . __METHOD__); } }
/** * Encrypts data * * @param string $data The data to encrypt * * @return string The encrypted data * * @throws \CodeCollab\Encryption\CryptoException When not being able to (safely) encrypt the data */ public function encrypt(string $data) : string { try { return Crypto::encrypt($data, $this->key); } catch (EnvironmentIsBrokenException $e) { throw new CryptoException($e->getMessage(), $e->getCode(), $e); } }
/** * 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); }
/** * Encrypt 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 $input Value to encrypt using AES256. * @param null|string $key256 An options key used to perform the decryption with instead of the `AES_KEY256`. * * @return string The encrypted value of $input. */ public function encrypt($input, $key256 = null) { if ($key256 === null) { $key256 = \App::config('AES_KEY256'); } //if $key256 = \Defuse\Crypto\Key::loadFromAsciiSafeString($key256); return \Defuse\Crypto\Crypto::encrypt($input, $key256); }
/** * {@inheritdoc} */ public function set($value) { $type = gettype($value); if ($type === 'object') { $value = serialize($value); } $json = json_encode(['type' => $type, 'value' => $value]); $this->cacheItem->set(Crypto::encrypt($json, $this->key)); return $this; }
public static function encrypt($message, $urlSafe = false) { if (!self::$key) { throw new Exception('Generate and set Encryption::$key before calling Encryption::encrypt()!'); } $cipher = Crypto::encrypt($message, self::$key); if ($urlSafe) { $cipher = str_replace(array('/', '+'), array('_', '-'), base64_encode($cipher)); } return $cipher; }
/** * Sets a cookie, while hashing the name and encrypting the value using the key * * @param mixed $key * @param mixed $value * @param integer|boolean $time * @param string $domain */ public static function set($key, $value, $time = false, $domain = '/') { if ($time === false) { $time = time() + 3600 * 24; } //one day try { setcookie(sha1($key), Crypto::encrypt($value, self::$_enckey), $time, $domain); } catch (\Exception $e) { self::remove($key, $domain); } }
/** * Get encrypted time. * * @return string */ protected function getEncryptedTime() { try { return Crypto::encrypt(time(), $this->key); } catch (Ex\CryptoTestFailedException $ex) { return false; //die('Cannot safely perform encryption111111'); } catch (Ex\CannotPerformOperationException $ex) { return false; //die('Cannot safely perform encryption'); } }
/** * Encrypt a message with defuse/php-encryption, using an ephemeral key, * then encrypt the key with RSA. * * @param string $plaintext * @param PublicKey $rsaPublicKey * * @return string */ public static function encrypt($plaintext, PublicKey $rsaPublicKey) { // Random encryption key $ephemeral = Key::createNewRandomKey(); // Encrypt the actual message $symmetric = Base64::encode(Crypto::encrypt($plaintext, $ephemeral, true)); // Use RSA to encrypt the encryption key $storeKey = \base64_encode(self::rsaEncrypt($ephemeral->saveToAsciiSafeString(), $rsaPublicKey)); $packaged = \implode(self::SEPARATOR, array(self::VERSION_TAG, $storeKey, $symmetric)); $checksum = \substr(\hash('sha256', $packaged), 0, 16); // Return the ciphertext return $packaged . self::SEPARATOR . $checksum; }
/** * Method to encrypt a data string. * * @param string $data The data string to encrypt. * @param Key $key The key object to use for encryption. * * @return string The encrypted data string. * * @since 1.3.0 * @throws \InvalidArgumentException * @throws \RuntimeException */ public function encrypt($data, Key $key) { // Validate key. if ($key->getType() != 'crypto') { throw new \InvalidArgumentException('Invalid key of type: ' . $key->getType() . '. Expected crypto.'); } // Encrypt the data. try { return DefuseCrypto::encrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); } }
protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token) { parent::onLoginSuccess($request, $response, $token); try { $password = $request->get('password'); $cookie = $this->getCookie($response); $hash = $this->decodeCookie($cookie->getValue())[3]; $key = $this->createKey($hash); $value = Crypto::encrypt($password, $key); $response->headers->setCookie(new Cookie($this->options['name'] . '_A', $value, $cookie->getExpiresTime(), $this->options['path'], $this->options['domain'], $this->options['secure'], $this->options['httponly'])); } catch (Exception $ex) { $this->logger->error('unexpected exception occurred, while decrypting the rememberMe cookie' . "\n" . $ex->getTraceAsString()); $request->getSession()->invalidate(); throw new AccessDeniedException("Unexpected exception occurred."); } }
/** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $password = '******'; $hash = password_hash($password, PASSWORD_BCRYPT); $salt = base64_decode($this->container->getParameter('salt_key')); if (\strlen($salt) < Key::MIN_SAFE_KEY_BYTE_SIZE) { $suggestedSalt = base64_encode(openssl_random_pseudo_bytes(Key::MIN_SAFE_KEY_BYTE_SIZE * 2)); throw new AbortMigrationException('You need to define an own salt_key in your parameters.yml file which is at least ' . Key::MIN_SAFE_KEY_BYTE_SIZE . ' characters long.' . "\n" . 'Following a randomly created key:' . "\n" . 'salt_key: ' . $suggestedSalt); } $dataKey = null; if ($this->container->hasParameter('data_key_delete_after_migration')) { $asciiDataKey = $this->container->getParameter('data_key_delete_after_migration'); $dataKey = Key::LoadFromAsciiSafeString($asciiDataKey); } if ($dataKey == null) { throw new AbortMigrationException('You need to define an own data_key_delete_after_migration in your parameters.yml which is a key generated with \\Defuse\\Crypto\\Key::CreateNewRandomKey()->saveToAsciiSafeString()' . "\n" . 'Following a randomly created key:' . "\n" . 'data_key_delete_after_migration: ' . Key::CreateNewRandomKey()->saveToAsciiSafeString() . "\n" . 'YOU MUST delete this entry in your parameters.yml afterwards (you can make a copy on a save device).'); } $key = Key::CreateKeyBasedOnPassword($password, $salt); $encryptedDataKey = Crypto::encrypt($asciiDataKey, $key, true); $this->addSql('CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARBINARY(255) NOT NULL, updated_by_user INT NOT NULL, updated_at DATETIME NOT NULL, UNIQUE INDEX UNIQ_64C19C15E237E06 (name), INDEX IDX_64C19C1A7F6CB27 (updated_by_user), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE purchase (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, purchase_date DATE NOT NULL, total VARBINARY(255) NOT NULL, updated_by_user INT NOT NULL, updated_at DATETIME NOT NULL, INDEX IDX_6117D13BA76ED395 (user_id), INDEX IDX_6117D13BA7F6CB27 (updated_by_user), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE purchase_position (id INT AUTO_INCREMENT NOT NULL, purchase_id INT NOT NULL, category_id INT NOT NULL, expression LONGBLOB NOT NULL, price VARBINARY(255) NOT NULL, notice LONGBLOB NULL, updated_by_user INT NOT NULL, updated_at DATETIME NOT NULL, INDEX IDX_6FEEF7A712469DE2 (category_id), INDEX IDX_6FEEF7A7558FBEB9 (purchase_id), INDEX IDX_6FEEF7A7A7F6CB27 (updated_by_user), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE app_users (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(25) NOT NULL, password VARCHAR(64) NOT NULL, email VARCHAR(60) NOT NULL, role VARCHAR(20) DEFAULT NULL, data_key VARBINARY(255) NOT NULL, updated_by_user INT NOT NULL, updated_at DATETIME NOT NULL, UNIQUE INDEX UNIQ_C2502824F85E0677 (username), UNIQUE INDEX UNIQ_C2502824E7927C74 (email), INDEX IDX_C2502824A7F6CB27 (updated_by_user), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE category ADD CONSTRAINT FK_64C19C1A7F6CB27 FOREIGN KEY (updated_by_user) REFERENCES app_users (id)'); $this->addSql('ALTER TABLE purchase ADD CONSTRAINT FK_6117D13BA76ED395 FOREIGN KEY (user_id) REFERENCES app_users (id)'); $this->addSql('ALTER TABLE purchase ADD CONSTRAINT FK_6117D13BA7F6CB27 FOREIGN KEY (updated_by_user) REFERENCES app_users (id)'); $this->addSql('ALTER TABLE purchase_position ADD CONSTRAINT FK_6FEEF7A712469DE2 FOREIGN KEY (category_id) REFERENCES category (id)'); $this->addSql('ALTER TABLE purchase_position ADD CONSTRAINT FK_6FEEF7A7558FBEB9 FOREIGN KEY (purchase_id) REFERENCES purchase (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE purchase_position ADD CONSTRAINT FK_6FEEF7A7A7F6CB27 FOREIGN KEY (updated_by_user) REFERENCES app_users (id)'); $this->addSql('ALTER TABLE app_users ADD CONSTRAINT FK_C2502824A7F6CB27 FOREIGN KEY (updated_by_user) REFERENCES app_users (id)'); $now = date('Y-m-d\\TH:i:s', time()); $this->addSql('INSERT INTO app_users (username, password, role, data_key, updated_by_user, updated_at) ' . 'VALUES (\'admin\', :password, \'ROLE_ADMIN\', :data_key, \'1\', :updated_at)', array('password' => $hash, 'data_key' => $encryptedDataKey, 'updated_at' => $now)); $this->addSql('INSERT INTO category (name, updated_by_user, updated_at) ' . 'VALUES (:name, \'1\', :updated_at)', array('name' => Crypto::encrypt('Lebensmittel', $dataKey, true), 'updated_at' => $now)); }
/** * @param mixed $value * @return string */ public function transform($value) { return Crypto::encrypt($value, $this->key, $this->getBinary()); }
/** * Takes a plaintext Login, encrypts it with the group key, and saves it into the login * @param Login $login * @param $loginPassword * @return Login * @throws Ex\CannotPerformOperationException * @throws \Exception */ public function encryptLoginPassword(Login $login, $loginPassword) { $groupKey = $this->keyProtect->getGroupKey($login->getGroup()); // Encrypt login with group key return $login->setPassword(Crypto::encrypt($loginPassword, $groupKey)); }
use Defuse\Crypto\Crypto; use Defuse\Crypto\Exception as Ex; require_once 'autoload.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 (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!');
<?php use Defuse\Crypto\Crypto; require_once 'autoload.php'; function showResults($type, $start, $end, $count) { $time = $end - $start; $rate = $count / $time; echo $type, ': ', $rate, ' calls/s', "\n"; } // 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);
<?php session_start(); ini_set("log_errors", 1); ini_set("error_log", "/tmp/php-error.log"); error_log("Hello, errors!"); require_once '../includes/defuse-crypto.phar'; use Defuse\Crypto\Crypto; use Defuse\Crypto\KeyProtectedByPassword; include_once '../includes/config.php'; $dbh = new PDO(DB_DRIVER . ":host=" . DB_SERVER . ";port=" . DB_PORT . ";dbname=" . DB_NAME, DB_USER_TEL_CHANGER, DB_PASS_TEL_CHANGER); /* Check if valid */ if (preg_replace('/\\D/', '', filter_var($_POST["TEL"], FILTER_SANITIZE_NUMBER_INT, FILTER_NULL_ON_FAILURE)) == "") { header('HTTP/1.1 400 User is a noob'); die(json_encode(array("result" => false, "message" => "Please enter a telephone number", "error_code" => "tc100"))); } $get_key_stmt = $dbh->prepare("SELECT `PEOPLE_ENCRYPTED_ENCRYPTION_KEY` FROM `" . DB_PEOPLE_TABLE . "` WHERE `" . DB_PEOPLE_TABLE . "`.`PEOPLE_ID` = :PEOPLE_ID;"); $get_key_stmt->bindParam(":PEOPLE_ID", $_SESSION["id"]); $get_key_stmt->execute(); $protected_key = KeyProtectedByPassword::loadFromAsciiSafeString($get_key_stmt->fetch()["PEOPLE_ENCRYPTED_ENCRYPTION_KEY"]); $user_key = $protected_key->unlockKey($_SESSION["key_unlocker"]); $update_stmt = $dbh->prepare("UPDATE `" . DB_PEOPLE_TABLE . "` SET `PEOPLE_PHONE_NUMBER` = :PEOPLE_PHONE_NUMBER WHERE `" . DB_PEOPLE_TABLE . "`.`PEOPLE_ID` = :PEOPLE_ID;"); $update_stmt->bindParam(":PEOPLE_PHONE_NUMBER", Crypto::encrypt(preg_replace('/\\D/', '', filter_var($_POST["TEL"], FILTER_SANITIZE_NUMBER_INT, FILTER_NULL_ON_FAILURE)), $user_key)); $update_stmt->bindParam(":PEOPLE_ID", $_SESSION["id"]); $update_stmt->execute(); header("HTTP/1.1 200 Change successful");
public static function generateCookieToken($login, $password) { $persistence = 0; $config = self::loadConfig(); // Add a cookie for session persistance, if enabled if (isset($config['persistant_enable']) && $config['persistant_enable']) { if (trim($config['persistant_encryption_key']) == '' || trim($config['persistant_cookie_name']) == '') { jLog::log(jLocale::get('jelix~auth.error.persistant.incorrectconfig', 'persistant_cookie_name, persistant_encryption_key'), 'error'); return 0; } if (isset($config['persistant_duration'])) { $persistence = intval($config['persistant_duration']) * 86400; } else { $persistence = 86400; // 24h } $persistence += time(); $cryptokey = \Defuse\Crypto\Key::loadFromAsciiSafeString($config['persistant_encryption_key']); $encrypted = \Defuse\Crypto\Crypto::encrypt(json_encode(array($login, $password)), $cryptokey); setcookie($config['persistant_cookie_name'], $encrypted, $persistence, $config['persistant_cookie_path'], "", false, true); } return $persistence; }
/** * Encrypt something * * @param string $cleartext * @return string hexadecimal representation of crypted string */ public function encrypt($cleartext) { return Crypto::binToHex(Crypto::encrypt($cleartext, $this->getSecretKey())); }
protected function updateObject() { $image = !$this->image ? 'NULL' : $this->db->quote($this->image); $imageIcon = !$this->image_icon ? 'NULL' : $this->db->quote($this->image_icon); $imageSquare = !$this->image_square ? 'NULL' : $this->db->quote($this->image_square); $imageSmall = !$this->image_small ? 'NULL' : $this->db->quote($this->image_small); $bio = !$this->bio ? 'NULL' : $this->db->quote($this->bio); $gender = !in_array($this->gender, array('male', 'female'), true) ? $this->db->quote('male') : $this->db->quote($this->gender); $active = (int) $this->active === 0 ? 0 : 1; // Prepare valid alias. $this->alias = Helper::safeAlias($this->alias, $this->user_id); $query = $this->db->getQuery(true); $query->update($this->db->quoteName('#__itpsc_profiles'))->set($this->db->quoteName('name') . '=' . $this->db->quote($this->name))->set($this->db->quoteName('alias') . '=' . $this->db->quote($this->alias))->set($this->db->quoteName('image') . '=' . $image)->set($this->db->quoteName('image_icon') . '=' . $imageIcon)->set($this->db->quoteName('image_square') . '=' . $imageSquare)->set($this->db->quoteName('image_small') . '=' . $imageSmall)->set($this->db->quoteName('bio') . '=' . $bio)->set($this->db->quoteName('birthday') . '=' . $this->db->quote($this->birthday))->set($this->db->quoteName('gender') . '=' . $gender)->set($this->db->quoteName('website') . '=' . $this->db->quote($this->website))->set($this->db->quoteName('user_id') . '=' . (int) $this->user_id)->set($this->db->quoteName('active') . '=' . (int) $active)->set($this->db->quoteName('location_id') . '=' . (int) $this->location_id)->set($this->db->quoteName('country_id') . '=' . (int) $this->country_id)->where($this->db->quoteName('id') . '=' . (int) $this->id); // Encrypt phone and address. if ($this->secretKey) { $phone = !$this->phone ? null : $this->db->quote(Crypto::encrypt($this->phone, $this->secretKey)); $address = !$this->address ? null : $this->db->quote(Crypto::encrypt($this->address, $this->secretKey)); $query->set($this->db->quoteName('phone') . '=' . $phone)->set($this->db->quoteName('address') . '=' . $address); } $this->db->setQuery($query); $this->db->execute(); }
/** * 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); }
private function store_encrypted_password($password) { // generate a random key require_once 'php-encryption/autoload.php'; try { $key = Crypto::createNewRandomKey(); } catch (Ex\CryptoTestFailedException $ex) { die('Cannot safely create a key'); } catch (Ex\CannotPerformOperationException $ex) { die('Cannot safely create a key'); } // store the key in the session $_SESSION['nextpass']['key'] = $key; // encrypt the password with the key try { $encrypted_password = Crypto::encrypt($password, $key); } catch (Ex\CryptoTestFailedException $ex) { die('Cannot safely perform encryption'); } catch (Ex\CannotPerformOperationException $ex) { die('Cannot safely perform encryption'); } // store the encrypted password in a cookie $encrypted_password = Crypto::binToHex($encrypted_password); $secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443; setcookie("nextpass_password", $encrypted_password, 0, $this->html_code['path'], "", $secure, true); }
/** * {@inheritdoc} */ public function encrypt(string $plaintext) : string { return Crypto::encrypt($plaintext, $this->key); }
/** * Switch the crypto lib to defuse/php-encryption * * @throws Exception */ private function schema5() { if (!is_writable(ELAB_ROOT . 'config.php')) { throw new Exception('Please make your config file writable by server for this update.'); } $legacy = new \Elabftw\Elabftw\LegacyCrypto(); // our new key (raw binary string) try { $new_secret_key = Crypto::CreateNewRandomKey(); } catch (Exception $e) { die($e->getMessage()); } $new_smtp_password = ''; $new_stamp_password = ''; if (strlen(get_config('smtp_password')) > 0) { $old_smtp_password = $legacy->decrypt(get_config('smtp_password')); $new_smtp_password = Crypto::binTohex(Crypto::encrypt($old_smtp_password, $new_secret_key)); } if (strlen(get_config('stamppass')) > 0) { // get the old passwords $old_stamp_password = $legacy->decrypt(get_config('stamppass')); $new_stamp_password = Crypto::binTohex(Crypto::encrypt($old_stamp_password, $new_secret_key)); } $updates = array('smtp_password' => $new_smtp_password, 'stamppass' => $new_stamp_password); if (!update_config($updates)) { throw new Exception('Error updating config with new passwords!'); } // we will rewrite the config file with the new key $contents = "<?php\ndefine('DB_HOST', '" . DB_HOST . "');\ndefine('DB_NAME', '" . DB_NAME . "');\ndefine('DB_USER', '" . DB_USER . "');\ndefine('DB_PASSWORD', '" . DB_PASSWORD . "');\ndefine('ELAB_ROOT', '" . ELAB_ROOT . "');\ndefine('SECRET_KEY', '" . Crypto::binTohex($new_secret_key) . "');\n"; if (file_put_contents('config.php', $contents) == 'false') { throw new Exception('There was a problem writing the file!'); } }
private function encodePasswordAndChangeDataKey(User $user) { $plainPassword = $user->getPlainPassword(); $password = $this->get('security.password_encoder')->encodePassword($user, $plainPassword); $user->setPassword($password); $saltKey = base64_decode($this->getParameter('salt_key')); $key = Key::CreateKeyBasedOnPassword($plainPassword, $saltKey); /*@var $cryptoKey \Defuse\Crypto\Key */ $cryptoKey = $this->get('session')->get(AuthSuccessHandler::SESSION_KEY_DATA_KEY); $asciiDataKey = $cryptoKey->saveToAsciiSafeString(); $encryptedDataKey = Crypto::encrypt($asciiDataKey, $key, true); $user->setDataKey($encryptedDataKey); }
/* 8 character long hex */ /* Random key for pw reset */ $pw_reset_key = bin2hex(openssl_random_pseudo_bytes(32)); /* 64 character long hex */ /* Bind parameters */ $stmt->bindParam(":PEOPLE_ENCRYPTED_ENCRYPTION_KEY", $pw_encoded_key); // cannot be unlocked without $_SESSION var provided $stmt->bindParam(":PEOPLE_FIRST_NAME", filter_var(filter_var($_POST["FIRST_NAME"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW)); $stmt->bindParam(":PEOPLE_LAST_NAME", filter_var(filter_var($_POST["LAST_NAME"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW)); $stmt->bindParam(":PEOPLE_EMAIL_ADDRESS", $PEOPLE_EMAIL_ADDRESS); $stmt->bindParam(":PEOPLE_PHONE_NUMBER", Crypto::encrypt(preg_replace('/\\D/', '', filter_var($_POST["TEL"], FILTER_SANITIZE_NUMBER_INT, FILTER_NULL_ON_FAILURE)), $user_key)); $stmt->bindParam(":PEOPLE_PASSWD", password_hash(base64_decode($_POST["PASSWD"]), PASSWORD_DEFAULT, array("cost" => 12))); $stmt->bindParam(":PEOPLE_PASSWD_RESET_KEY", $pw_reset_key); $stmt->bindParam(":PEOPLE_ADDR_FORMATTED_ADDR", Crypto::encrypt(filter_var(filter_var($_POST["ADDR_FORMATTED"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW), $user_key)); $stmt->bindParam(":PEOPLE_ADDR_LAT", Crypto::encrypt(filter_var(filter_var($_POST["ADDR_LAT"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW), $user_key)); $stmt->bindParam(":PEOPLE_ADDR_LNG", Crypto::encrypt(filter_var(filter_var($_POST["ADDR_LNG"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW), $user_key)); $stmt->bindParam(":PEOPLE_ADDR_COUNTRY", filter_var(filter_var($_POST["ADDR_COUNTRY"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW)); $stmt->bindParam(":PEOPLE_ADDR_ADMIN_AREA_LEVEL_1", filter_var(filter_var($_POST["ADDR_ADMIN_LEVEL_1"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW)); $stmt->bindParam(":PEOPLE_EMAIL_VERIFICATION_KEY", $email_key); $stmt->bindParam(":PEOPLE_PICTURE_LOCATION", $pici); $stmt->bindParam(":PEOPLE_REGISTERED_IP", $_SERVER["REMOTE_ADDR"]); $stmt->bindParam(":PEOPLE_REGISTERED_UA", $_SERVER["HTTP_USER_AGENT"]); $stmt->bindParam(":PEOPLE_LAST_LOGIN_IP", $_SERVER["REMOTE_ADDR"]); $stmt->bindParam(":PEOPLE_LAST_LOGIN_UA", $_SERVER["HTTP_USER_AGENT"]); /* Execute */ $stmt->execute(); /* Get ID from new account */ $id_get = $dbh_get->prepare("SELECT `PEOPLE_ID` FROM `" . DB_PEOPLE_TABLE . "` WHERE `PEOPLE_EMAIL_ADDRESS` = ?"); $id_get->bindParam(1, $PEOPLE_EMAIL_ADDRESS); $id_get->execute(); /* Execute */