6 #include "mbedtls/pk.h"
14 mbedtls_rsa_init(&
m_Rsa);
24 mbedtls_rsa_init(&
m_Rsa);
35 mbedtls_rsa_free(&
m_Rsa);
47 LOG(
"RSA key generation failed: -0x%x", -res);
63 cPubKey(mbedtls_rsa_context * a_Rsa) :
66 mbedtls_pk_init(&m_Key);
67 if (mbedtls_pk_setup(&m_Key, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) != 0)
69 ASSERT(!
"Cannot init PrivKey context");
72 if (mbedtls_rsa_copy(mbedtls_pk_rsa(m_Key), a_Rsa) != 0)
74 ASSERT(!
"Cannot copy PrivKey to PK context");
84 mbedtls_pk_free(&m_Key);
88 operator mbedtls_pk_context * (void) {
return &m_Key; }
92 mbedtls_pk_context m_Key;
95 unsigned char buf[3000];
96 int res = mbedtls_pk_write_pubkey_der(PkCtx, buf,
sizeof(buf));
101 return {
reinterpret_cast<const std::byte *
>(buf +
sizeof(buf) - res),
static_cast<size_t>(res) };
110 const auto KeyLength = mbedtls_rsa_get_len(&
m_Rsa);
111 if (a_EncryptedData.size() < KeyLength)
113 LOGD(
"%s: Invalid a_EncryptedLength: got %zu, exp at least %zu", __FUNCTION__, a_EncryptedData.size(), KeyLength);
114 ASSERT(!
"Invalid a_DecryptedMaxLength!");
117 if (a_DecryptedMaxLength < KeyLength)
119 LOGD(
"%s: Invalid a_DecryptedMaxLength: got %zu, exp at least %zu", __FUNCTION__, a_DecryptedMaxLength, KeyLength);
120 ASSERT(!
"Invalid a_DecryptedMaxLength!");
123 size_t DecryptedLength;
124 int res = mbedtls_rsa_pkcs1_decrypt(
126 reinterpret_cast<const unsigned char *
>(a_EncryptedData.data()), a_DecryptedData, a_DecryptedMaxLength
132 return static_cast<int>(DecryptedLength);
std::basic_string_view< std::byte > ContiguousByteBufferView
std::basic_string< std::byte > ContiguousByteBuffer
void LOG(std::string_view a_Format, const Args &... args)
mbedtls_ctr_drbg_context * GetInternal(void)
Returns the internal context ptr.
int Initialize(const void *a_Custom, size_t a_CustomSize)
Initializes the context.
Encapsulates an RSA private key used in PKI cryptography.
cRsaPrivateKey(void)
Creates a new empty object, the key is not assigned.
mbedtls_rsa_context m_Rsa
The mbedTLS key context.
cCtrDrbgContext m_CtrDrbg
The random generator used for generating the key and encryption / decryption.
int Decrypt(ContiguousByteBufferView a_EncryptedData, Byte *a_DecryptedData, size_t a_DecryptedMaxLength)
Decrypts the data using RSAES-PKCS#1 algorithm.
ContiguousByteBuffer GetPubKeyDER(void)
Returns the public key part encoded in ASN1 DER encoding.
bool Generate(unsigned a_KeySizeBits=1024)
Generates a new key within this object, with the specified size in bits.