CryptoAlgorithmAES_CBCOpenSSL.cpp [plain text]
#include "config.h"
#include "CryptoAlgorithmAES_CBC.h"
#if ENABLE(WEB_CRYPTO)
#include "CryptoAlgorithmAesCbcCfbParams.h"
#include "CryptoKeyAES.h"
#include "OpenSSLCryptoUniquePtr.h"
#include <openssl/evp.h>
namespace WebCore {
static const EVP_CIPHER* aesAlgorithm(size_t keySize)
{
if (keySize * 8 == 128)
return EVP_aes_128_cbc();
if (keySize * 8 == 192)
return EVP_aes_192_cbc();
if (keySize * 8 == 256)
return EVP_aes_256_cbc();
return nullptr;
}
static Optional<Vector<uint8_t>> cryptEncrypt(const Vector<uint8_t>& key, const Vector<uint8_t>& iv, Vector<uint8_t>&& plainText)
{
const EVP_CIPHER* algorithm = aesAlgorithm(key.size());
if (!algorithm)
return WTF::nullopt;
EvpCipherCtxPtr ctx;
int len;
if (!(ctx = EvpCipherCtxPtr(EVP_CIPHER_CTX_new())))
return WTF::nullopt;
size_t plainSize = plainText.size();
const size_t cipherTextLen = roundUpToMultipleOf(EVP_CIPHER_block_size(algorithm), plainSize + 1);
Vector<uint8_t> cipherText(cipherTextLen);
if (1 != EVP_EncryptInit_ex(ctx.get(), algorithm, nullptr, key.data(), iv.data()))
return WTF::nullopt;
if (1 != EVP_EncryptUpdate(ctx.get(), cipherText.data(), &len, plainText.data(), plainSize))
return WTF::nullopt;
if (1 != EVP_EncryptFinal_ex(ctx.get(), cipherText.data() + len, &len))
return WTF::nullopt;
return cipherText;
}
static Optional<Vector<uint8_t>> cryptDecrypt(const Vector<uint8_t>& key, const Vector<uint8_t>& iv, const Vector<uint8_t>& cipherText)
{
const EVP_CIPHER* algorithm = aesAlgorithm(key.size());
if (!algorithm)
return WTF::nullopt;
EvpCipherCtxPtr ctx;
size_t cipherSize = cipherText.size();
Vector<uint8_t> plainText(cipherSize);
int len;
int plainTextLen;
if (!(ctx = EvpCipherCtxPtr(EVP_CIPHER_CTX_new())))
return WTF::nullopt;
if (1 != EVP_DecryptInit_ex(ctx.get(), algorithm, nullptr, key.data(), iv.data()))
return WTF::nullopt;
if (1 != EVP_DecryptUpdate(ctx.get(), plainText.data(), &len, cipherText.data(), cipherSize))
return WTF::nullopt;
plainTextLen = len;
if (1 != EVP_DecryptFinal_ex(ctx.get(), plainText.data() + len, &len))
return WTF::nullopt;
plainTextLen += len;
plainText.shrink(plainTextLen);
return plainText;
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_CBC::platformEncrypt(const CryptoAlgorithmAesCbcCfbParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& plainText, Padding)
{
auto output = cryptEncrypt(key.key(), parameters.ivVector(), Vector<uint8_t>(plainText));
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_CBC::platformDecrypt(const CryptoAlgorithmAesCbcCfbParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& cipherText, Padding)
{
auto output = cryptDecrypt(key.key(), parameters.ivVector(), cipherText);
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
}
#endif // ENABLE(WEB_CRYPTO)