CryptoAlgorithmAES_KWGCrypt.cpp [plain text]
#include "config.h"
#include "CryptoAlgorithmAES_KW.h"
#if ENABLE(SUBTLE_CRYPTO)
#include "CryptoKeyAES.h"
#include <pal/crypto/gcrypt/Handle.h>
#include <pal/crypto/gcrypt/Utilities.h>
namespace WebCore {
static std::optional<Vector<uint8_t>> gcryptWrapKey(const Vector<uint8_t>& key, const Vector<uint8_t>& data)
{
auto algorithm = PAL::GCrypt::aesAlgorithmForKeySize(key.size() * 8);
if (!algorithm)
return std::nullopt;
PAL::GCrypt::Handle<gcry_cipher_hd_t> handle;
gcry_error_t error = gcry_cipher_open(&handle, *algorithm, GCRY_CIPHER_MODE_AESWRAP, 0);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
error = gcry_cipher_setkey(handle, key.data(), key.size());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
error = gcry_cipher_final(handle);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
Vector<uint8_t> output(data.size() + 8);
error = gcry_cipher_encrypt(handle, output.data(), output.size(), data.data(), data.size());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
return output;
}
static std::optional<Vector<uint8_t>> gcryptUnwrapKey(const Vector<uint8_t>& key, const Vector<uint8_t>& data)
{
auto algorithm = PAL::GCrypt::aesAlgorithmForKeySize(key.size() * 8);
if (!algorithm)
return std::nullopt;
PAL::GCrypt::Handle<gcry_cipher_hd_t> handle;
gcry_error_t error = gcry_cipher_open(&handle, *algorithm, GCRY_CIPHER_MODE_AESWRAP, 0);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
error = gcry_cipher_setkey(handle, key.data(), key.size());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
error = gcry_cipher_final(handle);
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
Vector<uint8_t> output(data.size() - 8);
error = gcry_cipher_decrypt(handle, output.data(), output.size(), data.data(), data.size());
if (error != GPG_ERR_NO_ERROR) {
PAL::GCrypt::logError(error);
return std::nullopt;
}
return output;
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_KW::platformWrapKey(const CryptoKeyAES& key, const Vector<uint8_t>& data)
{
auto output = gcryptWrapKey(key.key(), data);
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_KW::platformUnwrapKey(const CryptoKeyAES& key, const Vector<uint8_t>& data)
{
auto output = gcryptUnwrapKey(key.key(), data);
if (!output)
return Exception { OperationError };
return WTFMove(*output);
}
}
#endif // ENABLE(SUBTLE_CRYPTO)