-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUID_utils.c
More file actions
419 lines (390 loc) · 12.7 KB
/
UID_utils.c
File metadata and controls
419 lines (390 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
* Copyright (c) 2016-2018. Uniquid Inc. or its affiliates. All Rights Reserved.
*
* License is in the "LICENSE" file accompanying this file.
* See the License for the specific language governing permissions and limitations under the License.
*/
/*
* @file UID_utils.c
*
* @date 29/lug/2016
* @author M. Palumbi
*/
/**
* @file UID_utils.h
*
* Utilities functions to support IAM library
*
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "ecdsa.h"
#include "secp256k1.h"
#include "base58.h"
#include "base64.h"
#include "UID_utils.h"
/**
* Converts an hex string to a binary buffer
*
* buf must be provided at least strlen(str) / 2 bytes long
*
* @param[in] str string in hex format to convert
* @param[out] buf binary out buffer
* @param[in] len size in bytes of the out buffer
*
* @return number of bytes converted on success
* 0 if buffer too small
*/
size_t fromhex(const char *str, uint8_t *buf, size_t len)
{
uint8_t c;
size_t l = strlen(str) / 2;
if (l > len) return 0;
for (size_t i = 0; i < l; i++) {
c = 0;
if (str[i*2] >= '0' && str[i*2] <= '9') c += (str[i*2] - '0') << 4;
if (str[i*2] >= 'a' && str[i*2] <= 'f') c += (10 + str[i*2] - 'a') << 4;
if (str[i*2] >= 'A' && str[i*2] <= 'F') c += (10 + str[i*2] - 'A') << 4;
if (str[i*2+1] >= '0' && str[i*2+1] <= '9') c += (str[i*2+1] - '0');
if (str[i*2+1] >= 'a' && str[i*2+1] <= 'f') c += (10 + str[i*2+1] - 'a');
if (str[i*2+1] >= 'A' && str[i*2+1] <= 'F') c += (10 + str[i*2+1] - 'A');
buf[i] = c;
}
return l;
}
/**
* Converts len bytes from an hex string to a binary buffer
*
* buf must be provided at least len bytes long
*
* @param[in] str string in hex format to be converted
* @param[out] buf binary out buffer
* @param[in] len number of bytes to be converted
*
* @return address of the output buffer
*/
uint8_t *fromnhex(const char *str, uint8_t *buf, size_t len)
{
uint8_t c;
for (size_t i = 0; i < len; i++) {
c = 0;
if (str[i*2] >= '0' && str[i*2] <= '9') c += (str[i*2] - '0') << 4;
if (str[i*2] >= 'a' && str[i*2] <= 'f') c += (10 + str[i*2] - 'a') << 4;
if (str[i*2] >= 'A' && str[i*2] <= 'F') c += (10 + str[i*2] - 'A') << 4;
if (str[i*2+1] >= '0' && str[i*2+1] <= '9') c += (str[i*2+1] - '0');
if (str[i*2+1] >= 'a' && str[i*2+1] <= 'f') c += (10 + str[i*2+1] - 'a');
if (str[i*2+1] >= 'A' && str[i*2+1] <= 'F') c += (10 + str[i*2+1] - 'A');
buf[i] = c;
}
return buf;
}
/**
* Converts a binary buffer to a string in hexadecimal ascii representation
*
* buf must be provided at least 2 * l + 1 bytes long
*
* @param[in] bin input binary buffer
* @param[in] l number of bytes to be converted
* @param[out] buf buffer to be filled with the result
*
* @return string buffer holding the result
*/
char *tohex(const uint8_t *bin, size_t l, char *buf)
{
// char *buf = (char *)malloc(l * 2 + 1);
static char digits[] = "0123456789abcdef";
for (size_t i = 0; i < l; i++) {
buf[i*2 ] = digits[(bin[i] >> 4) & 0xF];
buf[i*2+1] = digits[bin[i] & 0xF];
}
buf[l * 2] = 0;
return buf;
}
/**
* Encode a varint (variable-lenght integer)
*
* out buffer must be at least 5 bytes in size
*
* @param[in] len unsigned integer to be converted
* @param[out] out buffer to be filled with the varint
*
* @return the varint lenght in bytes
*/
uint32_t ser_length(uint32_t len, uint8_t *out)
{
if (len < 253) {
out[0] = len & 0xFF;
return 1;
}
if (len < 0x10000) {
out[0] = 253;
out[1] = len & 0xFF;
out[2] = (len >> 8) & 0xFF;
return 3;
}
out[0] = 254;
out[1] = len & 0xFF;
out[2] = (len >> 8) & 0xFF;
out[3] = (len >> 16) & 0xFF;
out[4] = (len >> 24) & 0xFF;
return 5;
}
/**
* Initialize the bitcoin message hash
*
* @param[in] message_len total len of the message to be hashed (sum of all partial_len)
* @param[in] ctx cotntext to accumulate partial hashes
*/
void UID_hashMessage_init(size_t message_len, SHA256_CTX *ctx)
{
sha256_Init(ctx);
sha256_Update(ctx, (const uint8_t *)"\x18" "Bitcoin Signed Message:" "\n", 25);
uint8_t varint[5];
uint32_t l = ser_length(message_len, varint);
sha256_Update(ctx, varint, l);
}
/**
* Update the hash context with new data
*
* @param[in] partial_message partial message data
* @param[in] partial_len size of the partial message data
* @param[in] ctx cotntext to accumulate partial hashes
*/
void UID_hashMessage_update(char *partial_message, size_t partial_len, SHA256_CTX *ctx)
{
sha256_Update(ctx, (const uint8_t *)partial_message, partial_len);
}
/**
* Evaluate the hash of the message
*
* @param[out] hash buffer to be filled with the hash
* @param[in] ctx cotntext to accumulate partial hashes
*/
void UID_hashMessage_final(uint8_t hash[32], SHA256_CTX *ctx)
{
sha256_Final(ctx, hash);
sha256_Raw(hash, 32, hash);
}
/**
* Compute the bitcoin message signature \@specific BIP32 path from the hash
*
* @param[in] hash hash of the message to be signed
* @param[in] path BIP32 path
* @param[out] b64signature buffer to be filled with the signature (base64 coded NULL terminated string)
* @param[in] ssize size of the b64signature buffer
*
* @return UID_SIGN_OK if no error
*/
int UID_signMessageHash(uint8_t hash[32], UID_Bip32Path *path, char *b64signature, size_t ssize)
{
uint8_t signature[65] = {0};
uint8_t pby;
//int result = ecdsa_sign_digest(&secp256k1, privkey, hash, signature + 1, &pby);
int result = UID_signAt(path, hash, signature + 1, &pby);
if (result != UID_SIGN_OK) return UID_SIGN_FAILED;
signature[0] = 27 + pby + 4;
size_t olen = 0;
int ret;
ret = mbedtls_base64_encode((unsigned char *)b64signature, ssize, &olen, signature, sizeof(signature));
if (0 == ret) return UID_SIGN_OK;
return UID_SIGN_SMALL_BUFFER;
}
/**
* Compute the bitcoin message signature \@specific BIP32 path
*
* @param[in] message string holding the message to be signed
* @param[in] path BIP32 path
* @param[out] b64signature buffer to be filled with the signature (base64 coded NULL terminated string)
* @param[in] ssize size of the b64signature buffer
*
* @return UID_SIGN_OK if no error
*/
int UID_signMessage(char *message, UID_Bip32Path *path, char *b64signature, size_t ssize)
{
SHA256_CTX ctx;
size_t message_len;
uint8_t hash[32];
message_len = strlen(message);
UID_hashMessage_init(message_len, &ctx);
UID_hashMessage_update(message, message_len, &ctx);
UID_hashMessage_final(hash, &ctx);
return UID_signMessageHash(hash, path, b64signature, ssize);
}
/**
* Compute the bitcoin message signature
*
* @param[in] message buffer holding the message to be signed
* @param[in] message_len lenght of the message
* @param[in] privkey 32 byte long buffer holding the private key (raw binary)
* @param[out] signature 65 bytes long buffer to be filled with the signature
*
* @return 0 == no error
*/
int cryptoMessageSign(const uint8_t *message, size_t message_len, const uint8_t *privkey, uint8_t *signature)
{
SHA256_CTX ctx;
sha256_Init(&ctx);
sha256_Update(&ctx, (const uint8_t *)"\x18" "Bitcoin Signed Message:" "\n", 25);
uint8_t varint[5];
uint32_t l = ser_length(message_len, varint);
sha256_Update(&ctx, varint, l);
sha256_Update(&ctx, message, message_len);
uint8_t hash[32];
sha256_Final(&ctx, hash);
sha256_Raw(hash, 32, hash);
uint8_t pby;
int result = ecdsa_sign_digest(&secp256k1, privkey, hash, signature + 1, &pby);
if (result == 0) {
signature[0] = 27 + pby + 4;
}
return result;
}
/**
* Verify the signature of a bitcoin message
*
* @param[in] message string containing the message
* @param[in] b64signature signature base64 coded
* @param[in] address bitcoin address
*
* @return UID_SIGN_OK == signature match
*/
int UID_verifyMessage(char *message, char *b64signature, char *address)
{
uint8_t signature_bin[65] = {0};
size_t size = 0;
int ret;
ret = mbedtls_base64_decode(signature_bin, sizeof(signature_bin), &size, (unsigned char *)b64signature, strlen(b64signature));
if(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL == ret) return UID_SIGN_SMALL_BUFFER;
if(0 != ret) return UID_SIGN_INVALID_CHARACTER;
ret = cryptoMessageVerify((uint8_t *)message, strlen(message), address, signature_bin);
return (0 == ret ? UID_SIGN_OK : UID_SIGN_VERIFY_ERROR);
}
/**
* Recover the address from the ash and signature
*
* @param[in] hash hash that was signed
* @param[in] b64signature recovery byte + signature base64 coded
* @param[out] address buffer to be filled with the address
*
* @return UID_SIGN_OK == address succesfully recovered
*/
int UID_addressFromSignedHash(uint8_t hash[32], char *b64signature, BTC_Address address)
{
bignum256 r, s, e;
curve_point cp, cp2;
uint8_t pubkey[65];
uint8_t signature[65] = {0};
int ret;
size_t size = 0;
// decode signature
ret = mbedtls_base64_decode(signature, sizeof(signature), &size, (unsigned char *)b64signature, strlen(b64signature));
if(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL == ret) return UID_SIGN_SMALL_BUFFER;
if(0 != ret) return UID_SIGN_INVALID_CHARACTER;
uint8_t nV = signature[0];
if (nV < 27 || nV >= 35) {
return UID_SIGN_INVALID_RECOVERY_BYTE;
}
bool compressed;
compressed = (nV >= 31);
if (compressed) {
nV -= 4;
}
uint8_t recid = nV - 27;
// read r and s
bn_read_be(signature + 1, &r);
bn_read_be(signature + 33, &s);
// x = r
memcpy(&cp.x, &r, sizeof(bignum256));
// compute y from x
uncompress_coords(&secp256k1, recid % 2, &cp.x, &cp.y);
// e = -hash
bn_read_be(hash, &e);
bn_subtract(&secp256k1.order, &e, &e);
// r = r^-1
bn_inverse(&r, &secp256k1.order);
point_multiply(&secp256k1, &s, &cp, &cp);
scalar_multiply(&secp256k1, &e, &cp2);
point_add(&secp256k1, &cp2, &cp);
point_multiply(&secp256k1, &r, &cp, &cp);
pubkey[0] = 0x04;
bn_write_be(&cp.x, pubkey + 1);
bn_write_be(&cp.y, pubkey + 33);
// check if the address is correct
if (compressed) {
pubkey[0] = 0x02 | (cp.y.val[0] & 0x01);
}
ecdsa_get_address(pubkey, /*version*/ NETWORK_BYTE, address, sizeof(BTC_Address));
return UID_SIGN_OK;
}
/**
* Verify the signature of a bitcoin message
*
* @param[in] message buffer holding the message to be verified
* @param[in] message_len lenght of the message
* @param[in] address bitcoin address against which verify the signature
* @param[in] signature 65 bytes long buffer holding the signature
*
* @return 0 == signature match
*/
int cryptoMessageVerify(const uint8_t *message, size_t message_len, const char *address, const uint8_t *signature)
{
bignum256 r, s, e;
curve_point cp, cp2;
SHA256_CTX ctx;
uint8_t pubkey[65], addr_raw[21], data[21], hash[32];
uint8_t nV = signature[0];
if (nV < 27 || nV >= 35) {
return 1;
}
bool compressed;
compressed = (nV >= 31);
if (compressed) {
nV -= 4;
}
uint8_t recid = nV - 27;
// read r and s
bn_read_be(signature + 1, &r);
bn_read_be(signature + 33, &s);
// x = r
memcpy(&cp.x, &r, sizeof(bignum256));
// compute y from x
uncompress_coords(&secp256k1, recid % 2, &cp.x, &cp.y);
// calculate hash
sha256_Init(&ctx);
sha256_Update(&ctx, (const uint8_t *)"\x18" "Bitcoin Signed Message:" "\n", 25);
uint8_t varint[5];
uint32_t l = ser_length(message_len, varint);
sha256_Update(&ctx, varint, l);
sha256_Update(&ctx, message, message_len);
sha256_Final(&ctx, hash);
sha256_Raw(hash, 32, hash);
// e = -hash
bn_read_be(hash, &e);
bn_subtract(&secp256k1.order, &e, &e);
// r = r^-1
bn_inverse(&r, &secp256k1.order);
point_multiply(&secp256k1, &s, &cp, &cp);
scalar_multiply(&secp256k1, &e, &cp2);
point_add(&secp256k1, &cp2, &cp);
point_multiply(&secp256k1, &r, &cp, &cp);
pubkey[0] = 0x04;
bn_write_be(&cp.x, pubkey + 1);
bn_write_be(&cp.y, pubkey + 33);
// check if the address is correct
if (compressed) {
pubkey[0] = 0x02 | (cp.y.val[0] & 0x01);
}
memset(data,0,sizeof(data));
base58_decode_check(address, data, sizeof(data));
ecdsa_get_address_raw(pubkey, data[0], addr_raw);
if (memcmp(addr_raw, data, 21) != 0) {
return 2;
}
// check if signature verifies the digest
if (ecdsa_verify_digest(&secp256k1, pubkey, signature + 1, hash) != 0) {
return 3;
}
return 0;
}