/**
  * @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__);
     }
 }
Пример #2
0
 /**
  * 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);
     }
 }
Пример #3
0
 /**
  * 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);
 }
Пример #4
0
 private function decrypt($resource)
 {
     if ($resource !== null) {
         $msg = stream_get_contents($resource);
         return Crypto::decrypt($msg, $this->key, true);
     }
     return null;
 }
Пример #5
0
 /**
  * {@inheritdoc}
  */
 public function get()
 {
     if (!$this->isHit()) {
         return;
     }
     $item = json_decode(Crypto::decrypt($this->cacheItem->get(), $this->key), true);
     return $this->transform($item);
 }
Пример #6
0
 public function write($data)
 {
     $cipher = Crypto::Encrypt(json_encode($data), $this->key);
     $cookie_domain = '';
     if (!empty(\Config\Base::$auth['cookie_domain'])) {
         $cookie_domain = \Config\Base::$auth['cookie_domain'];
     }
     setcookie('auth', $cipher, time() + $this->timeout, '/', $cookie_domain);
 }
Пример #7
0
 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;
 }
Пример #8
0
 /**
  * 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);
 }
Пример #9
0
 /**
  * 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::legacyDecrypt($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);
     }
 }
Пример #10
0
 /**
  * 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;
 }
Пример #11
0
 /**
  * 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);
     }
 }
Пример #12
0
 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 "";
     }
 }
Пример #13
0
 /**
  * 
  * 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);
 }
Пример #14
0
 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.");
     }
 }
Пример #15
0
 /**
  * @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));
 }
Пример #16
0
 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;
 }
Пример #17
0
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $errors = true;
    response(VALIDATION_DATE_INVALID, $errors);
}
if (strtotime($expiration_date) > strtotime("today +30 days")) {
    $errors = true;
    response(VALIDATION_DATE_INVALID, $errors);
}
// If all of the above validation checks pass, continue on
if (!$errors) {
    // 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::encryptWithPassword($data, $password);
    } catch (Ex\EnvironmentIsBrokenException $ex) {
        response(ENCRYPTION_UNSAFE, true);
    }
    // Store the encrypted data
    $array = array('secret' => bin2hex($data_encrypted), 'expiration_date' => strtotime($expiration_date . ' +1 day'));
    $item = $collection->item();
    if ($item->post($array)) {
        $item->event('log')->post(['action' => 'created']);
        $id = $item->getKey();
    } else {
        response($item->getStatus(), true);
    }
    // Send email to recipient
    if (!empty($email_recipient)) {
        // Email body
Пример #18
0
 /**
  * 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');
     }
 }
Пример #19
0
 /**
  * @param $passwordHash
  * @param $token
  * @return array
  */
 public static function tokenDecrypt($passwordHash, $token)
 {
     $decrypted = Crypto::decryptWithPassword($token, $passwordHash);
     return explode("|", $decrypted);
 }
Пример #20
0
 /**
  * For migrating from an older version of the library
  *
  * @param string $password
  * @param string $ciphertext
  * @param string $oldKey
  * @param Key $newKey
  * @return string
  * @throws \Exception
  */
 public static function upgradeFromVersion1(string $password, string $ciphertext, string $oldKey, Key $newKey) : string
 {
     if (!self::decryptAndVerifyLegacy($password, $ciphertext, $oldKey)) {
         throw new \Exception('The correct password is necessary for legacy migration.');
     }
     $plaintext = Crypto::legacyDecrypt($ciphertext, $oldKey);
     return self::hashAndEncrypt($plaintext, $newKey);
 }
Пример #21
0
<?php

// Set the encoding to something more "challenging."
$ret = mb_internal_encoding('UTF-8');
if ($ret === FALSE) {
    echo "Couldn't set encoding.";
    exit(1);
}
// Dump out the settings / encoding for future reference.
$val = ini_get("mbstring.func_overload");
echo "Settings: \n";
echo "    func_overload: " . $val . "\n";
echo "    mb_internal_encoding(): " . mb_internal_encoding() . "\n";
// Perform the tests.
require_once \dirname(__DIR__) . '/autoload.php';
try {
    \Defuse\Crypto\Crypto::RuntimeTest();
    echo "TEST PASSED!\n";
    exit(0);
} catch (\Defuse\Crypto\Exception\CryptoTestFailed $ex) {
    echo "TEST FAILED!\n";
    var_dump($ex);
    exit(1);
} catch (\Defuse\Crypto\Exception\CannotPerformOperation $ex) {
    echo "TEST FAILED\n";
    var_dump($ex);
    exit(1);
}
Пример #22
0
<?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);
Пример #23
0
if ($fail_total >= 3) {
    $item->event('log')->post(['action' => 'disabled']);
    $errors = true;
    response(VALIDATION_TOO_MANY_ATTEMPTS, $errors);
}
// If all of the above validation checks pass, continue on
if (!$errors) {
    $salt = Crypto::hexToBin($item->salt);
    $data_encrypted = Crypto::hexToBin($item->secret);
    // Create decryption key
    $length = 16;
    $iterations = PASSWORD_ITERATIONS;
    $key = hash_pbkdf2("sha256", $password, $salt, $iterations, $length);
    // Decrypt data, reference: https://github.com/defuse/php-encryption/
    try {
        $data_decrypted = Crypto::Decrypt($data_encrypted, $key);
    } catch (Ex\InvalidCiphertextException $ex) {
        // VERY IMPORTANT
        // Log event
        $item->event('log')->post(['action' => 'failed']);
        response(DECRYPTION_PASSWORD_WRONG, true);
    } catch (Ex\CryptoTestFailedException $ex) {
        response(ENCRYPTION_UNSAFE, true);
    } catch (Ex\CannotPerformOperationException $ex) {
        response(DECRYPTION_UNSAFE, true);
    }
    // Delete message
    $item->delete();
    // Log event
    if ($item->delete()) {
        $item->event('log')->post(['action' => 'deleted']);
Пример #24
0
 /**
  * {@inheritdoc}
  */
 public function decrypt(string $ciphertext) : string
 {
     return Crypto::decrypt($ciphertext, $this->key);
 }
 /**
  * @param mixed $value
  * @return string
  */
 public function reverseTransform($value)
 {
     return Crypto::decrypt($value, $this->key, $this->getBinary());
 }
Пример #26
0
<?php

require_once \dirname(__DIR__) . '/autoload.php';
use Defuse\Crypto\Crypto;
$status = 0;
for ($i = 0; $i < 100; ++$i) {
    $random = \openssl_random_pseudo_bytes(32);
    $encode_a = Crypto::binToHex($random);
    $encode_b = \bin2hex($random);
    if ($encode_a !== $encode_b) {
        $status = 1;
        \var_dump([$encode_a, $encode_b]);
    }
    // echo "\t", $encode_a, "\t", $encode_b, "\n";
    $decode_a = Crypto::hexToBin($encode_b);
    $decode_b = \hex2bin($encode_a);
    if ($decode_a !== $decode_b) {
        $status = 1;
        \var_dump([\base64_encode($decode_a), \base64_decode($decode_b)]);
    }
}
if ($status < 0) {
    echo 'Encoded successfully!', "\n";
}
exit($status);
\var_dump(Crypto::binToHex("ABJA"));
\var_dump(Crypto::hexToBin('41424a41'));
 /**
  * @param string $ciphertext
  * @param null|Key $key
  * @return string
  * @throws CannotPerformOperationException
  * @throws InvalidCiphertextException
  */
 public function decrypt($ciphertext, $key = null)
 {
     $key = $this->getKey($key);
     return Crypto::Decrypt($ciphertext, $key);
 }
Пример #28
0
    $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');
}
Пример #29
0
 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);
 }
Пример #30
0
 /**
  * Encrypt something
  *
  * @param string $cleartext
  * @return string hexadecimal representation of crypted string
  */
 public function encrypt($cleartext)
 {
     return Crypto::binToHex(Crypto::encrypt($cleartext, $this->getSecretKey()));
 }