CryptoAlgorithmRSAES_PKCS1_v1_5GCrypt.cpp [plain text]
#include "config.h"
#include "CryptoAlgorithmRSAES_PKCS1_v1_5.h"
#if ENABLE(SUBTLE_CRYPTO)
#include "CryptoKeyRSA.h"
#include "GCryptUtilities.h"
namespace WebCore {
static std::optional<Vector<uint8_t>> gcryptEncrypt(gcry_sexp_t keySexp, const Vector<uint8_t>& plainText, size_t keySizeInBytes)
{
PAL::GCrypt::Handle<gcry_sexp_t> dataSexp;
gcry_error_t error = gcry_sexp_build(&dataSexp, nullptr, "(data(flags pkcs1)(value %b))",
plainText.size(), plainText.data());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
PAL::GCrypt::Handle<gcry_sexp_t> cipherSexp;
error = gcry_pk_encrypt(&cipherSexp, dataSexp, keySexp);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
PAL::GCrypt::Handle<gcry_sexp_t> aSexp(gcry_sexp_find_token(cipherSexp, "a", 0));
if (!aSexp)
return std::nullopt;
return mpiZeroPrefixedData(aSexp, keySizeInBytes);
}
static std::optional<Vector<uint8_t>> gcryptDecrypt(gcry_sexp_t keySexp, const Vector<uint8_t>& cipherText)
{
PAL::GCrypt::Handle<gcry_sexp_t> encValSexp;
gcry_error_t error = gcry_sexp_build(&encValSexp, nullptr, "(enc-val(flags pkcs1)(rsa(a %b)))",
cipherText.size(), cipherText.data());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
PAL::GCrypt::Handle<gcry_sexp_t> plainSexp;
error = gcry_pk_decrypt(&plainSexp, encValSexp, keySexp);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
PAL::GCrypt::Handle<gcry_sexp_t> valueSexp(gcry_sexp_find_token(plainSexp, "value", 0));
if (!valueSexp)
return std::nullopt;
return mpiData(valueSexp);
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmRSAES_PKCS1_v1_5::platformEncrypt(const CryptoKeyRSA& key, const Vector<uint8_t>& plainText)
{
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!(key.keySizeInBits() % 8));
auto output = gcryptEncrypt(key.platformKey(), plainText, key.keySizeInBits() / 8);
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmRSAES_PKCS1_v1_5::platformDecrypt(const CryptoKeyRSA& key, const Vector<uint8_t>& cipherText)
{
auto output = gcryptDecrypt(key.platformKey(), cipherText);
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
}
#endif // ENABLE(SUBTLE_CRYPTO)