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 "../tf-psa-crypto/core/tf_psa_crypto_common.h"
8 #include <string.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #define BUFFER_SIZE 4096
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_cipher_encrypt_decrypt_main(void)21 int psa_cipher_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] = { 0 };
27 uint8_t encrypt[BUFFER_SIZE] = { 0 };
28 uint8_t decrypt[BUFFER_SIZE] = { 0 };
29 /* We need to tell the compiler that we meant to leave out the null character. */
30 const uint8_t key_bytes[32] MBEDTLS_ATTRIBUTE_UNTERMINATED_STRING =
31 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
32 size_t encrypted_length;
33 size_t decrypted_length;
34
35 status = psa_crypto_init();
36 if (status != PSA_SUCCESS) {
37 printf("psa_crypto_init failed\n");
38 return EXIT_FAILURE;
39 }
40
41 status = psa_generate_random(original, sizeof(original));
42 if (status != PSA_SUCCESS) {
43 printf("psa_generate_random() failed\n");
44 return EXIT_FAILURE;
45 }
46
47 psa_set_key_usage_flags(&attributes,
48 PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
49 psa_set_key_algorithm(&attributes, PSA_ALG_ECB_NO_PADDING);
50 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
51 psa_set_key_bits(&attributes, 256);
52
53 status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
54 if (status != PSA_SUCCESS) {
55 printf("psa_import_key failed\n");
56 return EXIT_FAILURE;
57 }
58
59 status = psa_cipher_encrypt(key_id, PSA_ALG_ECB_NO_PADDING,
60 original, sizeof(original),
61 encrypt, sizeof(encrypt), &encrypted_length);
62 if (status != PSA_SUCCESS) {
63 printf("psa_cipher_encrypt failed\n");
64 return EXIT_FAILURE;
65 }
66
67 status = psa_cipher_decrypt(key_id, PSA_ALG_ECB_NO_PADDING,
68 encrypt, encrypted_length,
69 decrypt, sizeof(decrypt), &decrypted_length);
70 if (status != PSA_SUCCESS) {
71 printf("psa_cipher_decrypt failed\n");
72 return EXIT_FAILURE;
73 }
74
75 if (memcmp(original, decrypt, sizeof(original)) != 0) {
76 printf("\nEncryption/Decryption failed!\n");
77 } else {
78 printf("\nEncryption/Decryption successful!\n");
79 }
80
81 psa_destroy_key(key_id);
82 mbedtls_psa_crypto_free();
83 return 0;
84 }
85