public static function decrypt($ciphertext, $key) { // Extract MAC and IV from the remainder of the ciphertext $mac = substr($ciphertext, 0, self::ENCRYPTION_MAC_SIZE); $iv = substr($ciphertext, self::ENCRYPTION_MAC_SIZE, self::ENCRYPTION_BLOCK_SIZE); $ciphertext = substr($ciphertext, self::ENCRYPTION_MAC_SIZE + self::ENCRYPTION_BLOCK_SIZE); // Validate MAC $mac_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_MAC_INFO); $mac_compare = hash_hmac(self::ENCRYPTION_MAC_ALGO, $iv . $ciphertext, $mac_key, true); if (!Password::strcmpConstantTime($mac, $mac_compare)) { return false; } // Generate subkey for encryption $enc_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_KEY_INFO); // Decrypt the ciphertext $mcrypt_method = str_replace('aes', 'rijndael', self::ENCRYPTION_ALGO); $plaintext = @mcrypt_decrypt($mcrypt_method, $enc_key, $ciphertext, self::ENCRYPTION_MODE, $iv); if ($plaintext === false) { return false; } $plaintext = self::_stripPKCS7Padding($plaintext, self::ENCRYPTION_BLOCK_SIZE); if ($plaintext === false) { return false; } // Return the plaintext return $plaintext; }
/** * @brief Verify a digital signature * @param string $signature The signature to verify * @param string $plaintext The string to verify * @param string $key Optional key. If empty, default key will be used. * @return bool */ public function verifySignature($signature, $plaintext, $key = null) { if ($key === null || $key === '') { $key = $this->_getSessionKey(); } // Verify the signature using HMAC $oPassword = new Password(); $compare = bin2hex(self::_defuseCompatibleHKDF($plaintext, $key)); return $oPassword->strcmpConstantTime($signature, $compare); }