aboutsummaryrefslogtreecommitdiff
path: root/src/noscrypt.c
blob: a24c804f1c4caa7068ca01357f068b50275aab35 (plain)
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
/*
* Copyright (c) 2024 Vaughn Nugent
*
* Package: noscrypt
* File: noscrypt.c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or  (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with NativeHeapApi. If not, see http://www.gnu.org/licenses/.
*/

#include "noscrypt.h"

#include <secp256k1_ecdh.h>
#include <secp256k1_schnorrsig.h>

//Setup mbedtls
#include <mbedtls/platform_util.h>
#include <mbedtls/md.h>
#include <mbedtls/hkdf.h>
#include <mbedtls/hmac_drbg.h>
#include <mbedtls/chacha20.h>
#include <mbedtls/sha256.h>
#include <mbedtls/constant_time.h>

/* Non win platforms may need an inline override */
#if !defined(_NC_IS_WINDOWS) && !defined(inline)
	#define inline __inline__
#endif // !IS_WINDOWS

//NULL
#ifndef NULL
	#define NULL ((void*)0)
#endif // !NULL

#define CHACHA_NONCE_SIZE 12	//Size of 12 is set by the cipher spec
#define CHACHA_KEY_SIZE 32		//Size of 32 is set by the cipher spec

/*
* Local macro for secure zero buffer fill
*/
#define ZERO_FILL(x, size) mbedtls_platform_zeroize(x, size) 

//Include string for memmove
#include <string.h>
#define MEMMOV(dst, src, size) memmove(dst, src, size)

/*
* Validation macros
*/

#ifndef NC_INPUT_VALIDATION_OFF
	#define CHECK_INVALID_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_INVALID_ARG, argPos);
	#define CHECK_NULL_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_NULL_PTR, argPos);
	#define CHECK_ARG_RANGE(x, min, max, argPos) if(x < min || x > max) return NCResultWithArgPosition(E_ARGUMENT_OUT_OF_RANGE, argPos);
#else
	//empty macros 
	#define CHECK_INVALID_ARG(x)
	#define CHECK_NULL_ARG(x, argPos) 
	#define CHECK_ARG_RANGE(x, min, max, argPos) 
#endif // !NC_DISABLE_INPUT_VALIDATION


#ifdef DEBUG
	/* Must include assert.h for assertions */
	#include <assert.h> 
	#define DEBUG_ASSERT(x) assert(x);
	#define DEBUG_ASSERT2(x, message) assert(x && message);	

	/*
	* Compiler enabled static assertion keywords are 
	* only available in C11 and later. Later versions 
	* have macros built-in from assert.h so we can use
	* the static_assert macro directly.
	* 
	* Static assertions are only used for testing such as 
	* sanity checks and this library targets the c89 standard
	* so static_assret very likely will not be available. 
	*/
	#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
		#define STATIC_ASSERT(x, m) static_assert(x, m)
	#else
		#define STATIC_ASSERT(x, m)
		#pragma message("Static assertions are not supported by this language version")
	#endif

#else
	#define DEBUG_ASSERT(x)
	#define DEBUG_ASSERT2(x, message)
	#define STATIC_ASSERT(x, m)
#endif

struct shared_secret {
	uint8_t value[NC_SHARED_SEC_SIZE];
};

struct conversation_key {
	uint8_t value[NC_CONV_KEY_SIZE];
};

struct message_key {
	uint8_t value[NC_MESSAGE_KEY_SIZE];
};

/*
* The following struct layout is exactly the same as 
* the message key, they may be typecasted to each other.
* as long as the size is the same.
*/
struct nc_expand_keys {
	uint8_t chacha_key[CHACHA_KEY_SIZE];
	uint8_t chacha_nonce[CHACHA_NONCE_SIZE];
	uint8_t hmac_key[NC_HMAC_KEY_SIZE];
};

/* Pointer typecast must work between expanded keys 
* and message key, size must be identical to work 
*/
STATIC_ASSERT(sizeof(struct nc_expand_keys) == sizeof(struct message_key), "Expected struct nc_expand_keys to be the same size as struct message_key");

/*
* Internal helper functions to do common structure conversions
*/

static inline int _convertToXonly(const NCContext* ctx, const NCPublicKey* compressedPubKey, secp256k1_xonly_pubkey* xonly)
{
	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte key structure")
	DEBUG_ASSERT2(xonly != NULL, "Expected valid X-only secp256k1 public key structure ")

	//Parse the public key into the x-only structure
	return secp256k1_xonly_pubkey_parse(ctx->secpCtx, xonly, compressedPubKey->key);
}

static int _convertToPubKey(const NCContext* ctx, const NCPublicKey* compressedPubKey, secp256k1_pubkey* pubKey)
{
	int result;
	uint8_t compressed[sizeof(NCPublicKey) + 1];

	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte key structure")
	DEBUG_ASSERT2(pubKey != NULL, "Expected valid secp256k1 public key structure")

	//Set the first byte to 0x02 to indicate a compressed public key
	compressed[0] = BIP340_PUBKEY_HEADER_BYTE;

	//Copy the compressed public key data into a new buffer (offset by 1 to store the header byte)
	MEMMOV((compressed + 1), compressedPubKey, sizeof(NCPublicKey));

	result = secp256k1_ec_pubkey_parse(ctx->secpCtx, pubKey, compressed, sizeof(compressed));

	//zero everything
	ZERO_FILL(compressed, sizeof(compressed));

	return result;
}

static inline int _convertFromXonly(const NCContext* ctx, const secp256k1_xonly_pubkey* xonly, NCPublicKey* compressedPubKey)
{
	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(xonly != NULL, "Expected valid X-only secp256k1 public key structure.")
	DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte pubkey structure")

	return secp256k1_xonly_pubkey_serialize(ctx->secpCtx, compressedPubKey->key, xonly);
}

/*
* IMPL NOTES:
* This callback function will be invoked by the ecdh function to hash the shared point.
*
* For nostr, this operation is defined in the new NIP-44 spec here:
* https://github.com/nostr-protocol/nips/blob/master/44.md#encryption
*
* The x coordinate of the shared point is copied directly into the output buffer. No hashing is
* performed here. The y coordinate is not used, and for this implementation, there is no data
* pointer.
*/
static int _edhHashFuncInternal(
	unsigned char* output,
	const uint8_t* x32,
	const uint8_t* y32,
	void* data
)
{
	((void)y32);	//unused for nostr
	((void)data);

	DEBUG_ASSERT2(output != NULL, "Expected valid output buffer")
	DEBUG_ASSERT2(x32 != NULL, "Expected a valid public 32byte x-coodinate buffer")

	//Copy the x coordinate of the shared point into the output buffer
	MEMMOV(output, x32, 32);

	return 32;	//Return the number of bytes written to the output buffer
}

static NCResult _computeSharedSecret(
	const NCContext* ctx,
	const NCSecretKey* sk,
	const NCPublicKey* otherPk,
	struct shared_secret* sharedPoint
)
{
	int result;
	secp256k1_pubkey pubKey;

	DEBUG_ASSERT(ctx != NULL)
	DEBUG_ASSERT(sk != NULL)
	DEBUG_ASSERT(otherPk != NULL)
	DEBUG_ASSERT(sharedPoint != NULL)

	//Recover pubkey from compressed public key data
	if (_convertToPubKey(ctx, otherPk, &pubKey) != 1)
	{
		return E_INVALID_ARG;
	}

	/*
	* Compute the shared point using the ecdh function.
	*
	* The above callback is invoked to "compute" the hash (it
	* copies the x coord) and it does not use the data pointer
	* so it is set to NULL.
	*/
	result = secp256k1_ecdh(
		ctx->secpCtx,
		(uint8_t*)sharedPoint,
		&pubKey,
		sk->key,
		&_edhHashFuncInternal,
		NULL
	);

	//Clean up sensitive data
	ZERO_FILL(&pubKey, sizeof(pubKey));

	//Result should be 1 on success
	return result > 0 ? NC_SUCCESS : E_OPERATION_FAILED;
}

static inline const mbedtls_md_info_t* _getSha256MdInfo(void)
{
	const mbedtls_md_info_t* info;
	//Get sha256 md info for hdkf operations
	info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
	DEBUG_ASSERT2(info != NULL, "Expected SHA256 md info struct to be valid")
	return info;
}


static inline NCResult _computeConversationKey(
	const NCContext* ctx, 
	const mbedtls_md_info_t* mdInfo,
	const struct shared_secret* sharedSecret,
	struct conversation_key* ck 
)
{
	int opResult;
	//Validate internal args
	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(sharedSecret != NULL, "Expected a valid shared-point")
	DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md context")
	DEBUG_ASSERT2(ck != NULL, "Expected a valid conversation key")
	
	//Derive the encryption key
	opResult = mbedtls_hkdf_extract(
		mdInfo,
		Nip44ConstantSalt,
		sizeof(Nip44ConstantSalt),
		(uint8_t*)sharedSecret,			//Shared secret is the input key
		NC_SHARED_SEC_SIZE,
		(uint8_t*)ck					//Output produces a conversation key
	);

	//Return success if the hkdf operation was successful
	return opResult == 0 ? NC_SUCCESS : E_OPERATION_FAILED;
}


/*
* Explode the hkdf into the chacha key, chacha nonce, and hmac key.
*/
static inline const struct nc_expand_keys* _expandKeysFromHkdf(const struct message_key* hkdf)
{
	return (const struct nc_expand_keys*)hkdf;
}

static int _chachaEncipher(const struct nc_expand_keys* keys, NCCryptoData* args)
{
	DEBUG_ASSERT2(keys != NULL, "Expected valid keys")
	DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")

	return mbedtls_chacha20_crypt(
		keys->chacha_key,
		keys->chacha_nonce,
		0,						//Counter (always starts at 0)
		args->dataSize,			//Data size (input and output are assumed to be the same size)
		args->inputData,		//Input data
		args->outputData		//Output data
	);
}

static inline NCResult _getMessageKey(
	const mbedtls_md_info_t* mdInfo,
	const struct conversation_key* converstationKey, 
	const uint8_t* nonce, 
	size_t nonceSize,
	struct message_key* messageKey
)
{
	int result;
	DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md context")
	DEBUG_ASSERT2(nonce != NULL, "Expected valid nonce buffer")
	DEBUG_ASSERT2(converstationKey != NULL, "Expected valid conversation key")
	DEBUG_ASSERT2(messageKey != NULL, "Expected valid message key buffer")

	//Another HKDF to derive the message key with nonce
	result = mbedtls_hkdf_expand(
		mdInfo,
		(uint8_t*)converstationKey,			//Conversation key is the input key
		NC_CONV_KEY_SIZE,
		nonce,
		nonceSize,
		(uint8_t*)messageKey,				//Output produces a message key (write it directly to struct memory)
		NC_MESSAGE_KEY_SIZE
	);

	return result == 0 ? NC_SUCCESS : E_OPERATION_FAILED;
}

static inline NCResult _encryptEx(
	const NCContext* ctx, 
	const mbedtls_md_info_t* mdINfo,
	const struct conversation_key* ck, 
	uint8_t hmacKey[NC_HMAC_KEY_SIZE],
	NCCryptoData* args
)
{
	NCResult result;
	struct message_key messageKey;
	const struct nc_expand_keys* expandedKeys;

	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(ck != NULL, "Expected valid conversation key")
	DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
	DEBUG_ASSERT2(mdINfo != NULL, "Expected valid md info struct")
	DEBUG_ASSERT2(hmacKey != NULL, "Expected valid hmac key buffer")

	//Failure, bail out
	if ((result = _getMessageKey(mdINfo, ck, args->nonce, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	//Expand the keys from the hkdf so we can use them in the cipher
	expandedKeys = _expandKeysFromHkdf(&messageKey);

	//Copy the hmac key into the args
	MEMMOV(hmacKey, expandedKeys->hmac_key, NC_HMAC_KEY_SIZE);

	//CHACHA20 (the result will be 0 on success)
	result = (NCResult)_chachaEncipher(expandedKeys, args);

Cleanup:
	//Clean up sensitive data
	ZERO_FILL(&messageKey, sizeof(messageKey));

	return result;
}

static inline NCResult _decryptEx(
	const NCContext* ctx, 
	const mbedtls_md_info_t* mdInfo,
	const struct conversation_key* ck,
	NCCryptoData* args
)
{
	NCResult result;
	struct message_key messageKey;
	const struct nc_expand_keys* cipherKeys;

	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(ck != NULL, "Expected valid conversation key")
	DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
	DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md info struct")	

	//Failure to get message keys, bail out
	if ((result = _getMessageKey(mdInfo, ck, args->nonce, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	//Expand the keys from the hkdf so we can use them in the cipher
	cipherKeys = _expandKeysFromHkdf(&messageKey);

	//CHACHA20 (the result will be 0 on success)
	result = (NCResult) _chachaEncipher(cipherKeys, args);

Cleanup:
	//Clean up sensitive data
	ZERO_FILL(&messageKey, sizeof(messageKey));

	return result;
}

static NCResult _verifyMacEx(
	const NCContext* ctx,
	const uint8_t conversationKey[NC_CONV_KEY_SIZE],
	NCMacVerifyArgs* args
)
{
	NCResult result;
	const mbedtls_md_info_t* sha256Info;
	const struct nc_expand_keys* keys;
	struct message_key messageKey;
	uint8_t hmacOut[NC_ENCRYPTION_MAC_SIZE];
 
	DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
	DEBUG_ASSERT2(conversationKey != NULL, "Expected valid conversation key")
	DEBUG_ASSERT2(args != NULL, "Expected valid mac verification args")

	sha256Info = _getSha256MdInfo();

	/*
	* We need to get the message key in order to
	* get the required hmac key
	*/
	result = _getMessageKey(
		sha256Info,
		(struct conversation_key*)conversationKey,
		args->nonce,
		NC_ENCRYPTION_NONCE_SIZE,
		&messageKey
	);

	if (result != NC_SUCCESS)
	{
		goto Cleanup;
	}

	/* Expand keys to get the hmac-key */
	keys = _expandKeysFromHkdf(&messageKey);

	/*
	* Compute the hmac of the data using the computed hmac key
	*/
	if (mbedtls_md_hmac(sha256Info, keys->hmac_key, NC_HMAC_KEY_SIZE, args->payload, args->payloadSize, hmacOut) != 0)
	{
		result = E_OPERATION_FAILED;
		goto Cleanup;
	}

	/* constant time compare the macs */
	result = mbedtls_ct_memcmp(hmacOut, args->mac, NC_ENCRYPTION_MAC_SIZE) == 0 ? NC_SUCCESS : E_OPERATION_FAILED;

Cleanup:
	/* Clean up sensitive data */
	ZERO_FILL(&messageKey, sizeof(messageKey));
	ZERO_FILL(hmacOut, sizeof(hmacOut));

	return result;
}


/*
* EXTERNAL API FUNCTIONS
*/
NC_EXPORT uint32_t NC_CC NCGetContextStructSize(void) 
{
	return sizeof(NCContext);
}

NC_EXPORT NCResult NC_CC NCInitContext(
	NCContext* ctx, 
	const uint8_t entropy[32]
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_NULL_ARG(entropy, 1)

	ctx->secpCtx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);

	//Randomize once on init
	return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG;
}

NC_EXPORT NCResult NC_CC NCReInitContext(
	NCContext* ctx, 
	const uint8_t entropy[32]
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(entropy, 1)

	//Only randomize again
	return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG;
}

NC_EXPORT NCResult NC_CC NCDestroyContext(NCContext* ctx)
{
	CHECK_NULL_ARG(ctx, 0);
	CHECK_INVALID_ARG(ctx->secpCtx, 0);

	//Destroy secp256k1 context
	secp256k1_context_destroy(ctx->secpCtx);

	//Wipe the context
	ZERO_FILL(ctx, sizeof(NCContext));

	return NC_SUCCESS;
}

//KEY Functions
NC_EXPORT NCResult NC_CC NCGetPublicKey(
	const NCContext* ctx, 
	const NCSecretKey* sk, 
	NCPublicKey* pk
)
{
	int result;
	secp256k1_keypair keyPair;
	secp256k1_xonly_pubkey xonly;	

	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(pk, 2)

	if (secp256k1_keypair_create(ctx->secpCtx, &keyPair, sk->key) != 1)
	{
		return E_INVALID_ARG;
	}

	//Generate the x-only public key, docs say this should always return 1
	result = secp256k1_keypair_xonly_pub(ctx->secpCtx, &xonly, NULL, &keyPair);
	DEBUG_ASSERT2(result == 1, "Expected x-only kepair to ALWAYS return 1")

	//Convert to compressed pubkey
	result = _convertFromXonly(ctx, &xonly, pk);
	DEBUG_ASSERT2(result == 1, "Expected x-only pubkey serialize to return 1")

	//Clean out keypair
	ZERO_FILL(&keyPair, sizeof(keyPair));
	ZERO_FILL(&xonly, sizeof(xonly));

	return NC_SUCCESS;
}

NC_EXPORT NCResult NC_CC NCValidateSecretKey(
	const NCContext* ctx, 
	const NCSecretKey* sk
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)

	//Validate the secret key
	return secp256k1_ec_seckey_verify(ctx->secpCtx, sk->key);
}

//Ecdsa Functions

NC_EXPORT NCResult NC_CC NCSignDigest(
	const NCContext* ctx, 
	const NCSecretKey* sk, 
	const uint8_t random32[32], 
	const uint8_t digest32[32], 
	uint8_t sig64[64]
)
{
	int result;
	secp256k1_keypair keyPair;
	secp256k1_xonly_pubkey xonly;	

	//Validate arguments
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(random32, 2)
	CHECK_NULL_ARG(digest32, 3)
	CHECK_NULL_ARG(sig64, 4)

	//Generate the keypair
	if (secp256k1_keypair_create(ctx->secpCtx, &keyPair, sk->key) != 1)
	{
		return E_INVALID_ARG;
	}

	//Sign the digest
	result = secp256k1_schnorrsig_sign32(ctx->secpCtx, sig64, digest32, &keyPair, random32);
	DEBUG_ASSERT2(result == 1, "Expected schnorr signature to return 1");

	//x-only public key from keypair so the signature can be verified
	result = secp256k1_keypair_xonly_pub(ctx->secpCtx, &xonly, NULL, &keyPair);
	DEBUG_ASSERT2(result == 1, "Expected x-only public key to ALWAYS return 1");

	//Verify the signature is valid
	result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);

	//cleanup any sensitive data
	ZERO_FILL(&keyPair, sizeof(keyPair));
	ZERO_FILL(&xonly, sizeof(xonly));

	return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
}

NC_EXPORT NCResult NC_CC NCSignData(
	const NCContext* ctx,
	const NCSecretKey* sk,
	const uint8_t random32[32],
	const uint8_t* data,
	size_t dataSize,
	uint8_t sig64[64]
)
{
	uint8_t digest[32];

	//Double check is required because arg position differs
	CHECK_NULL_ARG(ctx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(random32, 2)
	CHECK_NULL_ARG(data, 3)
	CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 4)
	CHECK_NULL_ARG(sig64, 5)

	//Compute sha256 of the data before signing
	if(mbedtls_sha256(data, dataSize, digest, 0) != 0)
	{
		return E_INVALID_ARG;
	}

	//Sign the freshly computed digest
	return NCSignDigest(ctx, sk, random32, digest, sig64);
}

NC_EXPORT NCResult NC_CC NCVerifyDigest(
	const NCContext* ctx,
	const NCPublicKey* pk,
	const uint8_t digest32[32],
	const uint8_t sig64[64]
)
{
	int result;
	secp256k1_xonly_pubkey xonly;

	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(pk, 1)
	CHECK_NULL_ARG(digest32, 2)
	CHECK_NULL_ARG(sig64, 3)	

	//recover the x-only key from a compressed public key
	if(_convertToXonly(ctx, pk, &xonly) != 1)
	{
		return E_INVALID_ARG;
	}

	//Verify the signature
	result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);

	//cleanup any sensitive data
	ZERO_FILL(&xonly, sizeof(xonly));

	return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
}

NC_EXPORT NCResult NC_CC NCVerifyData(
	const NCContext* ctx,
	const NCPublicKey* pk,
	const uint8_t* data,
	const size_t dataSize,
	const uint8_t sig64[64]
)
{
	uint8_t digest[32];

	CHECK_NULL_ARG(ctx, 0)
	CHECK_NULL_ARG(pk, 1)
	CHECK_NULL_ARG(data, 2)
	CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3)
	CHECK_NULL_ARG(sig64, 4)

	//Compute sha256 of the data before verifying
	if (mbedtls_sha256(data, dataSize, digest, 0) != 0)
	{
		return E_INVALID_ARG;
	}

	//Verify the freshly computed digest
	return NCVerifyDigest(ctx, pk, digest, sig64);
}

//ECDH Functions
NC_EXPORT NCResult NC_CC NCGetSharedSecret(
	const NCContext* ctx, 
	const NCSecretKey* sk, 
	const NCPublicKey* otherPk, 
	uint8_t sharedPoint[NC_SHARED_SEC_SIZE]
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(otherPk, 2)
	CHECK_NULL_ARG(sharedPoint, 3)	

	return _computeSharedSecret(
		ctx, 
		sk, 
		otherPk, 
		(struct shared_secret*)sharedPoint
	);
}

NC_EXPORT NCResult NC_CC NCGetConversationKeyEx(
	const NCContext* ctx,
	const uint8_t sharedPoint[NC_SHARED_SEC_SIZE],
	uint8_t conversationKey[NC_CONV_KEY_SIZE]
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sharedPoint, 1)
	CHECK_NULL_ARG(conversationKey, 2)	

	//Cast the shared point to the shared secret type
	return _computeConversationKey(
		ctx, 
		_getSha256MdInfo(),
		(struct shared_secret*)sharedPoint, 
		(struct conversation_key*)conversationKey
	);
}

NC_EXPORT NCResult NC_CC NCGetConversationKey(
	const NCContext* ctx,
	const NCSecretKey* sk,
	const NCPublicKey* pk,
	uint8_t conversationKey[NC_CONV_KEY_SIZE]
)
{
	NCResult result;
	struct shared_secret sharedSecret;
	const mbedtls_md_info_t* mdInfo;

	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(pk, 2)
	CHECK_NULL_ARG(conversationKey, 3)	
	
	mdInfo = _getSha256MdInfo();

	//Compute the shared point
	if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	result = _computeConversationKey(
		ctx, 
		mdInfo, 
		&sharedSecret, 
		(struct conversation_key*)conversationKey
	);

Cleanup:
	//Clean up sensitive data
	ZERO_FILL(&sharedSecret, sizeof(sharedSecret));

	return result;
}

NC_EXPORT NCResult NC_CC NCEncryptEx(
	const NCContext* ctx, 
	const uint8_t conversationKey[NC_CONV_KEY_SIZE], 
	uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE],
	NCCryptoData* args
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(conversationKey, 1)
	CHECK_NULL_ARG(hmacKeyOut, 2)
	CHECK_NULL_ARG(args, 3)

	//Validte ciphertext/plaintext
	CHECK_INVALID_ARG(args->inputData, 3)
	CHECK_INVALID_ARG(args->outputData, 3)
	CHECK_INVALID_ARG(args->nonce, 3)
	CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)	

	return _encryptEx(
		ctx, 
		_getSha256MdInfo(), 
		(struct conversation_key*)conversationKey, 
		hmacKeyOut,
		args
	);
}

NC_EXPORT NCResult NC_CC NCEncrypt(
	const NCContext* ctx, 
	const NCSecretKey* sk, 
	const NCPublicKey* pk, 
	uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE],
	NCCryptoData* args
)
{	
	NCResult result;
	const mbedtls_md_info_t* mdInfo;
	struct shared_secret sharedSecret;
	struct conversation_key conversationKey;	

	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(pk, 2)
	CHECK_NULL_ARG(hmacKeyOut, 3)
	CHECK_NULL_ARG(args, 4)

	//Validate input/output data
	CHECK_INVALID_ARG(args->inputData, 4)
	CHECK_INVALID_ARG(args->outputData, 4)
	CHECK_INVALID_ARG(args->nonce, 4)
	CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 4)

	mdInfo = _getSha256MdInfo();

	//Compute the shared point
	if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
	{
		goto Cleanup;
	}
	
	//Compute the conversation key from secret and pubkic keys
	if ((result = _computeConversationKey(ctx, mdInfo, &sharedSecret, &conversationKey)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	result = _encryptEx(ctx, mdInfo, &conversationKey, hmacKeyOut, args);

Cleanup:
	//Clean up sensitive data
	ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
	ZERO_FILL(&conversationKey, sizeof(conversationKey));

	return result;
}

NC_EXPORT NCResult NC_CC NCDecryptEx(
	const NCContext* ctx, 
	const uint8_t conversationKey[NC_CONV_KEY_SIZE], 
	NCCryptoData* args
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(conversationKey, 1)
	CHECK_NULL_ARG(args, 2)

	//Validte ciphertext/plaintext
	CHECK_INVALID_ARG(args->inputData, 2)
	CHECK_INVALID_ARG(args->outputData, 2)
	CHECK_INVALID_ARG(args->nonce, 2)
	CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 2)

	return _decryptEx(
		ctx, 
		_getSha256MdInfo(), 
		(struct conversation_key*)conversationKey, 
		args
	);
}

NC_EXPORT NCResult NC_CC NCDecrypt(
	const NCContext* ctx,
	const NCSecretKey* sk,
	const NCPublicKey* pk,
	NCCryptoData* args
)
{
	NCResult result;
	struct shared_secret sharedSecret;
	struct conversation_key conversationKey;
	const mbedtls_md_info_t* mdInfo;

	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(pk, 2)
	CHECK_NULL_ARG(args, 3)

	//Validte ciphertext/plaintext
	CHECK_INVALID_ARG(args->inputData, 3)
	CHECK_INVALID_ARG(args->outputData, 3)
	CHECK_INVALID_ARG(args->nonce, 3)
	CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)

	mdInfo = _getSha256MdInfo();

	if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	if ((result = _computeConversationKey(ctx, mdInfo, &sharedSecret, &conversationKey)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	result = _decryptEx(ctx, mdInfo, &conversationKey, args);

Cleanup:
	//Clean up sensitive data
	ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
	ZERO_FILL(&conversationKey, sizeof(conversationKey));

	return result;
}

NC_EXPORT NCResult NCComputeMac(
	const NCContext* ctx,
	const uint8_t hmacKey[NC_HMAC_KEY_SIZE],
	const uint8_t* payload,
	size_t payloadSize,
	uint8_t hmacOut[NC_ENCRYPTION_MAC_SIZE]
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(hmacKey, 1)
	CHECK_NULL_ARG(payload, 2)
	CHECK_ARG_RANGE(payloadSize, 1, UINT32_MAX, 3)
	CHECK_NULL_ARG(hmacOut, 4)

	/*
	* Compute the hmac of the data using the supplied hmac key
	*/
	return mbedtls_md_hmac(
		_getSha256MdInfo(), 
		hmacKey, 
		NC_HMAC_KEY_SIZE, 
		payload, 
		payloadSize, 
		hmacOut
	) == 0 ? NC_SUCCESS : E_OPERATION_FAILED;
}


NC_EXPORT NCResult NC_CC NCVerifyMacEx(
	const NCContext* ctx,
	const uint8_t conversationKey[NC_CONV_KEY_SIZE],
	NCMacVerifyArgs* args
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(conversationKey, 1)
	CHECK_NULL_ARG(args, 2)

	CHECK_INVALID_ARG(args->mac, 2)
	CHECK_INVALID_ARG(args->payload, 2)
	CHECK_INVALID_ARG(args->nonce, 2)
	CHECK_ARG_RANGE(args->payloadSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 2)	

	return _verifyMacEx(ctx, conversationKey, args);
}

NC_EXPORT NCResult NC_CC NCVerifyMac(
	const NCContext* ctx,
	const NCSecretKey* sk,
	const NCPublicKey* pk,
	NCMacVerifyArgs* args
)
{
	CHECK_NULL_ARG(ctx, 0)
	CHECK_INVALID_ARG(ctx->secpCtx, 0)
	CHECK_NULL_ARG(sk, 1)
	CHECK_NULL_ARG(pk, 2)
	CHECK_NULL_ARG(args, 3)

	CHECK_INVALID_ARG(args->mac, 3)
	CHECK_INVALID_ARG(args->payload, 3)
	CHECK_INVALID_ARG(args->nonce, 3)
	CHECK_ARG_RANGE(args->payloadSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)

	NCResult result;
	struct shared_secret sharedSecret;
	struct conversation_key conversationKey;

	/* Computed the shared point so we can get the converstation key */
	if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	if ((result = _computeConversationKey(ctx, _getSha256MdInfo(), &sharedSecret, &conversationKey)) != NC_SUCCESS)
	{
		goto Cleanup;
	}

	result = _verifyMacEx(ctx, (uint8_t*)&conversationKey, args);

Cleanup:
	/* Clean up sensitive data */
	ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
	ZERO_FILL(&conversationKey, sizeof(conversationKey));

	return result;
}