Skip to content

Commit

Permalink
LibCrypto: Add methods to convert OpenSSL BN <-> UnsignedBigInteger
Browse files Browse the repository at this point in the history
These methods allow to convert between OpenSSL big numbers and ours.
  • Loading branch information
devgianlu committed Jan 11, 2025
1 parent d7c6952 commit a36747a
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions Libraries/LibCrypto/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
add_cxx_compile_options(-Wvla)

set(SOURCES
OpenSSL.cpp
AEAD/ChaCha20Poly1305.cpp
ASN1/ASN1.cpp
ASN1/DER.cpp
Expand Down
30 changes: 30 additions & 0 deletions Libraries/LibCrypto/OpenSSL.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2025, Altomani Gianluca <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/

#include <AK/ByteBuffer.h>
#include <LibCrypto/OpenSSL.h>
#include <openssl/evp.h>

namespace Crypto {

ErrorOr<OpenSSL_BN> 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<UnsignedBigInteger> 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);
}

}
15 changes: 15 additions & 0 deletions Libraries/LibCrypto/OpenSSL.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@

#include <AK/Error.h>
#include <AK/Format.h>
#include <LibCrypto/BigInt/UnsignedBigInteger.h>

#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/evp.h>

Expand Down Expand Up @@ -82,6 +84,16 @@ private: \
\
openssl_type* m_ptr { nullptr };

class OpenSSL_BN {
OPENSSL_WRAPPER_CLASS(OpenSSL_BN, BIGNUM, BN);

public:
static ErrorOr<OpenSSL_BN> create()
{
return OpenSSL_BN(OPENSSL_TRY_PTR(BN_new()));
}
};

class OpenSSL_PKEY {
OPENSSL_WRAPPER_CLASS(OpenSSL_PKEY, EVP_PKEY, EVP_PKEY);

Expand All @@ -104,4 +116,7 @@ class OpenSSL_MD_CTX {

#undef OPENSSL_WRAPPER_CLASS

ErrorOr<OpenSSL_BN> unsigned_big_integer_to_openssl_bignum(UnsignedBigInteger const& integer);
ErrorOr<UnsignedBigInteger> openssl_bignum_to_unsigned_big_integer(OpenSSL_BN const& bn);

}

0 comments on commit a36747a

Please sign in to comment.