• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "hks_openssl_ed25519tox25519.h"
17 
18 #include <openssl/bn.h>
19 #include <openssl/evp.h>
20 #include <stdbool.h>
21 #include <stddef.h>
22 
23 #include "hks_crypto_hal.h"
24 #include "hks_log.h"
25 #include "hks_openssl_engine.h"
26 #include "hks_template.h"
27 #include "securec.h"
28 
29 #define CURVE25519_KEY_LEN 32
30 #define CURVE25519_KEY_BITS 256
31 #define HKS_OPENSSL_ERROR_LEN 128
32 
33 #define P_BITS 256 // 255 significant bits + 1 for carry
34 #define P_BYTES 32 // 32 bytes
35 #define ED25519_FIX_KEY_BUFFER_SIZE 64
36 
37 // RFC standered implement
38 // The prime number: 2^255 - 19
39 static const unsigned char g_pBytes[P_BYTES] = {
40     0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0:p */
41     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
42     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xed
43 };
44 
45 // A non-zero element in the finite field
46 static const unsigned char g_dBytes[P_BYTES] = {
47     0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00,
48     0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52
49 };
50 
51 // The large number of (-2 mod p)
52 static const unsigned char g_negativeTwoModPBytes[P_BYTES] = {
53     0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
54     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xeb
55 };
56 
57 // The large number of (-1 mod p)
58 static const unsigned char g_negativeOneModPBytes[P_BYTES] = {
59     0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
60     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
61 };
62 
63 // The large number of (-1 / 2)
64 static const unsigned char g_negativeOneDivideTwoBytes[P_BYTES] = {
65     0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
66     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f
67 };
68 
ConvertStringToInt(const uint8_t * param,uint32_t paraLen,BIGNUM ** bigNum)69 static int32_t ConvertStringToInt(const uint8_t *param, uint32_t paraLen, BIGNUM **bigNum)
70 {
71     *bigNum = BN_bin2bn(param, paraLen, NULL);
72     HKS_IF_NULL_LOGE_RETURN(*bigNum, HKS_ERROR_BUFFER_TOO_SMALL, "failed to translate octet string into big integer!")
73 
74     return HKS_SUCCESS;
75 }
76 
FreeBigInt(BIGNUM ** bigInt)77 static void FreeBigInt(BIGNUM **bigInt)
78 {
79     BN_free(*bigInt);
80     *bigInt = NULL;
81 }
82 
Curve25519Destroy(struct Curve25519Structure * curve25519)83 static void Curve25519Destroy(struct Curve25519Structure *curve25519)
84 {
85     if (curve25519->p != NULL) {
86         FreeBigInt(&curve25519->p);
87     }
88 
89     if (curve25519->d != NULL) {
90         FreeBigInt(&curve25519->d);
91     }
92 
93     if (curve25519->negativeTwo != NULL) {
94         FreeBigInt(&curve25519->negativeTwo);
95     }
96 
97     if (curve25519->negativeOne != NULL) {
98         FreeBigInt(&curve25519->negativeOne);
99     }
100 
101     if (curve25519->negativeOneDivideTwo != NULL) {
102         FreeBigInt(&curve25519->negativeOneDivideTwo);
103     }
104 
105     if (curve25519->ed25519Pubkey != NULL) {
106         BN_clear(curve25519->ed25519Pubkey);
107         FreeBigInt(&curve25519->ed25519Pubkey);
108     }
109 }
110 
SwapEndianThirtyTwoByte(uint8_t * pubkey,int len,bool isBigEndian)111 static void SwapEndianThirtyTwoByte(uint8_t *pubkey, int len, bool isBigEndian)
112 {
113     HKS_IF_NOT_TRUE_RETURN_VOID(isBigEndian)
114     for (int i = 0; i < len / 2; ++i) { // 2: get the middle position of the string
115         uint8_t tmp = pubkey[i];
116         pubkey[i] = pubkey[len - i - 1];
117         pubkey[len - i - 1] = tmp;
118     }
119 }
120 
CovertData(struct Curve25519Structure * curve25519,uint8_t * pubkey,int len)121 static int32_t CovertData(struct Curve25519Structure *curve25519, uint8_t *pubkey, int len)
122 {
123     int32_t ret;
124     do {
125         ret = ConvertStringToInt(g_pBytes, P_BYTES, &curve25519->p);
126         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_pBytes big number failed!")
127         ret = ConvertStringToInt(g_dBytes, P_BYTES, &curve25519->d);
128         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_dBytes big number failed!")
129         ret = ConvertStringToInt(g_negativeTwoModPBytes, P_BYTES, &curve25519->negativeTwo);
130         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeTwoModPBytes big number failed!")
131         ret = ConvertStringToInt(g_negativeOneModPBytes, P_BYTES, &curve25519->negativeOne);
132         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeOneModPBytes big number failed!")
133         ret = ConvertStringToInt(g_negativeOneDivideTwoBytes, P_BYTES, &curve25519->negativeOneDivideTwo);
134         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeOneDivideTwoBytes big number failed!")
135         ret = ConvertStringToInt(pubkey, len, &curve25519->ed25519Pubkey);
136         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to ed25519 big number failed!")
137     } while (0);
138 
139     if (ret != HKS_SUCCESS) {
140         Curve25519Destroy(curve25519);
141     }
142 
143     return ret;
144 }
145 
Curve25519Initialize(struct Curve25519Structure * curve25519,const uint8_t * source,uint32_t sourceLen,bool isBigEndian)146 static int32_t Curve25519Initialize(struct Curve25519Structure *curve25519,
147     const uint8_t *source, uint32_t sourceLen, bool isBigEndian)
148 {
149     HKS_IF_TRUE_LOGE_RETURN(sourceLen != P_BYTES, HKS_ERROR_INVALID_ARGUMENT, "invalid param input")
150 
151     int32_t ret;
152     uint8_t pubKey[P_BYTES] = {0};
153     (void)memcpy_s(pubKey, P_BYTES - 1, source, sourceLen - 1); // the 0-30 bit assignment
154     pubKey[P_BYTES - 1] = source[P_BYTES - 1] & 0x7f; // the last bit assignment
155     SwapEndianThirtyTwoByte(pubKey, sizeof(pubKey), isBigEndian);
156 
157     (void)memset_s(curve25519, sizeof(struct Curve25519Structure), 0, sizeof(struct Curve25519Structure));
158     ret = CovertData(curve25519, pubKey, sizeof(pubKey));
159     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "convert binary data to big num failed!")
160     return ret;
161 }
162 
FreeLocalBigVar(struct Curve25519Var * var)163 static void FreeLocalBigVar(struct Curve25519Var *var)
164 {
165     if (var->a != NULL) {
166         BN_free(var->a);
167         var->a = NULL;
168     }
169 
170     if (var->b != NULL) {
171         BN_free(var->b);
172         var->b = NULL;
173     }
174 
175     if (var->c != NULL) {
176         BN_free(var->c);
177         var->c = NULL;
178     }
179 }
180 
Curve25519LocalVar(struct Curve25519Var * var)181 static int32_t Curve25519LocalVar(struct Curve25519Var *var)
182 {
183     int32_t ret = HKS_ERROR_BUFFER_TOO_SMALL;
184     do {
185         var->a = BN_new();
186         if (var->a == NULL) {
187             HKS_LOG_E("Big integer a is null!");
188             ret = HKS_ERROR_BUFFER_TOO_SMALL;
189             break;
190         }
191         var->b = BN_new();
192         if (var->b == NULL) {
193             HKS_LOG_E("Big integer b is null!");
194             ret = HKS_ERROR_BUFFER_TOO_SMALL;
195             break;
196         }
197         var->c = BN_new();
198         if (var->c == NULL) {
199             HKS_LOG_E("Big integer c is null!");
200             ret = HKS_ERROR_BUFFER_TOO_SMALL;
201             break;
202         }
203         ret = HKS_SUCCESS;
204     } while (0);
205 
206     if (ret != HKS_SUCCESS) {
207         FreeLocalBigVar(var);
208     }
209 
210     return ret;
211 }
212 
CheckEd25519PubkeyPart(const struct Curve25519Structure * curve25519,struct Curve25519Var * var,BN_CTX * ctx,BIGNUM * tmpOne)213 static int32_t CheckEd25519PubkeyPart(const struct Curve25519Structure *curve25519, struct Curve25519Var *var,
214     BN_CTX *ctx, BIGNUM *tmpOne)
215 {
216     if (BN_set_word(tmpOne, 1) <= 0) {
217         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
218     }
219     if (BN_mod_add(var->b, var->b, tmpOne, curve25519->p, ctx) <= 0) {
220         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
221     }
222     if (BN_mod_exp(var->c, var->b, curve25519->negativeTwo, curve25519->p, ctx) <= 0) {
223         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
224     }
225     if (BN_mod_add(var->b, var->a, curve25519->negativeOne, curve25519->p, ctx) <= 0) {
226         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
227     }
228     if (BN_mod_mul(var->a, var->b, var->c, curve25519->p, ctx) <= 0) {
229         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
230     }
231     if (BN_mod_add(var->a, var->a, curve25519->p, curve25519->p, ctx) <= 0) {
232         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
233     }
234     if (BN_mod_exp(var->b, var->a, curve25519->negativeOneDivideTwo, curve25519->p, ctx) <= 0) {
235         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
236     }
237     return HKS_SUCCESS;
238 }
239 
CheckEd25519Pubkey(const struct Curve25519Structure * curve25519,struct Curve25519Var * var,uint8_t flag,BN_CTX * ctx)240 static int32_t CheckEd25519Pubkey(const struct Curve25519Structure *curve25519, struct Curve25519Var *var,
241     uint8_t flag, BN_CTX *ctx)
242 {
243     int32_t res = HKS_ERROR_CRYPTO_ENGINE_ERROR;
244     uint32_t result = (uint32_t)(BN_cmp(curve25519->ed25519Pubkey, curve25519->p) < 0);
245     BIGNUM *tmpOne = BN_new();
246     HKS_IF_NULL_RETURN(tmpOne, res)
247 
248     do {
249         if (BN_mod_sqr(var->a, curve25519->ed25519Pubkey, curve25519->p, ctx) <= 0) {
250             break;
251         }
252         if (BN_mod_mul(var->b, var->a, curve25519->d, curve25519->p, ctx) <= 0) {
253             break;
254         }
255         HKS_IF_NOT_SUCC_BREAK(CheckEd25519PubkeyPart(curve25519, var, ctx, tmpOne))
256         result &= (uint32_t)(BN_cmp(var->b, curve25519->negativeOneDivideTwo) < 0);
257         if (BN_mod_sub(var->a, var->a, curve25519->p, curve25519->p, ctx) <= 0) {
258             break;
259         }
260         // 7: Get the sign bit of the last byte of the ed25519 pubkey
261         result = result ^ (BN_cmp(var->a, tmpOne) < 0 ? (0x1 & ((uint32_t)flag >> 7)) : 0x0);
262         HKS_IF_TRUE_BREAK(result == 0)
263         res = HKS_SUCCESS;
264     } while (0);
265     if (tmpOne != NULL) {
266         BN_free(tmpOne);
267     }
268     return res;
269 }
270 
FillPubKeyByZero(uint8_t * pubKey,uint32_t * pubKeySize)271 static int32_t FillPubKeyByZero(uint8_t *pubKey, uint32_t *pubKeySize)
272 {
273     HKS_IF_TRUE_RETURN(*pubKeySize >= P_BYTES, HKS_SUCCESS)
274 
275     uint8_t tmpKey[P_BYTES] = {0};
276     int baseAddr = P_BYTES - *pubKeySize;
277     (void)memcpy_s(tmpKey + baseAddr, P_BYTES - baseAddr, pubKey, *pubKeySize);
278     (void)memcpy_s(pubKey, P_BYTES, tmpKey, P_BYTES);
279     *pubKeySize = P_BYTES;
280     return HKS_SUCCESS;
281 }
282 
BnOperationOfPubKeyConversion(const struct HksBlob * keyIn,struct HksBlob * keyOut,struct Curve25519Var * var,BIGNUM * numberOne,BN_CTX * ctx)283 static int32_t BnOperationOfPubKeyConversion(const struct HksBlob *keyIn, struct HksBlob *keyOut,
284     struct Curve25519Var *var, BIGNUM *numberOne, BN_CTX *ctx)
285 {
286     uint8_t tmpKey[P_BYTES] = {0};
287     struct Curve25519Structure curve25519 = {0};
288     int32_t ret = Curve25519Initialize(&curve25519, keyIn->data, keyIn->size, true);
289     HKS_IF_NOT_SUCC_RETURN(ret, ret)
290     ret = HKS_ERROR_CRYPTO_ENGINE_ERROR;
291     do {
292         HKS_IF_NOT_SUCC_BREAK(CheckEd25519Pubkey(&curve25519, var, keyIn->data[keyIn->size - 1], ctx))
293         if (BN_set_word(numberOne, 1) <= 0) {
294             break;
295         }
296         if (BN_sub(var->a, curve25519.p, curve25519.ed25519Pubkey) <= 0) {
297             break;
298         }
299         if (BN_add(var->b, var->a, numberOne) <= 0) {
300             break;
301         }
302         if (BN_mod_exp(var->a, var->b, curve25519.negativeTwo, curve25519.p, ctx) <= 0) {
303             break;
304         }
305         if (BN_add(var->b, curve25519.ed25519Pubkey, numberOne) <= 0) {
306             break;
307         }
308         if (BN_mod_mul(var->c, var->a, var->b, curve25519.p, ctx) <= 0) {
309             break;
310         }
311         if (BN_bn2bin(var->c, tmpKey) <= 0) {
312             break;
313         }
314         uint32_t tmpSize = (uint32_t)BN_num_bytes(var->c);
315         HKS_IF_NOT_SUCC_BREAK(FillPubKeyByZero(tmpKey, &tmpSize))
316         SwapEndianThirtyTwoByte(tmpKey, tmpSize, true);
317         if (memcpy_s(keyOut->data, keyOut->size, tmpKey, tmpSize) != EOK) {
318             break;
319         }
320         keyOut->size = tmpSize;
321         ret = HKS_SUCCESS;
322     } while (0);
323     Curve25519Destroy(&curve25519);
324     (void)memset_s(tmpKey, P_BYTES, 0, P_BYTES);
325     return ret;
326 }
327 
ConvertPubkeyX25519FromED25519(const struct HksBlob * keyIn,struct HksBlob * keyOut)328 int32_t ConvertPubkeyX25519FromED25519(const struct HksBlob *keyIn, struct HksBlob *keyOut)
329 {
330     uint32_t tmpSize = sizeof(struct KeyMaterial25519) + CURVE25519_KEY_LEN;
331     if (keyOut->size < tmpSize) {
332         return HKS_ERROR_INVALID_ARGUMENT;
333     }
334     struct KeyMaterial25519 *keyMaterialOut = (struct KeyMaterial25519 *)keyOut->data;
335     keyMaterialOut->keyAlg = HKS_ALG_X25519;
336     keyMaterialOut->keySize = HKS_CURVE25519_KEY_SIZE_256;
337     keyMaterialOut->pubKeySize = CURVE25519_KEY_LEN;
338     keyMaterialOut->priKeySize = 0;
339     keyMaterialOut->reserved = 0;
340     struct HksBlob outPubKey = { CURVE25519_KEY_LEN, keyOut->data + sizeof(struct KeyMaterial25519) };
341 
342     BN_CTX *ctx = BN_CTX_new();
343     HKS_IF_NULL_RETURN(ctx, HKS_ERROR_CRYPTO_ENGINE_ERROR)
344 
345     int32_t ret = 0;
346     struct Curve25519Var var = { NULL, NULL, NULL };
347     BIGNUM *numberOne = BN_new();
348     do {
349         if (numberOne == NULL) {
350             ret = HKS_ERROR_MALLOC_FAIL;
351             break;
352         }
353         ret = Curve25519LocalVar(&var);
354         HKS_IF_NOT_SUCC_BREAK(ret)
355         ret = BnOperationOfPubKeyConversion(keyIn, &outPubKey, &var, numberOne, ctx);
356     } while (0);
357 
358     if (ctx != NULL) {
359         BN_CTX_free(ctx);
360     }
361     if (numberOne != NULL) {
362         BN_free(numberOne);
363     }
364     FreeLocalBigVar(&var);
365     return ret;
366 }
367 
ConvertPrivX25519FromED25519(const struct HksBlob * keyIn,struct HksBlob * keyOut)368 int32_t ConvertPrivX25519FromED25519(const struct HksBlob *keyIn, struct HksBlob *keyOut)
369 {
370     uint32_t tmpSize = sizeof(struct KeyMaterial25519) + CURVE25519_KEY_LEN;
371     uint32_t totalSize = sizeof(struct KeyMaterial25519) + CURVE25519_KEY_LEN * 2; // 2: private key and public key
372     if (keyIn->size < totalSize || keyOut->size < tmpSize) {
373         HKS_LOG_E("Invalid keyInSize=%" LOG_PUBLIC "u or keyOutSize=%" LOG_PUBLIC "u", keyIn->size, keyOut->size);
374         return HKS_ERROR_INVALID_ARGUMENT;
375     }
376     struct KeyMaterial25519 *keyMaterialOut = (struct KeyMaterial25519 *)keyOut->data;
377     keyMaterialOut->keyAlg = HKS_ALG_X25519;
378     keyMaterialOut->keySize = HKS_CURVE25519_KEY_SIZE_256;
379     keyMaterialOut->pubKeySize = 0;
380     keyMaterialOut->priKeySize = CURVE25519_KEY_LEN;
381     keyMaterialOut->reserved = 0;
382     uint32_t offset = sizeof(struct KeyMaterial25519);
383 
384     uint8_t *input = keyIn->data + tmpSize;
385     const uint32_t inputLen = CURVE25519_KEY_LEN; // Get 32 bytes private key data as the hash input
386     uint8_t digest[ED25519_FIX_KEY_BUFFER_SIZE] = {0};
387     uint32_t digestLen = ED25519_FIX_KEY_BUFFER_SIZE;
388 
389     if (EVP_Digest(input, inputLen, digest, &digestLen, EVP_sha512(), NULL) <= 0) {
390         HksLogOpensslError();
391         return HKS_ERROR_CRYPTO_ENGINE_ERROR;
392     }
393 
394     if (memcpy_s(keyOut->data + offset, keyMaterialOut->priKeySize, digest,
395         digestLen / 2) != EOK) { // 2 : used to calculate half of the digest length
396         (void)memset_s(digest, digestLen, 0, digestLen);
397         HKS_LOG_E("copy digest data to output key failed");
398         return HKS_ERROR_INSUFFICIENT_MEMORY;
399     }
400 
401     // 248 127 64 are the constant value of x25 to ed25 algorithm
402     keyOut->size = tmpSize;
403     keyOut->data[offset] &= 248; // 248: RFC 8032
404     keyOut->data[tmpSize - 1] &= 127; // 127: RFC 8032
405     keyOut->data[tmpSize - 1] |= 64;  // 64: RFC 8032
406     (void)memset_s(digest, digestLen, 0, digestLen);
407     return HKS_SUCCESS;
408 }
409