/** * Create a new UserAgentGenerator instance. * * @param Key $secretKey * @param string|null $userAgent */ public function __construct(Key $secretKey, string $userAgent = null) { if ($userAgent !== null) { $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? ''; } $this->userAgent = $secretKey->saveToAsciiSafeString() . $userAgent; }
private function encryptGroupKey(User $user, Key $groupKey) { // Encrypt key with users public key $pubKey = $user->getPubKey(); // TODO check return openssl_public_encrypt($groupKey->saveToAsciiSafeString(), $encryptedKey, $pubKey); return $encryptedKey; }
/** * @expectedException \Defuse\Crypto\Exception\BadFormatException * @excpectedExceptionMessage key version header */ public function testIncorrectHeader() { $key = Key::createNewRandomKey(); $str = $key->saveToAsciiSafeString(); $str[0] = 'f'; Key::loadFromAsciiSafeString($str); }
/** * @expectedException \Defuse\Crypto\Exception\InvalidCiphertext */ public function testBitflip() { $key = \Defuse\Crypto\Key::LoadFromAsciiSafeString(\hex2bin('0102030405060708090a0b0c0d0e0f10')); $password = PasswordLock::hashAndEncrypt('YELLOW SUBMARINE', $key); $password[0] = \ord($password[0]) === 0 ? 255 : 0; PasswordLock::decryptAndVerify('YELLOW SUBMARINE', $password, $key); }
/** * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException */ public function testBitflip() { $key = Key::createNewRandomKey(); $password = PasswordLock::hashAndEncrypt('YELLOW SUBMARINE', $key); $password[0] = \ord($password[0]) === 0 ? 255 : 0; PasswordLock::decryptAndVerify('YELLOW SUBMARINE', $password, $key); }
function install() { if (self::$key === null) { $cryptokey = \Defuse\Crypto\Key::createNewRandomKey(); self::$key = $cryptokey->saveToAsciiSafeString(); } $authconfig = $this->getConfigIni()->getValue('auth', 'coordplugins'); $authconfigMaster = $this->getLocalConfigIni()->getValue('auth', 'coordplugins'); $forWS = in_array($this->entryPoint->type, array('json', 'jsonrpc', 'soap', 'xmlrpc')); if (!$authconfig || $forWS && $authconfig == $authconfigMaster) { if ($forWS) { $pluginIni = 'authsw.coord.ini.php'; } else { $pluginIni = 'auth.coord.ini.php'; } $authconfig = dirname($this->entryPoint->getConfigFile()) . '/' . $pluginIni; if ($this->firstExec('auth:' . $authconfig)) { // no configuration, let's install the plugin for the entry point $this->config->setValue('auth', $authconfig, 'coordplugins'); if (!file_exists(jApp::configPath($authconfig))) { $this->copyFile('var/config/' . $pluginIni, jApp::configPath($authconfig)); } } } $this->getLocalConfigIni()->setValue('persistant_encryption_key', self::$key, 'coordplugin_auth'); }
public function testEncryptionAndDecrypt() { $e = new Encrypter(Key::createNewRandomKey()); $encrypted = $e->encrypt('foo'); $this->assertNotEquals('foo', $encrypted); $this->assertEquals('foo', $e->decrypt($encrypted)); }
/** * Creates instance * * @param string $key The encryption key * * @throws \CodeCollab\Encryption\CryptoException When the key is not in a valid format */ public function __construct(string $key) { try { $this->key = DefuseKey::loadFromAsciiSafeString($key); } catch (BadFormatException $e) { throw new CryptoException($e->getMessage(), $e->getCode(), $e); } }
public function testProviderWithoutConfigManagerAndNamespace() { $container = new Container(); $container->register(new HashingServiceProvider()); $container->instance('viserio.hashing.options', ['key' => Key::createNewRandomKey()]); $this->assertInstanceOf(Password::class, $container->get(Password::class)); $this->assertInstanceOf(Password::class, $container->get('password')); }
/** * @param $key * @param array $options */ public function __construct($key, array $options = []) { if (is_string($key)) { $key = Key::loadFromAsciiSafeString($key); } $this->key = $key; $this->setOptions($options); }
/** * Generates a new key * * @return string The generated key * * @throws \CodeCollab\Encryption\CryptoException When not being able to create a sufficient strong key */ public function generate() : string { try { return DefuseKey::createNewRandomKey()->saveToAsciiSafeString(); } catch (EnvironmentIsBrokenException $e) { throw new CryptoException($e->getMessage(), $e->getCode(), $e); } }
/** * 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 function testGenerate() { $generator = new UserAgentGenerator(Key::createNewRandomKey(), 'test'); $this->assertInternalType('string', $generator->generate()); $this->assertSame(40, strlen($generator->generate())); $generator = new UserAgentGenerator(Key::createNewRandomKey()); $this->assertInternalType('string', $generator->generate()); $this->assertSame(40, strlen($generator->generate())); }
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; }
public function testProviderWithoutConfigManagerAndNamespace() { $container = new Container(); $container->register(new EncrypterServiceProvider()); $key = Key::createNewRandomKey(); $container->instance('viserio.encryption.options', ['key' => $key->saveToAsciiSafeString()]); $this->assertInstanceOf(Encrypter::class, $container->get(Encrypter::class)); $this->assertInstanceOf(Encrypter::class, $container->get('encrypter')); }
public function testEncryptDecryptWithPassword() { $data = "EnCrYpT EvErYThInG"; $password = '******'; // Make sure encrypting then decrypting doesn't change the message. $ciphertext = Crypto::encryptWithPassword($data, $password, true); try { $decrypted = Crypto::decryptWithPassword($ciphertext, $password, 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::decryptWithPassword($ciphertext . 'a', $password, 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::decryptWithPassword($ciphertext, $password, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } } // Decrypting with the wrong password. $password = '******'; $data = 'abcdef'; $ciphertext = Crypto::encryptWithPassword($data, $password, true); $wrong_password = '******'; try { Crypto::decryptWithPassword($ciphertext, $wrong_password, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } // Ciphertext too small. $password = Key::createNewRandomKey(); $ciphertext = \str_repeat('A', Core::MINIMUM_CIPHERTEXT_SIZE - 1); try { Crypto::decryptWithPassword($ciphertext, $password, true); throw new Ex\EnvironmentIsBrokenException(); } catch (Ex\WrongKeyOrModifiedCiphertextException $e) { /* expected */ } }
public function testGenerateWithIp() { $_SERVER['REMOTE_ADDR'] = '192.0.2.60'; $generator = new ClientIpGenerator(Key::createNewRandomKey()); $this->assertInternalType('string', $generator->generate()); $this->assertSame(40, strlen($generator->generate())); unset($_SERVER['REMOTE_ADDR']); // return empty ip string $this->assertInternalType('string', $generator->generate()); $this->assertSame(40, strlen($generator->generate())); }
public function setUp() { parent::setUp(); $encrypter = new Encrypter(Key::createNewRandomKey()); $config = $this->mock(ConfigContract::class); $config->shouldReceive('get')->with('cache.drivers', []); $config->shouldReceive('get')->with('cache.namespace'); $manager = new SessionManager($config, $encrypter); $manager->setContainer(new ArrayContainer([JarContract::class => $this->mock(JarContract::class), CacheManagerContract::class => new CacheManager($config)])); $this->manager = $manager; }
public function testProvider() { $container = new Container(); $container->register(new EncrypterServiceProvider()); $container->register(new ConfigServiceProvider()); $container->register(new SessionServiceProvider()); $container->register(new FilesServiceProvider()); $key = Key::createNewRandomKey(); $container->get('config')->set('encryption', ['key' => $key->saveToAsciiSafeString()]); $container->get('config')->set('session', ['path' => '', 'lifetime' => 3000, 'cookie' => 'test']); $this->assertInstanceOf(SessionManager::class, $container->get(SessionManager::class)); $this->assertInstanceOf(SessionManager::class, $container->get('session')); $this->assertInstanceOf(StoreContract::class, $container->get('session.store')); }
/** * * Encrypt a message with defuse/php-encryption, using an ephemeral key, * then encrypt the key with RSA. * * @param string $ciphertext * @param PrivateKey $rsaPrivateKey * * @return string * @throws InvalidCiphertextException * @throws InvalidChecksumException */ public static function decrypt($ciphertext, PrivateKey $rsaPrivateKey) { $split = explode(self::SEPARATOR, $ciphertext); if (\count($split) !== 4) { throw new InvalidCiphertextException('Invalid ciphertext message'); } if (!\hash_equals($split[0], self::VERSION_TAG)) { throw new InvalidCiphertextException('Invalid version tag'); } $checksum = \substr(\hash('sha256', implode('$', array_slice($split, 0, 3))), 0, 16); if (!\hash_equals($split[3], $checksum)) { throw new InvalidChecksumException('Invalid checksum'); } $key = Key::loadFromAsciiSafeString(self::rsaDecrypt(Base64::decode($split[1]), $rsaPrivateKey)); return Crypto::Decrypt(Base64::decode($split[2]), $key, true); }
function install() { if (self::$key === null) { $cryptokey = \Defuse\Crypto\Key::createNewRandomKey(); self::$key = $cryptokey->saveToAsciiSafeString(); } $conf = $this->getConfigIni()->getValue('auth', 'coordplugins'); if ($conf == '1') { $this->getConfigIni()->removeValue('persistant_crypt_key', 'coordplugin_auth'); } else { if ($conf) { $conff = jApp::configPath($conf); if (file_exists($conff)) { $ini = new \Jelix\IniFile\IniModifier($conff); $ini->removeValue('persistant_crypt_key'); } } } $this->getLocalConfigIni()->setValue('persistant_encryption_key', self::$key, 'coordplugin_auth'); }
/** * @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)); }
/** * Method to generate a new encryption key object. * * @param array $options Key generation options. * * @return Key * * @since 1.3.0 * @throws \RuntimeException */ public function generateKey(array $options = array()) { // Generate the encryption key. try { $public = DefuseKey::createNewRandomKey(); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely create a key', $ex->getCode(), $ex); } // Create the new encryption key object. return new Key('crypto', $public->saveToAsciiSafeString(), $public->getRawBytes()); }
/** * Decrypt the contents of a file handle $inputHandle and store the results * in $outputHandle using HKDF of $key to decrypt then verify * * @param resource $inputHandle * @param resource $outputHandle * @param Key $key * @return boolean */ public static function decryptResource($inputHandle, $outputHandle, Key $key) { // Because we don't have strict typing in PHP 5 if (!\is_resource($inputHandle)) { throw new Ex\InvalidInput('Input handle must be a resource!'); } if (!\is_resource($outputHandle)) { throw new Ex\InvalidInput('Output handle must be a resource!'); } // Parse the header. $header = self::readBytes($inputHandle, Core::HEADER_VERSION_SIZE); $config = self::getFileVersionConfigFromHeader($header, Core::CURRENT_FILE_VERSION); // Let's add this check before anything if (!\in_array($config->hashFunctionName(), \hash_algos())) { throw new Ex\CannotPerformOperationException('The specified hash function does not exist'); } // Let's grab the file salt. $file_salt = self::readBytes($inputHandle, $config->saltByteSize()); // For storing MACs of each buffer chunk $macs = []; /** * 1. We need to decode some values from our files */ /** * Let's split our keys * * $ekey -- Encryption Key -- used for AES */ $ekey = Core::HKDF($config->hashFunctionName(), $key->getRawBytes(), $config->keyByteSize(), $config->encryptionInfoString(), $file_salt, $config); /** * $akey -- Authentication Key -- used for HMAC */ $akey = Core::HKDF($config->hashFunctionName(), $key->getRawBytes(), $config->keyByteSize(), $config->authenticationInfoString(), $file_salt, $config); /** * Grab our IV from the encrypted message * * It should be the first N blocks of the file (N = 16) */ $ivsize = \openssl_cipher_iv_length($config->cipherMethod()); $iv = self::readBytes($inputHandle, $ivsize); // How much do we increase the counter after each buffered encryption to prevent nonce reuse $inc = $config->bufferByteSize() / $config->blockByteSize(); $thisIv = $iv; /** * Let's grab our MAC * * It should be the last N blocks of the file (N = 32) */ if (\fseek($inputHandle, -1 * $config->macByteSize(), SEEK_END) === false) { throw new Ex\CannotPerformOperationException('Cannot seek to beginning of MAC within input file'); } // Grab our last position of ciphertext before we read the MAC $cipher_end = \ftell($inputHandle); if ($cipher_end === false) { throw new Ex\CannotPerformOperationException('Cannot read input file'); } --$cipher_end; // We need to subtract one // We keep our MAC stored in this variable $stored_mac = self::readBytes($inputHandle, $config->macByteSize()); /** * We begin recalculating the HMAC for the entire file... */ $hmac = \hash_init($config->hashFunctionName(), HASH_HMAC, $akey); if ($hmac === false) { throw new Ex\CannotPerformOperationException('Cannot initialize a hash context'); } /** * Reset file pointer to the beginning of the file after the header */ if (\fseek($inputHandle, Core::HEADER_VERSION_SIZE, SEEK_SET) === false) { throw new Ex\CannotPerformOperationException('Cannot read seek within input file'); } /** * Set it to the first non-salt and non-IV byte */ if (\fseek($inputHandle, $config->saltByteSize() + $ivsize, SEEK_CUR) === false) { throw new Ex\CannotPerformOperationException('Cannot read seek input file to beginning of ciphertext'); } /** * 2. Let's recalculate the MAC */ /** * Let's initialize our $hmac hasher with our Salt and IV */ \hash_update($hmac, $header); \hash_update($hmac, $file_salt); \hash_update($hmac, $iv); $hmac2 = \hash_copy($hmac); $break = false; while (!$break) { /** * First, grab the current position */ $pos = \ftell($inputHandle); if ($pos === false) { throw new Ex\CannotPerformOperationException('Could not get current position in input file during decryption'); } /** * Would a full DBUFFER read put it past the end of the * ciphertext? If so, only return a portion of the file. */ if ($pos + $config->bufferByteSize() >= $cipher_end) { $break = true; $read = self::readBytes($inputHandle, $cipher_end - $pos + 1); } else { $read = self::readBytes($inputHandle, $config->bufferByteSize()); } if ($read === false) { throw new Ex\CannotPerformOperationException('Could not read input file during decryption'); } /** * We're updating our HMAC and nothing else */ \hash_update($hmac, $read); /** * Store a MAC of each chunk */ $chunkMAC = \hash_copy($hmac); if ($chunkMAC === false) { throw new Ex\CannotPerformOperationException('Cannot duplicate a hash context'); } $macs[] = \hash_final($chunkMAC); } /** * We should now have enough data to generate an identical HMAC */ $finalHMAC = \hash_final($hmac, true); /** * 3. Did we match? */ if (!Core::hashEquals($finalHMAC, $stored_mac)) { throw new Ex\InvalidCiphertextException('Message Authentication failure; tampering detected.'); } /** * 4. Okay, let's begin decrypting */ /** * Return file pointer to the first non-header, non-IV byte in the file */ if (\fseek($inputHandle, $config->saltByteSize() + $ivsize + Core::HEADER_VERSION_SIZE, SEEK_SET) === false) { throw new Ex\CannotPerformOperationException('Could not move the input file pointer during decryption'); } /** * Should we break the writing? */ $breakW = false; /** * This loop writes plaintext to the destination file: */ while (!$breakW) { /** * Get the current position */ $pos = \ftell($inputHandle); if ($pos === false) { throw new Ex\CannotPerformOperationException('Could not get current position in input file during decryption'); } /** * Would a full BUFFER read put it past the end of the * ciphertext? If so, only return a portion of the file. */ if ($pos + $config->bufferByteSize() >= $cipher_end) { $breakW = true; $read = self::readBytes($inputHandle, $cipher_end - $pos + 1); } else { $read = self::readBytes($inputHandle, $config->bufferByteSize()); } /** * Recalculate the MAC, compare with the one stored in the $macs * array to ensure attackers couldn't tamper with the file * after MAC verification */ \hash_update($hmac2, $read); $calcMAC = \hash_copy($hmac2); if ($calcMAC === false) { throw new Ex\CannotPerformOperationException('Cannot duplicate a hash context'); } $calc = \hash_final($calcMAC); if (empty($macs)) { throw new Ex\InvalidCiphertextException('File was modified after MAC verification'); } elseif (!Core::hashEquals(\array_shift($macs), $calc)) { throw new Ex\InvalidCiphertextException('File was modified after MAC verification'); } $thisIv = Core::incrementCounter($thisIv, $inc, $config); /** * Perform the AES decryption. Decrypts the message. */ $decrypted = \openssl_decrypt($read, $config->cipherMethod(), $ekey, OPENSSL_RAW_DATA, $thisIv); /** * Test for decryption faulure */ if ($decrypted === false) { throw new Ex\CannotPerformOperationException('OpenSSL decryption error'); } /** * Write the plaintext out to the output file */ self::writeBytes($outputHandle, $decrypted, Core::ourStrlen($decrypted)); } return true; }
public function testShouldRecreate() { $key = Key::createNewRandomKey(); $hash = $this->password->create('totally-insecure-but-lengthy-password'); $this->assertNotSame($hash, $this->password->shouldRecreate($hash, $key)); }
/** * @return \Defuse\Crypto\Key */ private function createKey($hash) { return Key::CreateKeyBasedOnPassword($hash, $this->saltKey); }
public function getKey($rawKey) { // If this is already a \Defuse\Crypto\Key object, just return it if ($rawKey instanceof Key) { return $rawKey; } if ($rawKey === null && defined('ENCRYPT_AT_REST_KEY')) { // Retrieve key from _ss_env, if set $rawKey = ENCRYPT_AT_REST_KEY; } if ($rawKey === null) { throw new \InvalidArgumentException('Can\'t encrypt without a key. Define ENCRYPT_AT_REST_KEY, or pass the $key argument.'); } $key = Key::LoadFromAsciiSafeString($rawKey); return $key; }
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; }
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); }
public function testStartMethodGeneratesFingerprint() { $session = $this->session; $oldFingerprint = $session->getFingerprint(); $session->addFingerprintGenerator(new UserAgentGenerator(Key::createNewRandomKey(), 'test')); $session->start(); $this->assertSame('', $oldFingerprint); $this->assertEquals(40, strlen($session->getFingerprint())); $this->assertNotEquals($oldFingerprint, $session->getFingerprint()); }