1 /*
2  * Copyright (C) 2015-2017 Alibaba Group Holding Limited
3  */
4 
5 #include "kv_conf.h"
6 
7 #if (KV_SECURE_SUPPORT)
8 
9 #include <stdint.h>
10 #include <string.h>
11 
12 #include "aos/kv.h"
13 
14 #include "kv_adapt.h"
15 
16 #if (KV_SECURE_CRYPT_IMPL == 1)
17 
18 #include "mbedtls/aes.h"
19 
20 #define OFB_KEY_LEN 32
21 #define OFB_IV_LEN  16
22 
23 static mbedtls_aes_context aes_context;
24 
_ofb_encrypt_wrap(uint8_t * ofb_key,uint8_t * ofb_iv,uint8_t * input,uint8_t * output,uint32_t len)25 static int32_t _ofb_encrypt_wrap(uint8_t *ofb_key, uint8_t *ofb_iv,
26                                  uint8_t *input, uint8_t *output, uint32_t len)
27 {
28     int32_t ret;
29 
30     uint32_t offset = 0;
31     uint8_t  iv[OFB_IV_LEN] = {0};
32 
33     if ((input == NULL) || (output == NULL)) {
34         return KV_ERR_INVALID_PARAM;
35     }
36 
37     memcpy(iv, ofb_iv, sizeof(iv));
38 
39     ret = mbedtls_aes_setkey_enc(&aes_context, ofb_key, OFB_KEY_LEN * 8);
40     if (ret != KV_OK) {
41         return ret;
42     }
43 
44     ret = mbedtls_aes_crypt_ofb(&aes_context, len, &offset, iv, input, output);
45     if (ret != KV_OK) {
46         return ret;
47     }
48 
49     return KV_OK;
50 }
51 
kv_secure_encrypt(uint8_t * input,uint8_t * output,uint32_t input_len)52 int32_t kv_secure_encrypt(uint8_t *input, uint8_t *output, uint32_t input_len)
53 {
54     uint8_t *ofb_key = NULL;
55     uint8_t *ofb_iv  = NULL;
56 
57     ofb_key = kv_secure_getkey(OFB_KEY_LEN);
58     ofb_iv  = kv_secure_getiv(OFB_IV_LEN);
59 
60     if ((ofb_key == NULL) || (ofb_iv == NULL)) {
61         return KV_ERR_ENCRYPT;
62     }
63 
64     if (_ofb_encrypt_wrap(ofb_key, ofb_iv, input, output, input_len) != KV_OK) {
65         return KV_ERR_ENCRYPT;
66     }
67 
68     return KV_OK;
69 }
70 
kv_secure_decrypt(uint8_t * input,uint8_t * output,uint32_t input_len)71 int32_t kv_secure_decrypt(uint8_t *input, uint8_t *output, uint32_t input_len)
72 {
73     uint8_t *ofb_key = NULL;
74     uint8_t *ofb_iv  = NULL;
75 
76     ofb_key = kv_secure_get_key(OFB_KEY_LEN);
77     ofb_iv  = kv_secure_get_iv(OFB_IV_LEN);
78 
79     if ((ofb_key == NULL) || (ofb_iv == NULL)) {
80         return KV_ERR_ENCRYPT;
81     }
82 
83     if (_ofb_encrypt_wrap(ofb_key, ofb_iv, input, output, input_len) != KV_OK) {
84         return KV_ERR_ENCRYPT;
85     }
86 
87     return KV_OK;
88 }
89 
90 #else /* User defined encrypt/decrypt implement here */
91 
kv_secure_encrypt(uint8_t * input,uint8_t * output,uint32_t input_len)92 int32_t kv_secure_encrypt(uint8_t *input, uint8_t *output, uint32_t input_len)
93 {
94     return KV_ERR_NOT_SUPPORT;
95 }
96 
kv_secure_decrypt(uint8_t * input,uint8_t * output,uint32_t input_len)97 int32_t kv_secure_decrypt(uint8_t *input, uint8_t *output, uint32_t input_len)
98 {
99     return KV_ERR_NOT_SUPPORT;
100 }
101 
102 #endif /* KV_SECURE_CRYPT_IMPL */
103 
104 #endif /* KV_SECURE_SUPPORT */
105 
106