1 /*
2  *  Copyright The Mbed TLS Contributors
3  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
4  */
5 
6 #include "psa/crypto.h"
7 #include <string.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 
11 #define KEY_BITS        4096
12 #define BUFFER_SIZE     PSA_BITS_TO_BYTES(KEY_BITS)
13 
print_bytestr(const uint8_t * bytes,size_t len)14 static void print_bytestr(const uint8_t *bytes, size_t len)
15 {
16     for (unsigned int idx = 0; idx < len; idx++) {
17         printf("%02X", bytes[idx]);
18     }
19 }
20 
psa_asymmetric_encrypt_decrypt_main(void)21 int psa_asymmetric_encrypt_decrypt_main(void)
22 {
23     psa_status_t status;
24     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
25     psa_key_id_t key_id = 0;
26     uint8_t original[BUFFER_SIZE/2] = { 0 };
27     uint8_t encrypt[BUFFER_SIZE] = { 0 };
28     uint8_t decrypt[BUFFER_SIZE] = { 0 };
29     size_t encrypted_length;
30     size_t decrypted_length;
31 
32     status = psa_crypto_init();
33     if (status != PSA_SUCCESS) {
34         printf("psa_crypto_init failed\n");
35         return EXIT_FAILURE;
36     }
37 
38     status = psa_generate_random(original, sizeof(original));
39     if (status != PSA_SUCCESS) {
40         printf("psa_generate_random() failed\n");
41         return EXIT_FAILURE;
42     }
43 
44     psa_set_key_usage_flags(&attributes,
45                             PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
46     psa_set_key_algorithm(&attributes, PSA_ALG_RSA_PKCS1V15_CRYPT);
47     psa_set_key_type(&attributes, PSA_KEY_TYPE_RSA_KEY_PAIR);
48     psa_set_key_bits(&attributes, KEY_BITS);
49 
50     status = psa_generate_key(&attributes, &key_id);
51     if (status != PSA_SUCCESS) {
52         printf("psa_generate_key failed (%d)\n", status);
53         return EXIT_FAILURE;
54     }
55 
56     status = psa_asymmetric_encrypt(key_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
57                                     original, sizeof(original), NULL, 0,
58                                     encrypt, sizeof(encrypt), &encrypted_length);
59     if (status != PSA_SUCCESS) {
60         printf("psa_asymmetric_encrypt failed (%d)\n", status);
61         return EXIT_FAILURE;
62     }
63 
64     status = psa_asymmetric_decrypt(key_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
65                                     encrypt, encrypted_length, NULL, 0,
66                                     decrypt, sizeof(decrypt), &decrypted_length);
67     if (status != PSA_SUCCESS) {
68         printf("psa_cipher_decrypt failed (%d)\n", status);
69         return EXIT_FAILURE;
70     }
71 
72     if (memcmp(original, decrypt, sizeof(original)) != 0) {
73         printf("\nEncryption/Decryption failed!\n");
74     } else {
75         printf("\nEncryption/Decryption successful!\n");
76     }
77 
78     psa_destroy_key(key_id);
79     mbedtls_psa_crypto_free();
80     return 0;
81 }
82