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 if (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 }
121
CovertData(struct Curve25519Structure * curve25519,uint8_t * pubkey,int len)122 static int32_t CovertData(struct Curve25519Structure *curve25519, uint8_t *pubkey, int len)
123 {
124 int32_t ret;
125 do {
126 ret = ConvertStringToInt(g_pBytes, P_BYTES, &curve25519->p);
127 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_pBytes big number failed!")
128 ret = ConvertStringToInt(g_dBytes, P_BYTES, &curve25519->d);
129 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_dBytes big number failed!")
130 ret = ConvertStringToInt(g_negativeTwoModPBytes, P_BYTES, &curve25519->negativeTwo);
131 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeTwoModPBytes big number failed!")
132 ret = ConvertStringToInt(g_negativeOneModPBytes, P_BYTES, &curve25519->negativeOne);
133 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeOneModPBytes big number failed!")
134 ret = ConvertStringToInt(g_negativeOneDivideTwoBytes, P_BYTES, &curve25519->negativeOneDivideTwo);
135 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to g_negativeOneDivideTwoBytes big number failed!")
136 ret = ConvertStringToInt(pubkey, len, &curve25519->ed25519Pubkey);
137 HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Convert to ed25519 big number failed!")
138 } while (0);
139
140 if (ret != HKS_SUCCESS) {
141 Curve25519Destroy(curve25519);
142 }
143
144 return ret;
145 }
146
Curve25519Initialize(struct Curve25519Structure * curve25519,const uint8_t * source,uint32_t sourceLen,bool isBigEndian)147 static int32_t Curve25519Initialize(struct Curve25519Structure *curve25519,
148 const uint8_t *source, uint32_t sourceLen, bool isBigEndian)
149 {
150 if (sourceLen != P_BYTES) {
151 HKS_LOG_E("invalid param input");
152 return HKS_ERROR_INVALID_ARGUMENT;
153 }
154
155 int32_t ret;
156 uint8_t pubKey[P_BYTES] = {0};
157 (void)memcpy_s(pubKey, P_BYTES - 1, source, sourceLen - 1); // the 0-30 bit assignment
158 pubKey[P_BYTES - 1] = source[P_BYTES - 1] & 0x7f; // the last bit assignment
159 SwapEndianThirtyTwoByte(pubKey, sizeof(pubKey), isBigEndian);
160
161 (void)memset_s(curve25519, sizeof(struct Curve25519Structure), 0, sizeof(struct Curve25519Structure));
162 ret = CovertData(curve25519, pubKey, sizeof(pubKey));
163 HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "convert binary data to big num failed!")
164 return ret;
165 }
166
FreeLocalBigVar(struct Curve25519Var * var)167 static void FreeLocalBigVar(struct Curve25519Var *var)
168 {
169 if (var->a != NULL) {
170 BN_free(var->a);
171 var->a = NULL;
172 }
173
174 if (var->b != NULL) {
175 BN_free(var->b);
176 var->b = NULL;
177 }
178
179 if (var->c != NULL) {
180 BN_free(var->c);
181 var->c = NULL;
182 }
183 }
184
Curve25519LocalVar(struct Curve25519Var * var)185 static int32_t Curve25519LocalVar(struct Curve25519Var *var)
186 {
187 int32_t ret = HKS_ERROR_BUFFER_TOO_SMALL;
188 do {
189 var->a = BN_new();
190 if (var->a == NULL) {
191 HKS_LOG_E("Big integer a is null!");
192 ret = HKS_ERROR_BUFFER_TOO_SMALL;
193 break;
194 }
195 var->b = BN_new();
196 if (var->b == NULL) {
197 HKS_LOG_E("Big integer b is null!");
198 ret = HKS_ERROR_BUFFER_TOO_SMALL;
199 break;
200 }
201 var->c = BN_new();
202 if (var->c == NULL) {
203 HKS_LOG_E("Big integer c is null!");
204 ret = HKS_ERROR_BUFFER_TOO_SMALL;
205 break;
206 }
207 ret = HKS_SUCCESS;
208 } while (0);
209
210 if (ret != HKS_SUCCESS) {
211 FreeLocalBigVar(var);
212 }
213
214 return ret;
215 }
216
CheckEd25519PubkeyPart(const struct Curve25519Structure * curve25519,struct Curve25519Var * var,BN_CTX * ctx,BIGNUM * tmpOne)217 static int32_t CheckEd25519PubkeyPart(const struct Curve25519Structure *curve25519, struct Curve25519Var *var,
218 BN_CTX *ctx, BIGNUM *tmpOne)
219 {
220 if (BN_set_word(tmpOne, 1) <= 0) {
221 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
222 }
223 if (BN_mod_add(var->b, var->b, tmpOne, curve25519->p, ctx) <= 0) {
224 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
225 }
226 if (BN_mod_exp(var->c, var->b, curve25519->negativeTwo, curve25519->p, ctx) <= 0) {
227 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
228 }
229 if (BN_mod_add(var->b, var->a, curve25519->negativeOne, curve25519->p, ctx) <= 0) {
230 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
231 }
232 if (BN_mod_mul(var->a, var->b, var->c, curve25519->p, ctx) <= 0) {
233 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
234 }
235 if (BN_mod_add(var->a, var->a, curve25519->p, curve25519->p, ctx) <= 0) {
236 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
237 }
238 if (BN_mod_exp(var->b, var->a, curve25519->negativeOneDivideTwo, curve25519->p, ctx) <= 0) {
239 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
240 }
241 return HKS_SUCCESS;
242 }
243
CheckEd25519Pubkey(const struct Curve25519Structure * curve25519,struct Curve25519Var * var,uint8_t flag,BN_CTX * ctx)244 static int32_t CheckEd25519Pubkey(const struct Curve25519Structure *curve25519, struct Curve25519Var *var,
245 uint8_t flag, BN_CTX *ctx)
246 {
247 int32_t res = HKS_ERROR_CRYPTO_ENGINE_ERROR;
248 uint32_t result = (uint32_t)(BN_cmp(curve25519->ed25519Pubkey, curve25519->p) < 0);
249 BIGNUM *tmpOne = BN_new();
250 HKS_IF_NULL_RETURN(tmpOne, res)
251
252 do {
253 if (BN_mod_sqr(var->a, curve25519->ed25519Pubkey, curve25519->p, ctx) <= 0) {
254 break;
255 }
256 if (BN_mod_mul(var->b, var->a, curve25519->d, curve25519->p, ctx) <= 0) {
257 break;
258 }
259 HKS_IF_NOT_SUCC_BREAK(CheckEd25519PubkeyPart(curve25519, var, ctx, tmpOne))
260 result &= (uint32_t)(BN_cmp(var->b, curve25519->negativeOneDivideTwo) < 0);
261 if (BN_mod_sub(var->a, var->a, curve25519->p, curve25519->p, ctx) <= 0) {
262 break;
263 }
264 if (BN_cmp(var->a, tmpOne) < 0) {
265 result ^= (0x1 & ((uint32_t)flag >> 7)); // 7: Get the sign bit of the last byte of the ed25519 pubkey
266 } else {
267 result ^= 0x0;
268 }
269 if (result == 0) {
270 break;
271 }
272 res = HKS_SUCCESS;
273 } while (0);
274 if (tmpOne != NULL) {
275 BN_free(tmpOne);
276 }
277 return res;
278 }
279
FillPubKeyByZero(uint8_t * pubKey,uint32_t * pubKeySize)280 static int32_t FillPubKeyByZero(uint8_t *pubKey, uint32_t *pubKeySize)
281 {
282 if (*pubKeySize < P_BYTES) {
283 uint8_t tmpKey[P_BYTES] = {0};
284 int baseAddr = P_BYTES - *pubKeySize;
285 (void)memcpy_s(tmpKey + baseAddr, P_BYTES - baseAddr, pubKey, *pubKeySize);
286 (void)memcpy_s(pubKey, P_BYTES, tmpKey, P_BYTES);
287 *pubKeySize = P_BYTES;
288 }
289 return HKS_SUCCESS;
290 }
291
BnOperationOfPubKeyConversion(const struct HksBlob * keyIn,struct HksBlob * keyOut,struct Curve25519Var * var,BIGNUM * numberOne,BN_CTX * ctx)292 static int32_t BnOperationOfPubKeyConversion(const struct HksBlob *keyIn, struct HksBlob *keyOut,
293 struct Curve25519Var *var, BIGNUM *numberOne, BN_CTX *ctx)
294 {
295 uint32_t tmpSize = keyOut->size;
296 uint8_t tmpKey[P_BYTES] = {0};
297 struct Curve25519Structure curve25519 = {0};
298 int32_t ret = Curve25519Initialize(&curve25519, keyIn->data, keyIn->size, true);
299 HKS_IF_NOT_SUCC_RETURN(ret, ret)
300 ret = HKS_ERROR_CRYPTO_ENGINE_ERROR;
301 do {
302 HKS_IF_NOT_SUCC_BREAK(CheckEd25519Pubkey(&curve25519, var, keyIn->data[keyIn->size - 1], ctx))
303 if (BN_set_word(numberOne, 1) <= 0) {
304 break;
305 }
306 if (BN_sub(var->a, curve25519.p, curve25519.ed25519Pubkey) <= 0) {
307 break;
308 }
309 if (BN_add(var->b, var->a, numberOne) <= 0) {
310 break;
311 }
312 if (BN_mod_exp(var->a, var->b, curve25519.negativeTwo, curve25519.p, ctx) <= 0) {
313 break;
314 }
315 if (BN_add(var->b, curve25519.ed25519Pubkey, numberOne) <= 0) {
316 break;
317 }
318 if (BN_mod_mul(var->c, var->a, var->b, curve25519.p, ctx) <= 0) {
319 break;
320 }
321 if (BN_bn2bin(var->c, tmpKey) <= 0) {
322 break;
323 }
324 tmpSize = (uint32_t)BN_num_bytes(var->c);
325 HKS_IF_NOT_SUCC_BREAK(FillPubKeyByZero(tmpKey, &tmpSize))
326 SwapEndianThirtyTwoByte(tmpKey, tmpSize, true);
327 if (memcpy_s(keyOut->data, keyOut->size, tmpKey, tmpSize) != EOK) {
328 break;
329 }
330 keyOut->size = tmpSize;
331 ret = HKS_SUCCESS;
332 } while (0);
333 Curve25519Destroy(&curve25519);
334 (void)memset_s(tmpKey, P_BYTES, 0, P_BYTES);
335 return ret;
336 }
337
ConvertPubkeyX25519FromED25519(const struct HksBlob * keyIn,struct HksBlob * keyOut)338 int32_t ConvertPubkeyX25519FromED25519(const struct HksBlob *keyIn, struct HksBlob *keyOut)
339 {
340 BN_CTX *ctx = BN_CTX_new();
341 HKS_IF_NULL_RETURN(ctx, HKS_ERROR_CRYPTO_ENGINE_ERROR)
342
343 struct Curve25519Var var = { NULL, NULL, NULL };
344 int32_t ret = Curve25519LocalVar(&var);
345 if (ret != HKS_SUCCESS) {
346 BN_CTX_free(ctx);
347 return ret;
348 }
349 BIGNUM *numberOne = BN_new();
350 ret = BnOperationOfPubKeyConversion(keyIn, keyOut, &var, numberOne, ctx);
351
352 BN_CTX_free(ctx);
353 BN_free(numberOne);
354 FreeLocalBigVar(&var);
355 return ret;
356 }
357
ConvertPrivX25519FromED25519(const struct HksBlob * keyIn,struct HksBlob * keyOut)358 int32_t ConvertPrivX25519FromED25519(const struct HksBlob *keyIn, struct HksBlob *keyOut)
359 {
360 uint32_t tmpSize = sizeof(struct KeyMaterial25519) + CURVE25519_KEY_LEN; // 2: pub + pri
361 struct KeyMaterial25519 *keyMaterialOut = (struct KeyMaterial25519 *)keyOut->data;
362 keyMaterialOut->keySize = tmpSize;
363 keyMaterialOut->pubKeySize = 0;
364 keyMaterialOut->priKeySize = CURVE25519_KEY_LEN;
365 uint32_t offset = sizeof(struct KeyMaterial25519);
366
367 uint8_t *input = keyIn->data + tmpSize;
368 const uint32_t inputLen = CURVE25519_KEY_LEN; // Get 32 bytes private key data as the hash input
369 uint8_t digest[ED25519_FIX_KEY_BUFFER_SIZE] = {0};
370 uint32_t digestLen = ED25519_FIX_KEY_BUFFER_SIZE;
371
372 if (EVP_Digest(input, inputLen, digest, &digestLen, EVP_sha512(), NULL) <= 0) {
373 HksLogOpensslError();
374 return HKS_ERROR_CRYPTO_ENGINE_ERROR;
375 }
376
377 if (memcpy_s(keyOut->data + offset, keyMaterialOut->priKeySize, digest,
378 digestLen / 2) != EOK) { // 2 : used to calculate half of the digest length
379 (void)memset_s(digest, digestLen, 0, digestLen);
380 HKS_LOG_E("copy digest data to output key failed");
381 return HKS_ERROR_INSUFFICIENT_MEMORY;
382 }
383
384 // 248 127 64 are the constant value of x25 to ed25 algorithm
385 keyOut->size = keyMaterialOut->keySize;
386 keyOut->data[offset] &= 248; // 248: RFC 8032
387 keyOut->data[keyMaterialOut->keySize - 1] &= 127; // 127: RFC 8032
388 keyOut->data[keyMaterialOut->keySize - 1] |= 64; // 64: RFC 8032
389 (void)memset_s(digest, digestLen, 0, digestLen);
390 return HKS_SUCCESS;
391 }
392