1 /*
2  * Copyright (C) 2015-2018 Alibaba Group Holding Limited
3  */
4 
5 #ifndef _IOTX_COMMON_SHA256_H_
6 #define _IOTX_COMMON_SHA256_H_
7 
8 #include <stdint.h>
9 
10 #define SHA256_DIGEST_LENGTH        (32)
11 #define SHA256_BLOCK_LENGTH         (64)
12 #define SHA256_SHORT_BLOCK_LENGTH   (SHA256_BLOCK_LENGTH - 8)
13 #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
14 
15 /**
16  * \brief          SHA-256 context structure
17  */
18 typedef struct {
19     uint32_t total[2];        /*!< number of bytes processed  */
20     uint32_t state[8];        /*!< intermediate digest state  */
21     unsigned char buffer[64]; /*!< data block being processed */
22     int is224;                /*!< 0 => SHA-256, else SHA-224 */
23 } iot_sha256_context;
24 
25 typedef union {
26     char sptr[8];
27     uint64_t lint;
28 } u_retLen;
29 
30 /**
31  * \brief          Initialize SHA-256 context
32  *
33  * \param ctx      SHA-256 context to be initialized
34  */
35 void utils_sha256_init(iot_sha256_context *ctx);
36 
37 /**
38  * \brief          Clear SHA-256 context
39  *
40  * \param ctx      SHA-256 context to be cleared
41  */
42 void utils_sha256_free(iot_sha256_context *ctx);
43 
44 /**
45  * \brief          SHA-256 context setup
46  *
47  * \param ctx      context to be initialized
48  */
49 void utils_sha256_starts(iot_sha256_context *ctx);
50 
51 /**
52  * \brief          SHA-256 process buffer
53  *
54  * \param ctx      SHA-256 context
55  * \param input    buffer holding the  data
56  * \param ilen     length of the input data
57  */
58 void utils_sha256_update(iot_sha256_context *ctx, const unsigned char *input,
59                          uint32_t ilen);
60 
61 /**
62  * \brief          SHA-256 final digest
63  *
64  * \param ctx      SHA-256 context
65  * \param output   SHA-256 checksum result
66  */
67 void utils_sha256_finish(iot_sha256_context *ctx, uint8_t output[32]);
68 
69 /* Internal use */
70 void utils_sha256_process(iot_sha256_context *ctx,
71                           const unsigned char data[64]);
72 
73 /**
74  * \brief          Output = SHA-256( input buffer )
75  *
76  * \param input    buffer holding the  data
77  * \param ilen     length of the input data
78  * \param output   SHA-256 checksum result
79  */
80 void utils_sha256(const uint8_t *input, uint32_t ilen, uint8_t output[32]);
81 
82 void utils_hmac_sha256(const uint8_t *msg, uint32_t msg_len, const uint8_t *key,
83                        uint32_t key_len, uint8_t output[32]);
84 
85 #endif
86