1 /*
2  * SPDX-License-Identifier: Apache-2.0
3  *
4  * Copyright (c) 2018-2019 JUUL Labs
5  * Copyright (c) 2019 Arm Limited
6  *
7  * Original license:
8  *
9  * Licensed to the Apache Software Foundation (ASF) under one
10  * or more contributor license agreements.  See the NOTICE file
11  * distributed with this work for additional information
12  * regarding copyright ownership.  The ASF licenses this file
13  * to you under the Apache License, Version 2.0 (the
14  * "License"); you may not use this file except in compliance
15  * with the License.  You may obtain a copy of the License at
16  *
17  *  http://www.apache.org/licenses/LICENSE-2.0
18  *
19  * Unless required by applicable law or agreed to in writing,
20  * software distributed under the License is distributed on an
21  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
22  * KIND, either express or implied.  See the License for the
23  * specific language governing permissions and limitations
24  * under the License.
25  */
26 
27 #ifndef BOOTUTIL_ENC_KEY_H
28 #define BOOTUTIL_ENC_KEY_H
29 
30 #include <stdbool.h>
31 #include <stdint.h>
32 #include <flash_map_backend/flash_map_backend.h>
33 #include "bootutil/crypto/aes_ctr.h"
34 #include "bootutil/image.h"
35 #include "bootutil/sign_key.h"
36 #include "bootutil/enc_key_public.h"
37 
38 #ifdef __cplusplus
39 extern "C" {
40 #endif
41 
42 #define BOOT_ENC_TLV_ALIGN_SIZE ALIGN_UP(BOOT_ENC_TLV_SIZE, BOOT_MAX_ALIGN)
43 
44 struct enc_key_data {
45     uint8_t valid;
46     bootutil_aes_ctr_context aes_ctr;
47 };
48 
49 /**
50  * Retrieve the private key for image encryption.
51  *
52  * @param[out]  private_key  structure to store the private key and
53  *                           its length.
54  *
55  * @return                   0 on success; nonzero on failure.
56  *
57  */
58 int boot_enc_retrieve_private_key(struct bootutil_key **private_key);
59 
60 struct boot_status;
61 
62 /* Decrypt random, symmetric encryption key */
63 int boot_decrypt_key(const uint8_t *buf, uint8_t *enckey);
64 
65 int boot_enc_init(struct enc_key_data *enc_state, uint8_t slot);
66 int boot_enc_drop(struct enc_key_data *enc_state, uint8_t slot);
67 int boot_enc_set_key(struct enc_key_data *enc_state, uint8_t slot,
68         const struct boot_status *bs);
69 int boot_enc_load(struct enc_key_data *enc_state, int slot,
70         const struct image_header *hdr, const struct flash_area *fap,
71         struct boot_status *bs);
72 bool boot_enc_valid(struct enc_key_data *enc_state, int slot);
73 void boot_enc_encrypt(struct enc_key_data *enc_state, int slot,
74         uint32_t off, uint32_t sz, uint32_t blk_off, uint8_t *buf);
75 void boot_enc_decrypt(struct enc_key_data *enc_state, int slot,
76         uint32_t off, uint32_t sz, uint32_t blk_off, uint8_t *buf);
77 void boot_enc_zeroize(struct enc_key_data *enc_state);
78 
79 #ifdef __cplusplus
80 }
81 #endif
82 
83 #endif /* BOOTUTIL_ENC_KEY_H */
84