diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txt index 32cf50e427ff..8bd6619b57b4 100644 --- a/Libraries/LibCrypto/CMakeLists.txt +++ b/Libraries/LibCrypto/CMakeLists.txt @@ -1,6 +1,7 @@ add_cxx_compile_options(-Wvla) set(SOURCES + OpenSSL.cpp AEAD/ChaCha20Poly1305.cpp ASN1/ASN1.cpp ASN1/DER.cpp diff --git a/Libraries/LibCrypto/OpenSSL.cpp b/Libraries/LibCrypto/OpenSSL.cpp new file mode 100644 index 000000000000..ec01cc83670d --- /dev/null +++ b/Libraries/LibCrypto/OpenSSL.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025, Altomani Gianluca + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include +#include +#include + +namespace Crypto { + +ErrorOr unsigned_big_integer_to_openssl_bignum(UnsignedBigInteger const& integer) +{ + auto bn = TRY(OpenSSL_BN::create()); + auto buf = TRY(ByteBuffer::create_uninitialized(integer.byte_length())); + auto integer_size = integer.export_data(buf.bytes()); + OPENSSL_TRY_PTR(BN_bin2bn(buf.bytes().data(), integer_size, bn.ptr())); + return bn; +} + +ErrorOr openssl_bignum_to_unsigned_big_integer(OpenSSL_BN const& bn) +{ + auto size = BN_num_bytes(bn.ptr()); + auto buf = TRY(ByteBuffer::create_uninitialized(size)); + BN_bn2bin(bn.ptr(), buf.bytes().data()); + return UnsignedBigInteger::import_data(buf.bytes().data(), size); +} + +} diff --git a/Libraries/LibCrypto/OpenSSL.h b/Libraries/LibCrypto/OpenSSL.h index 196f38c052d4..bcb49b1886ae 100644 --- a/Libraries/LibCrypto/OpenSSL.h +++ b/Libraries/LibCrypto/OpenSSL.h @@ -8,7 +8,9 @@ #include #include +#include +#include #include #include @@ -82,6 +84,16 @@ private: \ \ openssl_type* m_ptr { nullptr }; +class OpenSSL_BN { + OPENSSL_WRAPPER_CLASS(OpenSSL_BN, BIGNUM, BN); + +public: + static ErrorOr create() + { + return OpenSSL_BN(OPENSSL_TRY_PTR(BN_new())); + } +}; + class OpenSSL_PKEY { OPENSSL_WRAPPER_CLASS(OpenSSL_PKEY, EVP_PKEY, EVP_PKEY); @@ -104,4 +116,7 @@ class OpenSSL_MD_CTX { #undef OPENSSL_WRAPPER_CLASS +ErrorOr unsigned_big_integer_to_openssl_bignum(UnsignedBigInteger const& integer); +ErrorOr openssl_bignum_to_unsigned_big_integer(OpenSSL_BN const& bn); + }