1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "aes_openssl_common.h"
17 
18 #include "log.h"
19 #include "memory.h"
20 #include "result.h"
21 #include "openssl_adapter.h"
22 
GetIv(HcfParamsSpec * params)23 const unsigned char *GetIv(HcfParamsSpec *params)
24 {
25     if (params == NULL) {
26         return NULL;
27     }
28     HcfIvParamsSpec *spec = (HcfIvParamsSpec *)params;
29     uint8_t *iv = spec->iv.data;
30     return (const unsigned char *)iv;
31 }
32 
GetIvLen(HcfParamsSpec * params)33 size_t GetIvLen(HcfParamsSpec *params)
34 {
35     if (params == NULL) {
36         return 0;
37     }
38     HcfIvParamsSpec *spec = (HcfIvParamsSpec *)params;
39     return spec->iv.len;
40 }
41 
GetCcmTagLen(HcfParamsSpec * params)42 int32_t GetCcmTagLen(HcfParamsSpec *params)
43 {
44     if (params == NULL) {
45         return 0;
46     }
47     HcfCcmParamsSpec *spec = (HcfCcmParamsSpec *)params;
48     size_t tagLen = spec->tag.len;
49     return (int)tagLen;
50 }
51 
GetCcmTag(HcfParamsSpec * params)52 void *GetCcmTag(HcfParamsSpec *params)
53 {
54     if (params == NULL) {
55         return NULL;
56     }
57     HcfCcmParamsSpec *spec = (HcfCcmParamsSpec *)params;
58     uint8_t *tag = spec->tag.data;
59     return (void *)tag;
60 }
61 
FreeCipherData(CipherData ** data)62 void FreeCipherData(CipherData **data)
63 {
64     if (data == NULL || *data == NULL) {
65         return;
66     }
67     if ((*data)->ctx != NULL) {
68         OpensslEvpCipherCtxFree((*data)->ctx);
69         (*data)->ctx = NULL;
70     }
71     if ((*data)->aad != NULL) {
72         HcfFree((*data)->aad);
73         (*data)->aad = NULL;
74     }
75     if ((*data)->iv != NULL) {
76         HcfFree((*data)->iv);
77         (*data)->iv = NULL;
78     }
79     if ((*data)->tag != NULL) {
80         HcfFree((*data)->tag);
81         (*data)->tag = NULL;
82     }
83     HcfFree(*data);
84     *data = NULL;
85 }
86 
FreeRedundantOutput(HcfBlob * blob)87 void FreeRedundantOutput(HcfBlob *blob)
88 {
89     if (blob == NULL) {
90         return;
91     }
92     // when decrypt result is empty plaintext, out blob data maybe not null (malloc by hcf before decryption)
93     if ((blob->len == 0) && (blob->data != NULL)) {
94         HcfFree(blob->data);
95         blob->data = NULL;
96     }
97 }