Debian Codegraph @

modules/mbedtls/crypto_mbedtls.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* crypto_mbedtls.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "crypto_mbedtls.h"
32
33 #include "core/io/certs_compressed.gen.h"
34 #include "core/io/compression.h"
35 #include "core/io/file_access.h"
36 #include "core/os/os.h"
37
38 #include <mbedtls/debug.h>
39 #include <mbedtls/md.h>
40 #include <mbedtls/pem.h>
41
42 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
43 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
44 #define PEM_MIN_SIZE 54
45
46 CryptoKey *CryptoKeyMbedTLS::create(bool p_notify_postinitialize) {
47 return static_cast<CryptoKey *>(ClassDB::creator<CryptoKeyMbedTLS>(p_notify_postinitialize));
48 }
49
50 Error CryptoKeyMbedTLS::load(const String &p_path, bool p_public_only) {
51 ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
52
53 PackedByteArray out;
54 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
55 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'.");
56
57 uint64_t flen = f->get_length();
58 out.resize(flen + 1);
59 f->get_buffer(out.ptrw(), flen);
60 out.write[flen] = 0; // string terminator
61
62 int ret = 0;
63 if (p_public_only) {
64 ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size());
65 } else {
66 ret = _parse_key(out.ptr(), out.size());
67 }
68 // We MUST zeroize the memory for safety!
69 mbedtls_platform_zeroize(out.ptrw(), out.size());
70 ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
71
72 public_only = p_public_only;
73 return OK;
74 }
75
76 Error CryptoKeyMbedTLS::save(const String &p_path, bool p_public_only) {
77 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
78 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'.");
79
80 unsigned char w[16000];
81 memset(w, 0, sizeof(w));
82
83 int ret = 0;
84 if (p_public_only) {
85 ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
86 } else {
87 ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
88 }
89 if (ret != 0) {
90 mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written.
91 ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'.");
92 }
93
94 size_t len = strlen((char *)w);
95 f->store_buffer(w, len);
96 mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer.
97 return OK;
98 }
99
100 Error CryptoKeyMbedTLS::load_from_string(const String &p_string_key, bool p_public_only) {
101 int ret = 0;
102 const CharString string_key_utf8 = p_string_key.utf8();
103 if (p_public_only) {
104 ret = mbedtls_pk_parse_public_key(&pkey, (const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());
105 } else {
106 ret = _parse_key((const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());
107 }
108 ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
109
110 public_only = p_public_only;
111 return OK;
112 }
113
114 String CryptoKeyMbedTLS::save_to_string(bool p_public_only) {
115 unsigned char w[16000];
116 memset(w, 0, sizeof(w));
117
118 int ret = 0;
119 if (p_public_only) {
120 ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
121 } else {
122 ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
123 }
124 if (ret != 0) {
125 mbedtls_platform_zeroize(w, sizeof(w));
126 ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'.");
127 }
128 String s = String::utf8((char *)w);
129 return s;
130 }
131
132 int CryptoKeyMbedTLS::_parse_key(const uint8_t *p_buf, int p_size) {
133 #if MBEDTLS_VERSION_MAJOR >= 3
134 mbedtls_entropy_context rng_entropy;
135 mbedtls_ctr_drbg_context rng_drbg;
136
137 mbedtls_ctr_drbg_init(&rng_drbg);
138 mbedtls_entropy_init(&rng_entropy);
139 int ret = mbedtls_ctr_drbg_seed(&rng_drbg, mbedtls_entropy_func, &rng_entropy, nullptr, 0);
140 ERR_FAIL_COND_V_MSG(ret != 0, ret, vformat("mbedtls_ctr_drbg_seed returned -0x%x\n", (unsigned int)-ret));
141
142 ret = mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0, mbedtls_ctr_drbg_random, &rng_drbg);
143 mbedtls_ctr_drbg_free(&rng_drbg);
144 mbedtls_entropy_free(&rng_entropy);
145 return ret;
146 #else
147 return mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0);
148 #endif
149 }
150
151 X509Certificate *X509CertificateMbedTLS::create(bool p_notify_postinitialize) {
152 return static_cast<X509Certificate *>(ClassDB::creator<X509CertificateMbedTLS>(p_notify_postinitialize));
153 }
154
155 Error X509CertificateMbedTLS::load(const String &p_path) {
156 ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
157
158 PackedByteArray out;
159 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
160 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot open X509CertificateMbedTLS file '%s'.", p_path));
161
162 uint64_t flen = f->get_length();
163 out.resize(flen + 1);
164 f->get_buffer(out.ptrw(), flen);
165 out.write[flen] = 0; // string terminator
166
167 int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());
168 ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates from file '%s': %d.", p_path, ret));
169 if (ret > 0) { // Some certs parsed fine, don't error.
170 print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed from file '%s' (%d certificates skipped).", p_path, ret));
171 }
172
173 return OK;
174 }
175
176 Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {
177 ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
178
179 int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);
180 ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
181 if (ret > 0) { // Some certs parsed fine, don't error.
182 print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
183 }
184 return OK;
185 }
186
187 Error X509CertificateMbedTLS::save(const String &p_path) {
188 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
189 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot save X509CertificateMbedTLS file '%s'.", p_path));
190
191 mbedtls_x509_crt *crt = &cert;
192 while (crt) {
193 unsigned char w[4096];
194 size_t wrote = 0;
195 int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
196 if (ret != 0 || wrote == 0) {
197 ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'.");
198 }
199
200 f->store_buffer(w, wrote - 1); // don't write the string terminator
201 crt = crt->next;
202 }
203 return OK;
204 }
205
206 String X509CertificateMbedTLS::save_to_string() {
207 String buffer;
208 mbedtls_x509_crt *crt = &cert;
209 while (crt) {
210 unsigned char w[4096];
211 size_t wrote = 0;
212 int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
213 ERR_FAIL_COND_V_MSG(ret != 0 || wrote == 0, String(), "Error saving the certificate.");
214
215 // PEM is base64, aka ascii
216 buffer += String::ascii(Span((char *)w, wrote));
217 crt = crt->next;
218 }
219 if (buffer.length() <= PEM_MIN_SIZE) {
220 // When the returned value of variable 'buffer' would consist of no Base-64 data, return an empty String instead.
221 return String();
222 }
223 return buffer;
224 }
225
226 Error X509CertificateMbedTLS::load_from_string(const String &p_string_key) {
227 ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
228 CharString cs = p_string_key.utf8();
229
230 int ret = mbedtls_x509_crt_parse(&cert, (const unsigned char *)cs.get_data(), cs.size());
231 ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
232 if (ret > 0) { // Some certs parsed fine, don't error.
233 print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
234 }
235
236 return OK;
237 }
238
239 bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {
240 switch (p_md_type) {
241 case MBEDTLS_MD_SHA1:
242 case MBEDTLS_MD_SHA256:
243 return true;
244 default:
245 return false;
246 }
247 }
248
249 HMACContext *HMACContextMbedTLS::create(bool p_notify_postinitialize) {
250 return static_cast<HMACContext *>(ClassDB::creator<HMACContextMbedTLS>(p_notify_postinitialize));
251 }
252
253 Error HMACContextMbedTLS::start(HashingContext::HashType p_hash_type, const PackedByteArray &p_key) {
254 ERR_FAIL_COND_V_MSG(ctx != nullptr, ERR_FILE_ALREADY_IN_USE, "HMACContext already started.");
255
256 // HMAC keys can be any size.
257 ERR_FAIL_COND_V_MSG(p_key.is_empty(), ERR_INVALID_PARAMETER, "Key must not be empty.");
258
259 hash_type = p_hash_type;
260 mbedtls_md_type_t ht = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, hash_len);
261
262 bool allowed = HMACContextMbedTLS::is_md_type_allowed(ht);
263 ERR_FAIL_COND_V_MSG(!allowed, ERR_INVALID_PARAMETER, "Unsupported hash type.");
264
265 ctx = memalloc(sizeof(mbedtls_md_context_t));
266 mbedtls_md_init((mbedtls_md_context_t *)ctx);
267
268 mbedtls_md_setup((mbedtls_md_context_t *)ctx, mbedtls_md_info_from_type((mbedtls_md_type_t)ht), 1);
269 int ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, (const uint8_t *)p_key.ptr(), (size_t)p_key.size());
270 return ret ? FAILED : OK;
271 }
272
273 Error HMACContextMbedTLS::update(const PackedByteArray &p_data) {
274 ERR_FAIL_NULL_V_MSG(ctx, ERR_INVALID_DATA, "Start must be called before update.");
275
276 ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_PARAMETER, "Src must not be empty.");
277
278 int ret = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, (const uint8_t *)p_data.ptr(), (size_t)p_data.size());
279 return ret ? FAILED : OK;
280 }
281
282 PackedByteArray HMACContextMbedTLS::finish() {
283 ERR_FAIL_NULL_V_MSG(ctx, PackedByteArray(), "Start must be called before finish.");
284 ERR_FAIL_COND_V_MSG(hash_len == 0, PackedByteArray(), "Unsupported hash type.");
285
286 PackedByteArray out;
287 out.resize(hash_len);
288
289 unsigned char *out_ptr = (unsigned char *)out.ptrw();
290 int ret = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out_ptr);
291
292 mbedtls_md_free((mbedtls_md_context_t *)ctx);
293 memfree((mbedtls_md_context_t *)ctx);
294 ctx = nullptr;
295 hash_len = 0;
296
297 ERR_FAIL_COND_V_MSG(ret, PackedByteArray(), "Error received while finishing HMAC");
298 return out;
299 }
300
301 HMACContextMbedTLS::~HMACContextMbedTLS() {
302 if (ctx != nullptr) {
303 mbedtls_md_free((mbedtls_md_context_t *)ctx);
304 memfree((mbedtls_md_context_t *)ctx);
305 }
306 }
307
308 Crypto *CryptoMbedTLS::create(bool p_notify_postinitialize) {
309 return static_cast<Crypto *>(ClassDB::creator<CryptoMbedTLS>(p_notify_postinitialize));
310 }
311
312 void CryptoMbedTLS::initialize_crypto() {
313 Crypto::_create = create;
314 Crypto::_load_default_certificates = load_default_certificates;
315 X509CertificateMbedTLS::make_default();
316 CryptoKeyMbedTLS::make_default();
317 HMACContextMbedTLS::make_default();
318 }
319
320 void CryptoMbedTLS::finalize_crypto() {
321 Crypto::_create = nullptr;
322 Crypto::_load_default_certificates = nullptr;
323 if (default_certs) {
324 memdelete(default_certs);
325 default_certs = nullptr;
326 }
327 X509CertificateMbedTLS::finalize();
328 CryptoKeyMbedTLS::finalize();
329 HMACContextMbedTLS::finalize();
330 }
331
332 CryptoMbedTLS::CryptoMbedTLS() {
333 mbedtls_ctr_drbg_init(&ctr_drbg);
334 mbedtls_entropy_init(&entropy);
335 int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);
336 if (ret != 0) {
337 ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
338 }
339 }
340
341 CryptoMbedTLS::~CryptoMbedTLS() {
342 mbedtls_ctr_drbg_free(&ctr_drbg);
343 mbedtls_entropy_free(&entropy);
344 }
345
346 X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr;
347
348 X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {
349 return default_certs;
350 }
351
352 void CryptoMbedTLS::load_default_certificates(const String &p_path) {
353 ERR_FAIL_COND(default_certs != nullptr);
354
355 default_certs = memnew(X509CertificateMbedTLS);
356 ERR_FAIL_NULL(default_certs);
357
358 if (!p_path.is_empty()) {
359 // Use certs defined in project settings.
360 default_certs->load(p_path);
361 } else {
362 // Try to use system certs otherwise.
363 String system_certs = OS::get_singleton()->get_system_ca_certificates();
364 if (!system_certs.is_empty()) {
365 CharString cs = system_certs.utf8();
366 default_certs->load_from_memory((const uint8_t *)cs.get_data(), cs.size());
367 print_verbose("Loaded system CA certificates");
368 }
369 #ifdef BUILTIN_CERTS_ENABLED
370 else {
371 // Use builtin certs if there are no system certs.
372 PackedByteArray certs;
373 certs.resize(_certs_uncompressed_size + 1);
374 const int64_t decompressed_size = Compression::decompress(certs.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
375 ERR_FAIL_COND_MSG(decompressed_size != _certs_uncompressed_size, "Error decompressing builtin CA certificates. Decompressed size did not match expected size.");
376 certs.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
377 default_certs->load_from_memory(certs.ptr(), certs.size());
378 print_verbose("Loaded builtin CA certificates");
379 }
380 #endif
381 }
382 }
383
384 Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
385 Ref<CryptoKeyMbedTLS> out;
386 out.instantiate();
387 int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
388 ERR_FAIL_COND_V(ret != 0, nullptr);
389 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
390 out->public_only = false;
391 ERR_FAIL_COND_V(ret != 0, nullptr);
392 return out;
393 }
394
395 Ref<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) {
396 Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
397 ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument.");
398 mbedtls_x509write_cert crt;
399 mbedtls_x509write_crt_init(&crt);
400
401 mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
402 mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
403 mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
404 mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
405 mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
406 mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
407
408 uint8_t rand_serial[20];
409 mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, sizeof(rand_serial));
410
411 #if MBEDTLS_VERSION_MAJOR >= 3
412 mbedtls_x509write_crt_set_serial_raw(&crt, rand_serial, sizeof(rand_serial));
413 #else
414 mbedtls_mpi serial;
415 mbedtls_mpi_init(&serial);
416 ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, sizeof(rand_serial)), nullptr);
417 mbedtls_x509write_crt_set_serial(&crt, &serial);
418 #endif
419
420 mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
421 mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
422 mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
423
424 unsigned char buf[4096];
425 memset(buf, 0, 4096);
426 int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
427 #if MBEDTLS_VERSION_MAJOR < 3
428 mbedtls_mpi_free(&serial);
429 #endif
430 mbedtls_x509write_crt_free(&crt);
431 ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret));
432 buf[4095] = '\0'; // Make sure strlen can't fail.
433
434 Ref<X509CertificateMbedTLS> out;
435 out.instantiate();
436 out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size.
437 return out;
438 }
439
440 PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
441 ERR_FAIL_COND_V(p_bytes < 0, PackedByteArray());
442 PackedByteArray out;
443 out.resize(p_bytes);
444 int left = p_bytes;
445 int pos = 0;
446 // Ensure we generate random in chunks of no more than MBEDTLS_CTR_DRBG_MAX_REQUEST bytes or mbedtls_ctr_drbg_random will fail.
447 while (left > 0) {
448 int to_read = MIN(left, MBEDTLS_CTR_DRBG_MAX_REQUEST);
449 int ret = mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw() + pos, to_read);
450 ERR_FAIL_COND_V_MSG(ret != 0, PackedByteArray(), vformat("Failed to generate %d random bytes(s). Error: %d.", p_bytes, ret));
451 left -= to_read;
452 pos += to_read;
453 }
454 return out;
455 }
456
457 mbedtls_md_type_t CryptoMbedTLS::md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {
458 switch (p_hash_type) {
459 case HashingContext::HASH_MD5:
460 r_size = 16;
461 return MBEDTLS_MD_MD5;
462 case HashingContext::HASH_SHA1:
463 r_size = 20;
464 return MBEDTLS_MD_SHA1;
465 case HashingContext::HASH_SHA256:
466 r_size = 32;
467 return MBEDTLS_MD_SHA256;
468 default:
469 r_size = 0;
470 ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");
471 }
472 }
473
474 Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, Ref<CryptoKey> p_key) {
475 int size;
476 mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
477 ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");
478 ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));
479 Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
480 ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
481 ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");
482 size_t sig_size = 0;
483 #if MBEDTLS_VERSION_MAJOR >= 3
484 unsigned char buf[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
485 #else
486 unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
487 #endif
488 Vector<uint8_t> out;
489 int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf,
490 #if MBEDTLS_VERSION_MAJOR >= 3
491 sizeof(buf),
492 #endif
493 &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);
494 ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));
495 out.resize(sig_size);
496 memcpy(out.ptrw(), buf, sig_size);
497 return out;
498 }
499
500 bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, const Vector<uint8_t> &p_signature, Ref<CryptoKey> p_key) {
501 int size;
502 mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
503 ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");
504 ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));
505 Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
506 ERR_FAIL_COND_V_MSG(key.is_null(), false, "Invalid key provided.");
507 return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;
508 }
509
510 Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_plaintext) {
511 Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
512 ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
513 uint8_t buf[1024];
514 size_t size;
515 Vector<uint8_t> out;
516 int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
517 ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret));
518 out.resize(size);
519 memcpy(out.ptrw(), buf, size);
520 return out;
521 }
522
523 Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_ciphertext) {
524 Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
525 ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
526 ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key.");
527 uint8_t buf[2048];
528 size_t size;
529 Vector<uint8_t> out;
530 int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
531 ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret));
532 out.resize(size);
533 memcpy(out.ptrw(), buf, size);
534 return out;
535 }