summaryrefslogtreecommitdiffstats
path: root/modules/mbedtls
diff options
context:
space:
mode:
authorScorpionInc <d2dejohn@gmail.com>2023-04-05 17:45:55 -0400
committerScorpionInc <19487319+ScorpionInc@users.noreply.github.com>2023-05-09 19:02:33 -0400
commita5b867391e5228b491befadca101d4918dd0820c (patch)
tree93c1441b332c62f1ed5a8424c8262e4b1a9ae104 /modules/mbedtls
parentfba9416fe0046c32b19d47523eab95e9e6036093 (diff)
downloadredot-engine-a5b867391e5228b491befadca101d4918dd0820c.tar.gz
Exposes String functions for X509Certificates
Exposes String functions for X509Certificates via two function calls: save_to_string() and load_from_string(str).
Diffstat (limited to 'modules/mbedtls')
-rw-r--r--modules/mbedtls/crypto_mbedtls.cpp30
-rw-r--r--modules/mbedtls/crypto_mbedtls.h2
2 files changed, 32 insertions, 0 deletions
diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp
index 5b52af3068..6ae36daffe 100644
--- a/modules/mbedtls/crypto_mbedtls.cpp
+++ b/modules/mbedtls/crypto_mbedtls.cpp
@@ -42,6 +42,7 @@
#endif
#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
#define PEM_END_CRT "-----END CERTIFICATE-----\n"
+#define PEM_MIN_SIZE 54
#include <mbedtls/debug.h>
#include <mbedtls/md.h>
@@ -181,6 +182,35 @@ Error X509CertificateMbedTLS::save(String p_path) {
return OK;
}
+String X509CertificateMbedTLS::save_to_string() {
+ String buffer;
+ mbedtls_x509_crt *crt = &cert;
+ while (crt) {
+ unsigned char w[4096];
+ size_t wrote = 0;
+ int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
+ ERR_FAIL_COND_V_MSG(ret != 0 || wrote == 0, String(), "Error saving the certificate.");
+
+ buffer += String((char *)w, wrote);
+ crt = crt->next;
+ }
+ if (buffer.length() <= PEM_MIN_SIZE) {
+ // When the returned value of variable 'buffer' would consist of no Base-64 data, return an empty String instead.
+ return String();
+ }
+ return buffer;
+}
+
+Error X509CertificateMbedTLS::load_from_string(const String &p_string_key) {
+ ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use");
+ CharString cs = p_string_key.utf8();
+
+ int ret = mbedtls_x509_crt_parse(&cert, (const unsigned char *)cs.get_data(), cs.size());
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret));
+
+ return OK;
+}
+
bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {
switch (p_md_type) {
case MBEDTLS_MD_SHA1:
diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h
index 7422ebad3e..0168e1f663 100644
--- a/modules/mbedtls/crypto_mbedtls.h
+++ b/modules/mbedtls/crypto_mbedtls.h
@@ -85,6 +85,8 @@ public:
virtual Error load(String p_path);
virtual Error load_from_memory(const uint8_t *p_buffer, int p_len);
virtual Error save(String p_path);
+ virtual String save_to_string();
+ virtual Error load_from_string(const String &p_string_key);
X509CertificateMbedTLS() {
mbedtls_x509_crt_init(&cert);