ParagonIE\Halite\Symmetric\Crypto::encrypt PHP Method

encrypt() public static method

(Encrypt then MAC -- xsalsa20 then keyed-Blake2b) You don't need to worry about chosen-ciphertext attacks.
public static encrypt ( HiddenString $plaintext, EncryptionKey $secretKey, mixed $encoding = Halite::ENCODE_BASE64URLSAFE ) : string
$plaintext HiddenString
$secretKey EncryptionKey
$encoding mixed
return string
    public static function encrypt(HiddenString $plaintext, EncryptionKey $secretKey, $encoding = Halite::ENCODE_BASE64URLSAFE) : string
    {
        $config = SymmetricConfig::getConfig(Halite::HALITE_VERSION, 'encrypt');
        // Generate a nonce and HKDF salt:
        $nonce = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_NONCEBYTES);
        $salt = \Sodium\randombytes_buf($config->HKDF_SALT_LEN);
        /* Split our key into two keys: One for encryption, the other for
                   authentication. By using separate keys, we can reasonably dismiss
                   likely cross-protocol attacks.
        
                   This uses salted HKDF to split the keys, which is why we need the
                   salt in the first place. */
        list($encKey, $authKey) = self::splitKeys($secretKey, $salt, $config);
        // Encrypt our message with the encryption key:
        $encrypted = \Sodium\crypto_stream_xor($plaintext->getString(), $nonce, $encKey);
        \Sodium\memzero($encKey);
        // Calculate an authentication tag:
        $auth = self::calculateMAC(Halite::HALITE_VERSION . $salt . $nonce . $encrypted, $authKey, $config);
        \Sodium\memzero($authKey);
        $message = Halite::HALITE_VERSION . $salt . $nonce . $encrypted . $auth;
        // Wipe every superfluous piece of data from memory
        \Sodium\memzero($nonce);
        \Sodium\memzero($salt);
        \Sodium\memzero($encrypted);
        \Sodium\memzero($auth);
        $encoder = Halite::chooseEncoder($encoding);
        if ($encoder) {
            return $encoder($message);
        }
        return $message;
    }

Usage Example

Beispiel #1
0
 /**
  * Hash then encrypt a password
  * 
  * @param string $password   - The user's password
  * @param Key $secret_key - The master key for all passwords
  * @return string
  */
 public static function hash($password, \ParagonIE\Halite\Contract\CryptoKeyInterface $secret_key)
 {
     // First, let's calculate the hash
     $hashed = \Sodium\crypto_pwhash_scryptsalsa208sha256_str($password, \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE, \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE);
     // Now let's encrypt the result
     return Symmetric::encrypt($hashed, $secret_key);
 }
All Usage Examples Of ParagonIE\Halite\Symmetric\Crypto::encrypt