1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2019,Softathome
6 #define OPENSSL_API_COMPAT 0x10101000L
13 #include <openssl/bn.h>
14 #include <openssl/rsa.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/ssl.h>
18 #include <openssl/evp.h>
19 #include <openssl/engine.h>
20 #include <uboot_aes.h>
22 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
23 #define HAVE_ERR_REMOVE_THREAD_STATE
26 int image_aes_encrypt(struct image_cipher_info *info,
27 unsigned char *data, int size,
28 unsigned char **cipher, int *cipher_len)
31 unsigned char *buf = NULL;
32 int buf_len, len, ret = 0;
34 /* create and initialise the context */
35 ctx = EVP_CIPHER_CTX_new();
37 printf("Can't create context\n");
41 /* allocate a buffer for the result */
42 buf = malloc(size + AES_BLOCK_LENGTH);
44 printf("Can't allocate memory to encrypt\n");
49 if (EVP_EncryptInit_ex(ctx, info->cipher->calculate_type(),
50 NULL, info->key, info->iv) != 1) {
51 printf("Can't init encryption\n");
56 if (EVP_EncryptUpdate(ctx, buf, &len, data, size) != 1) {
57 printf("Can't encrypt data\n");
64 if (EVP_EncryptFinal_ex(ctx, buf + len, &len) != 1) {
65 printf("Can't finalise the encryption\n");
73 *cipher_len = buf_len;
76 EVP_CIPHER_CTX_free(ctx);
80 int image_aes_add_cipher_data(struct image_cipher_info *info, void *keydest,
81 void *fit, int node_noffset)
87 /* Either create or overwrite the named cipher node */
88 parent = fdt_subnode_offset(keydest, 0, FIT_CIPHER_NODENAME);
89 if (parent == -FDT_ERR_NOTFOUND) {
90 parent = fdt_add_subnode(keydest, 0, FIT_CIPHER_NODENAME);
93 if (ret != -FDT_ERR_NOSPACE) {
95 "Couldn't create cipher node: %s\n",
96 fdt_strerror(parent));
103 /* Either create or overwrite the named key node */
105 snprintf(name, sizeof(name), "key-%s-%s-%s",
106 info->name, info->keyname, info->ivname);
108 snprintf(name, sizeof(name), "key-%s-%s",
109 info->name, info->keyname);
111 node = fdt_subnode_offset(keydest, parent, name);
112 if (node == -FDT_ERR_NOTFOUND) {
113 node = fdt_add_subnode(keydest, parent, name);
116 if (ret != -FDT_ERR_NOSPACE) {
118 "Could not create key subnode: %s\n",
122 } else if (node < 0) {
123 fprintf(stderr, "Cannot select keys parent: %s\n",
132 /* Store the IV in the u-boot device tree */
133 ret = fdt_setprop(keydest, node, "iv",
134 info->iv, info->cipher->iv_len);
136 /* Store the IV in the FIT image */
137 ret = fdt_setprop(fit, node_noffset, "iv",
138 info->iv, info->cipher->iv_len);
141 ret = fdt_setprop(keydest, node, "key",
142 info->key, info->cipher->key_len);
145 ret = fdt_setprop_u32(keydest, node, "key-len",
146 info->cipher->key_len);
150 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;