1 /*
2  * Copyright (C) 2022-2024 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 #ifndef ADAPTOR_ALGORITHM_H
17 #define ADAPTOR_ALGORITHM_H
18 
19 #include <stdbool.h>
20 #include <stdint.h>
21 #include "buffer.h"
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif // __cplusplus
26 
27 #define ED25519_FIX_SIGN_BUFFER_SIZE 64
28 #define ED25519_FIX_PUBKEY_BUFFER_SIZE 32
29 #define SECRET_SIZE 32
30 #define HKDF_SALT_SIZE 32
31 #define HKDF_KEY_SIZE 32
32 #define AES_GCM_256_KEY_SIZE 32
33 #define AES_GCM_256_IV_SIZE 12
34 #define AES_GCM_256_TAG_SIZE 16
35 #define AES_GCM_256_AAD_MAX_SIZE 32
36 #define CIPHER_INFO_MAX_SIZE 1024
37 #define SHA256_DIGEST_SIZE 32
38 
39 typedef struct KeyPair {
40     Buffer *pubKey;
41     Buffer *priKey;
42 } KeyPair;
43 
44 typedef struct AesGcmParam {
45     Buffer *aad;
46     Buffer *iv;
47     Buffer *key;
48 } AesGcmParam;
49 
50 bool IsEd25519KeyPairValid(const KeyPair *keyPair);
51 void DestroyKeyPair(KeyPair *keyPair);
52 KeyPair *GenerateEd25519KeyPair(void);
53 int32_t Ed25519Sign(const KeyPair *keyPair, const Buffer *data, Buffer **sign);
54 int32_t Ed25519Verify(const Buffer *pubKey, const Buffer *data, const Buffer *sign);
55 
56 int32_t AesGcm256Encrypt(const Buffer *plaintext, const AesGcmParam *param, Buffer **ciphertext, Buffer **tag);
57 int32_t AesGcm256Decrypt(const Buffer *ciphertext, const AesGcmParam *param, const Buffer *tag, Buffer **plaintext);
58 
59 Buffer *DeriveDeviceKey(const Buffer *pinData, const Buffer *secret);
60 Buffer *Hkdf(const Buffer *salt, const Buffer *rootKey);
61 Buffer *Sha256Adaptor(const Buffer *data);
62 
63 int32_t HmacSha256(const Buffer *hmacKey, const Buffer *data, Buffer **hmac);
64 int32_t HmacSha512(const Buffer *hmacKey, const Buffer *data, Buffer **hmac);
65 
66 int32_t SecureRandom(uint8_t *buffer, uint32_t size);
67 
68 /* This is for example only, distribute key should be distributed in trusted environment between devices. */
69 int32_t GetDistributeKey(const Buffer *peerUdid, const Buffer *salt, Buffer **key);
70 
71 #ifdef __cplusplus
72 }
73 #endif // __cplusplus
74 #endif // ADAPTOR_ALGORITHM_H
75 
76