1 /*
2 * SPDX-FileCopyrightText: 2020-2021 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include "esp_tls_crypto.h"
8 #include "esp_log.h"
9 #include "esp_err.h"
10 static const char *TAG = "esp_crypto";
11 #ifdef CONFIG_ESP_TLS_USING_MBEDTLS
12 #include "mbedtls/sha1.h"
13 #include "mbedtls/base64.h"
14 #define _esp_crypto_sha1 esp_crypto_sha1_mbedtls
15 #define _esp_crypto_base64_encode esp_crypto_bas64_encode_mbedtls
16 #elif CONFIG_ESP_TLS_USING_WOLFSSL
17 #include "wolfssl/ssl.h" /* SHA functions are listed in wolfssl/ssl.h */
18 #include "wolfssl/wolfcrypt/coding.h"
19 #define _esp_crypto_sha1 esp_crypto_sha1_wolfSSL
20 #define _esp_crypto_base64_encode esp_crypto_base64_encode_woflSSL
21 #endif
22
23 #ifdef CONFIG_ESP_TLS_USING_MBEDTLS
esp_crypto_sha1_mbedtls(const unsigned char * input,size_t ilen,unsigned char output[20])24 static int esp_crypto_sha1_mbedtls( const unsigned char *input,
25 size_t ilen,
26 unsigned char output[20])
27 {
28 int ret = mbedtls_sha1_ret(input, ilen, output);
29 if (ret != 0) {
30 ESP_LOGE(TAG, "Error in calculating sha1 sum , Returned 0x%02X", ret);
31 }
32 return ret;
33 }
34
esp_crypto_bas64_encode_mbedtls(unsigned char * dst,size_t dlen,size_t * olen,const unsigned char * src,size_t slen)35 static int esp_crypto_bas64_encode_mbedtls( unsigned char *dst, size_t dlen,
36 size_t *olen, const unsigned char *src,
37 size_t slen)
38 {
39 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
40 }
41
42 #elif CONFIG_ESP_TLS_USING_WOLFSSL
esp_crypto_sha1_wolfSSL(const unsigned char * input,size_t ilen,unsigned char output[20])43 static int esp_crypto_sha1_wolfSSL( const unsigned char *input,
44 size_t ilen,
45 unsigned char output[20])
46 {
47 unsigned char *ret = wolfSSL_SHA1(input, ilen, output);
48 if (ret == NULL) {
49 ESP_LOGE(TAG, "Error in calculating sha1 sum");
50 return -1;
51 }
52 return 0;
53 }
54
esp_crypto_base64_encode_woflSSL(unsigned char * dst,size_t dlen,size_t * olen,const unsigned char * src,size_t slen)55 static int esp_crypto_base64_encode_woflSSL(unsigned char *dst, size_t dlen, size_t *olen,
56 const unsigned char *src, size_t slen)
57 {
58 *olen = dlen;
59 return Base64_Encode_NoNl((const byte *) src, (word32) slen, (byte *) dst, (word32 *) olen);
60 }
61
62 #else
63 #error "No TLS/SSL Stack selected"
64 #endif
65
esp_crypto_sha1(const unsigned char * input,size_t ilen,unsigned char output[20])66 int esp_crypto_sha1( const unsigned char *input,
67 size_t ilen,
68 unsigned char output[20])
69 {
70 return _esp_crypto_sha1(input, ilen, output);
71 }
72
esp_crypto_base64_encode(unsigned char * dst,size_t dlen,size_t * olen,const unsigned char * src,size_t slen)73 int esp_crypto_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
74 const unsigned char *src, size_t slen )
75 {
76 return _esp_crypto_base64_encode(dst, dlen, olen, src, slen);
77 }
78