/** * Encrypt $plaintext with $secret, then date and sign the message. * * @param string $secret * @param string $plaintext * @return array * Array(string $body, string $signature). * Note that $body begins with an unencrypted envelope (ttl, iv). * @throws InvalidMessageException */ public static function encryptThenSign($secret, $plaintext) { $iv = crypt_random_string(Constants::AES_BYTES); $keys = AesHelper::deriveAesKeys($secret); $cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC); $cipher->setKeyLength(Constants::AES_BYTES); $cipher->setKey($keys['enc']); $cipher->setIV($iv); // JSON string; this will be signed but not encrypted $jsonEnvelope = json_encode(array('ttl' => Time::getTime() + Constants::REQUEST_TTL, 'iv' => BinHex::bin2hex($iv))); // JSON string; this will be signed and encrypted $jsonEncrypted = $cipher->encrypt($plaintext); $body = $jsonEnvelope . Constants::PROTOCOL_DELIM . $jsonEncrypted; $signature = hash_hmac('sha256', $body, $keys['auth']); return array($body, $signature); }