1 /*
2 * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6 #include <stddef.h>
7 #include <sys/lock.h>
8
9 #include "soc/soc_caps.h"
10 #include "soc/periph_defs.h"
11 #include "esp_private/periph_ctrl.h"
12
13 #include "sha/sha_block.h"
14 #include "hal/sha_hal.h"
15
16
17 static _lock_t s_sha_lock;
18
esp_sha_write_digest_state(esp_sha_type sha_type,void * digest_state)19 void esp_sha_write_digest_state(esp_sha_type sha_type, void *digest_state)
20 {
21 sha_hal_write_digest(sha_type, digest_state);
22 }
23
esp_sha_read_digest_state(esp_sha_type sha_type,void * digest_state)24 void esp_sha_read_digest_state(esp_sha_type sha_type, void *digest_state)
25 {
26 sha_hal_read_digest(sha_type, digest_state);
27 }
28
29 /* Return block size (in bytes) for a given SHA type */
block_length(esp_sha_type type)30 inline static size_t block_length(esp_sha_type type)
31 {
32 switch (type) {
33 case SHA1:
34 case SHA2_224:
35 case SHA2_256:
36 return 64;
37 #if SOC_SHA_SUPPORT_SHA384
38 case SHA2_384:
39 #endif
40 #if SOC_SHA_SUPPORT_SHA512
41 case SHA2_512:
42 #endif
43 #if SOC_SHA_SUPPORT_SHA512_T
44 case SHA2_512224:
45 case SHA2_512256:
46 case SHA2_512T:
47 #endif
48 return 128;
49 default:
50 return 0;
51 }
52 }
53
54
55 /* Lock the SHA peripheral and then enable it */
esp_sha_acquire_hardware()56 void esp_sha_acquire_hardware()
57 {
58 _lock_acquire(&s_sha_lock); /* Released when releasing hw with esp_sha_release_hardware() */
59 periph_module_enable(PERIPH_SHA_MODULE);
60 }
61
62 /* Disable SHA peripheral block and then release it */
esp_sha_release_hardware()63 void esp_sha_release_hardware()
64 {
65 periph_module_disable(PERIPH_SHA_MODULE);
66 _lock_release(&s_sha_lock);
67 }
68
69
esp_sha_block(esp_sha_type sha_type,const void * data_block,bool is_first_block)70 void esp_sha_block(esp_sha_type sha_type, const void *data_block, bool is_first_block)
71 {
72 sha_hal_hash_block(sha_type, data_block, block_length(sha_type) / 4, is_first_block);
73 }
74