/** * Encrypt a message using the Halite encryption protocol * * @param string $plaintext * @param Key $secretKey * @param boolean $raw Don't hex encode the output? * @return string */ public static function encrypt($plaintext, Contract\CryptoKeyInterface $secretKey, $raw = false) { if ($secretKey->isAsymmetricKey()) { throw new CryptoAlert\InvalidKey('Expected a symmetric key, not an asymmetric key'); } if (!$secretKey->isEncryptionKey()) { throw new CryptoAlert\InvalidKey('Encryption key expected'); } $nonce = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_NONCEBYTES); $salt = \Sodium\randombytes_buf(Config::HKDF_SALT_LEN); list($eKey, $aKey) = self::splitKeys($secretKey, $salt); $xored = \Sodium\crypto_stream_xor($plaintext, $nonce, $eKey); $auth = self::calculateMAC(Config::HALITE_VERSION . $salt . $nonce . $xored, $aKey); \Sodium\memzero($eKey); \Sodium\memzero($aKey); if (!$raw) { return \Sodium\bin2hex(Config::HALITE_VERSION . $salt . $nonce . $xored . $auth); } return Config::HALITE_VERSION . $salt . $nonce . $xored . $auth; }