Path: blob/master/modules/mbedtls/crypto_mbedtls.cpp
10277 views
/**************************************************************************/1/* crypto_mbedtls.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "crypto_mbedtls.h"3132#include "core/io/certs_compressed.gen.h"33#include "core/io/compression.h"34#include "core/io/file_access.h"35#include "core/os/os.h"3637#include <mbedtls/debug.h>38#include <mbedtls/md.h>39#include <mbedtls/pem.h>4041#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"42#define PEM_END_CRT "-----END CERTIFICATE-----\n"43#define PEM_MIN_SIZE 544445CryptoKey *CryptoKeyMbedTLS::create(bool p_notify_postinitialize) {46return static_cast<CryptoKey *>(ClassDB::creator<CryptoKeyMbedTLS>(p_notify_postinitialize));47}4849Error CryptoKeyMbedTLS::load(const String &p_path, bool p_public_only) {50ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");5152PackedByteArray out;53Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);54ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'.");5556uint64_t flen = f->get_length();57out.resize(flen + 1);58f->get_buffer(out.ptrw(), flen);59out.write[flen] = 0; // string terminator6061int ret = 0;62if (p_public_only) {63ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size());64} else {65ret = _parse_key(out.ptr(), out.size());66}67// We MUST zeroize the memory for safety!68mbedtls_platform_zeroize(out.ptrw(), out.size());69ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");7071public_only = p_public_only;72return OK;73}7475Error CryptoKeyMbedTLS::save(const String &p_path, bool p_public_only) {76Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);77ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'.");7879unsigned char w[16000];80memset(w, 0, sizeof(w));8182int ret = 0;83if (p_public_only) {84ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));85} else {86ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));87}88if (ret != 0) {89mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written.90ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'.");91}9293size_t len = strlen((char *)w);94f->store_buffer(w, len);95mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer.96return OK;97}9899Error CryptoKeyMbedTLS::load_from_string(const String &p_string_key, bool p_public_only) {100int ret = 0;101const CharString string_key_utf8 = p_string_key.utf8();102if (p_public_only) {103ret = mbedtls_pk_parse_public_key(&pkey, (const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());104} else {105ret = _parse_key((const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());106}107ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");108109public_only = p_public_only;110return OK;111}112113String CryptoKeyMbedTLS::save_to_string(bool p_public_only) {114unsigned char w[16000];115memset(w, 0, sizeof(w));116117int ret = 0;118if (p_public_only) {119ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));120} else {121ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));122}123if (ret != 0) {124mbedtls_platform_zeroize(w, sizeof(w));125ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'.");126}127String s = String::utf8((char *)w);128return s;129}130131int CryptoKeyMbedTLS::_parse_key(const uint8_t *p_buf, int p_size) {132#if MBEDTLS_VERSION_MAJOR >= 3133mbedtls_entropy_context rng_entropy;134mbedtls_ctr_drbg_context rng_drbg;135136mbedtls_ctr_drbg_init(&rng_drbg);137mbedtls_entropy_init(&rng_entropy);138int ret = mbedtls_ctr_drbg_seed(&rng_drbg, mbedtls_entropy_func, &rng_entropy, nullptr, 0);139ERR_FAIL_COND_V_MSG(ret != 0, ret, vformat("mbedtls_ctr_drbg_seed returned -0x%x\n", (unsigned int)-ret));140141ret = mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0, mbedtls_ctr_drbg_random, &rng_drbg);142mbedtls_ctr_drbg_free(&rng_drbg);143mbedtls_entropy_free(&rng_entropy);144return ret;145#else146return mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0);147#endif148}149150X509Certificate *X509CertificateMbedTLS::create(bool p_notify_postinitialize) {151return static_cast<X509Certificate *>(ClassDB::creator<X509CertificateMbedTLS>(p_notify_postinitialize));152}153154Error X509CertificateMbedTLS::load(const String &p_path) {155ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");156157PackedByteArray out;158Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);159ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot open X509CertificateMbedTLS file '%s'.", p_path));160161uint64_t flen = f->get_length();162out.resize(flen + 1);163f->get_buffer(out.ptrw(), flen);164out.write[flen] = 0; // string terminator165166int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());167ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates from file '%s': %d.", p_path, ret));168if (ret > 0) { // Some certs parsed fine, don't error.169print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed from file '%s' (%d certificates skipped).", p_path, ret));170}171172return OK;173}174175Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {176ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");177178int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);179ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));180if (ret > 0) { // Some certs parsed fine, don't error.181print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));182}183return OK;184}185186Error X509CertificateMbedTLS::save(const String &p_path) {187Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);188ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot save X509CertificateMbedTLS file '%s'.", p_path));189190mbedtls_x509_crt *crt = &cert;191while (crt) {192unsigned char w[4096];193size_t wrote = 0;194int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);195if (ret != 0 || wrote == 0) {196ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'.");197}198199f->store_buffer(w, wrote - 1); // don't write the string terminator200crt = crt->next;201}202return OK;203}204205String X509CertificateMbedTLS::save_to_string() {206String buffer;207mbedtls_x509_crt *crt = &cert;208while (crt) {209unsigned char w[4096];210size_t wrote = 0;211int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);212ERR_FAIL_COND_V_MSG(ret != 0 || wrote == 0, String(), "Error saving the certificate.");213214// PEM is base64, aka ascii215buffer += String::ascii(Span((char *)w, wrote));216crt = crt->next;217}218if (buffer.length() <= PEM_MIN_SIZE) {219// When the returned value of variable 'buffer' would consist of no Base-64 data, return an empty String instead.220return String();221}222return buffer;223}224225Error X509CertificateMbedTLS::load_from_string(const String &p_string_key) {226ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");227CharString cs = p_string_key.utf8();228229int ret = mbedtls_x509_crt_parse(&cert, (const unsigned char *)cs.get_data(), cs.size());230ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));231if (ret > 0) { // Some certs parsed fine, don't error.232print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));233}234235return OK;236}237238bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {239switch (p_md_type) {240case MBEDTLS_MD_SHA1:241case MBEDTLS_MD_SHA256:242return true;243default:244return false;245}246}247248HMACContext *HMACContextMbedTLS::create(bool p_notify_postinitialize) {249return static_cast<HMACContext *>(ClassDB::creator<HMACContextMbedTLS>(p_notify_postinitialize));250}251252Error HMACContextMbedTLS::start(HashingContext::HashType p_hash_type, const PackedByteArray &p_key) {253ERR_FAIL_COND_V_MSG(ctx != nullptr, ERR_FILE_ALREADY_IN_USE, "HMACContext already started.");254255// HMAC keys can be any size.256ERR_FAIL_COND_V_MSG(p_key.is_empty(), ERR_INVALID_PARAMETER, "Key must not be empty.");257258hash_type = p_hash_type;259mbedtls_md_type_t ht = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, hash_len);260261bool allowed = HMACContextMbedTLS::is_md_type_allowed(ht);262ERR_FAIL_COND_V_MSG(!allowed, ERR_INVALID_PARAMETER, "Unsupported hash type.");263264ctx = memalloc(sizeof(mbedtls_md_context_t));265mbedtls_md_init((mbedtls_md_context_t *)ctx);266267mbedtls_md_setup((mbedtls_md_context_t *)ctx, mbedtls_md_info_from_type((mbedtls_md_type_t)ht), 1);268int ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, (const uint8_t *)p_key.ptr(), (size_t)p_key.size());269return ret ? FAILED : OK;270}271272Error HMACContextMbedTLS::update(const PackedByteArray &p_data) {273ERR_FAIL_NULL_V_MSG(ctx, ERR_INVALID_DATA, "Start must be called before update.");274275ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_PARAMETER, "Src must not be empty.");276277int ret = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, (const uint8_t *)p_data.ptr(), (size_t)p_data.size());278return ret ? FAILED : OK;279}280281PackedByteArray HMACContextMbedTLS::finish() {282ERR_FAIL_NULL_V_MSG(ctx, PackedByteArray(), "Start must be called before finish.");283ERR_FAIL_COND_V_MSG(hash_len == 0, PackedByteArray(), "Unsupported hash type.");284285PackedByteArray out;286out.resize(hash_len);287288unsigned char *out_ptr = (unsigned char *)out.ptrw();289int ret = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out_ptr);290291mbedtls_md_free((mbedtls_md_context_t *)ctx);292memfree((mbedtls_md_context_t *)ctx);293ctx = nullptr;294hash_len = 0;295296ERR_FAIL_COND_V_MSG(ret, PackedByteArray(), "Error received while finishing HMAC");297return out;298}299300HMACContextMbedTLS::~HMACContextMbedTLS() {301if (ctx != nullptr) {302mbedtls_md_free((mbedtls_md_context_t *)ctx);303memfree((mbedtls_md_context_t *)ctx);304}305}306307Crypto *CryptoMbedTLS::create(bool p_notify_postinitialize) {308return static_cast<Crypto *>(ClassDB::creator<CryptoMbedTLS>(p_notify_postinitialize));309}310311void CryptoMbedTLS::initialize_crypto() {312Crypto::_create = create;313Crypto::_load_default_certificates = load_default_certificates;314X509CertificateMbedTLS::make_default();315CryptoKeyMbedTLS::make_default();316HMACContextMbedTLS::make_default();317}318319void CryptoMbedTLS::finalize_crypto() {320Crypto::_create = nullptr;321Crypto::_load_default_certificates = nullptr;322if (default_certs) {323memdelete(default_certs);324default_certs = nullptr;325}326X509CertificateMbedTLS::finalize();327CryptoKeyMbedTLS::finalize();328HMACContextMbedTLS::finalize();329}330331CryptoMbedTLS::CryptoMbedTLS() {332mbedtls_ctr_drbg_init(&ctr_drbg);333mbedtls_entropy_init(&entropy);334int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);335if (ret != 0) {336ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));337}338}339340CryptoMbedTLS::~CryptoMbedTLS() {341mbedtls_ctr_drbg_free(&ctr_drbg);342mbedtls_entropy_free(&entropy);343}344345X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr;346347X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {348return default_certs;349}350351void CryptoMbedTLS::load_default_certificates(const String &p_path) {352ERR_FAIL_COND(default_certs != nullptr);353354default_certs = memnew(X509CertificateMbedTLS);355ERR_FAIL_NULL(default_certs);356357if (!p_path.is_empty()) {358// Use certs defined in project settings.359default_certs->load(p_path);360} else {361// Try to use system certs otherwise.362String system_certs = OS::get_singleton()->get_system_ca_certificates();363if (!system_certs.is_empty()) {364CharString cs = system_certs.utf8();365default_certs->load_from_memory((const uint8_t *)cs.get_data(), cs.size());366print_verbose("Loaded system CA certificates");367}368#ifdef BUILTIN_CERTS_ENABLED369else {370// Use builtin certs if there are no system certs.371PackedByteArray certs;372certs.resize(_certs_uncompressed_size + 1);373const int64_t decompressed_size = Compression::decompress(certs.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);374ERR_FAIL_COND_MSG(decompressed_size != _certs_uncompressed_size, "Error decompressing builtin CA certificates. Decompressed size did not match expected size.");375certs.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator376default_certs->load_from_memory(certs.ptr(), certs.size());377print_verbose("Loaded builtin CA certificates");378}379#endif380}381}382383Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {384Ref<CryptoKeyMbedTLS> out;385out.instantiate();386int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));387ERR_FAIL_COND_V(ret != 0, nullptr);388ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);389out->public_only = false;390ERR_FAIL_COND_V(ret != 0, nullptr);391return out;392}393394Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, const String &p_issuer_name, const String &p_not_before, const String &p_not_after) {395Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);396ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument.");397mbedtls_x509write_cert crt;398mbedtls_x509write_crt_init(&crt);399400mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));401mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));402mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());403mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());404mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);405mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);406407uint8_t rand_serial[20];408mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, sizeof(rand_serial));409410#if MBEDTLS_VERSION_MAJOR >= 3411mbedtls_x509write_crt_set_serial_raw(&crt, rand_serial, sizeof(rand_serial));412#else413mbedtls_mpi serial;414mbedtls_mpi_init(&serial);415ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, sizeof(rand_serial)), nullptr);416mbedtls_x509write_crt_set_serial(&crt, &serial);417#endif418419mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());420mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);421mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);422423unsigned char buf[4096];424memset(buf, 0, 4096);425int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);426#if MBEDTLS_VERSION_MAJOR < 3427mbedtls_mpi_free(&serial);428#endif429mbedtls_x509write_crt_free(&crt);430ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret));431buf[4095] = '\0'; // Make sure strlen can't fail.432433Ref<X509CertificateMbedTLS> out;434out.instantiate();435out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size.436return out;437}438439PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {440ERR_FAIL_COND_V(p_bytes < 0, PackedByteArray());441PackedByteArray out;442out.resize(p_bytes);443int left = p_bytes;444int pos = 0;445// Ensure we generate random in chunks of no more than MBEDTLS_CTR_DRBG_MAX_REQUEST bytes or mbedtls_ctr_drbg_random will fail.446while (left > 0) {447int to_read = MIN(left, MBEDTLS_CTR_DRBG_MAX_REQUEST);448int ret = mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw() + pos, to_read);449ERR_FAIL_COND_V_MSG(ret != 0, PackedByteArray(), vformat("Failed to generate %d random bytes(s). Error: %d.", p_bytes, ret));450left -= to_read;451pos += to_read;452}453return out;454}455456mbedtls_md_type_t CryptoMbedTLS::md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {457switch (p_hash_type) {458case HashingContext::HASH_MD5:459r_size = 16;460return MBEDTLS_MD_MD5;461case HashingContext::HASH_SHA1:462r_size = 20;463return MBEDTLS_MD_SHA1;464case HashingContext::HASH_SHA256:465r_size = 32;466return MBEDTLS_MD_SHA256;467default:468r_size = 0;469ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");470}471}472473Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, Ref<CryptoKey> p_key) {474int size;475mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);476ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");477ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));478Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);479ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");480ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");481size_t sig_size = 0;482#if MBEDTLS_VERSION_MAJOR >= 3483unsigned char buf[MBEDTLS_PK_SIGNATURE_MAX_SIZE];484#else485unsigned char buf[MBEDTLS_MPI_MAX_SIZE];486#endif487Vector<uint8_t> out;488int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf,489#if MBEDTLS_VERSION_MAJOR >= 3490sizeof(buf),491#endif492&sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);493ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));494out.resize(sig_size);495memcpy(out.ptrw(), buf, sig_size);496return out;497}498499bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, const Vector<uint8_t> &p_signature, Ref<CryptoKey> p_key) {500int size;501mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);502ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");503ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));504Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);505ERR_FAIL_COND_V_MSG(key.is_null(), false, "Invalid key provided.");506return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;507}508509Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_plaintext) {510Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);511ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");512uint8_t buf[1024];513size_t size;514Vector<uint8_t> out;515int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);516ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret));517out.resize(size);518memcpy(out.ptrw(), buf, size);519return out;520}521522Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_ciphertext) {523Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);524ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");525ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key.");526uint8_t buf[2048];527size_t size;528Vector<uint8_t> out;529int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);530ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret));531out.resize(size);532memcpy(out.ptrw(), buf, size);533return out;534}535536537