aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar vnugent <public@vaughnnugent.com>2024-03-03 15:02:02 -0500
committerLibravatar vnugent <public@vaughnnugent.com>2024-03-03 15:02:02 -0500
commit21f6c0a9cdd5ed67e48bb1f39f72217b5fe4758f (patch)
treeb081f9ccae15037372bfd906767247bbd58c2907
parent120022aa349f5e4cac28da74d568373c49245884 (diff)
Squashed commit of the following:
commit 490dfee4ef22479009627435c6ad728c3cbbab54 Author: vnugent <public@vaughnnugent.com> Date: Sun Mar 3 14:59:25 2024 -0500 test: #3 tests for encryption/description and Macs commit efa97490b7ed47f4e2f05bee52e2b33e14e439e6 Merge: 1b84e3c 120022a Author: vnugent <public@vaughnnugent.com> Date: Sun Mar 3 14:55:48 2024 -0500 merge master commit 1b84e3c7c2e55b1ff9ffdd09b66873e11c131441 Author: vnugent <public@vaughnnugent.com> Date: Sat Mar 2 22:57:36 2024 -0500 fix: #2 constent usage of sizeof() operator on struct types commit 9de5a214c66adea0ef2d0bac63c59449de202a88 Author: vnugent <public@vaughnnugent.com> Date: Fri Mar 1 14:30:36 2024 -0500 perf: avoid nc_key struct copy, cast and verify instead commit b917b761120ed684af28d0707673ffadcf14b8fe Author: vnugent <public@vaughnnugent.com> Date: Mon Feb 12 22:06:50 2024 -0500 fix: found the constant time memcompare function commit 9f85fff3b9f25da7410569ea94f994b88feb3910 Author: vnugent <public@vaughnnugent.com> Date: Fri Feb 9 22:48:35 2024 -0500 feat: added/update MAC functions to sign or verify nip44 payload commit aa5113741bb419b02d6ea416bba571fa3d65db46 Author: vnugent <public@vaughnnugent.com> Date: Wed Feb 7 01:37:53 2024 -0500 add missing hmac-key output buffer commit 55f47d22cc9ce4d1e22b70814d608c7ef3b1bbc9 Author: vnugent <public@vaughnnugent.com> Date: Sun Feb 4 21:08:13 2024 -0500 simple bug fixes, and public api argument validation tests commit 73c5a713fb164ae8b4ac8a891a8020e08eae0a3b Author: vnugent <public@vaughnnugent.com> Date: Fri Feb 2 23:05:48 2024 -0500 update api to return secpvalidate return code instead of internal return codes commit 06c73004e1a39a7ea4ea3a89c22dee0f66adb236 Author: vnugent <public@vaughnnugent.com> Date: Fri Feb 2 19:25:17 2024 -0500 change to lgpl license commit 6e79fdb3b6b6739fc7797d47e55a7691306cf736 Author: vnugent <public@vaughnnugent.com> Date: Wed Jan 31 21:30:49 2024 -0500 move validation macros, and optionally disable them commit ac1e58837f1ba687939f78b5c03cadd346c10ddd Author: vnugent <public@vaughnnugent.com> Date: Tue Jan 30 12:25:05 2024 -0500 couple more tests, renable range checks, set flags for all projects
-rw-r--r--CMakeLists.txt2
-rw-r--r--src/noscrypt.c342
-rw-r--r--src/noscrypt.h86
-rw-r--r--tests/hex.h148
-rw-r--r--tests/test.c219
5 files changed, 647 insertions, 150 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2504480..ab86081 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -84,7 +84,7 @@ endif()
unset(SECP256K1_LIB CACHE)
find_library(SECP256K1_LIB
- NAMES secp256k1 libsecp256k1 lib_secp256k1 ${}
+ NAMES secp256k1 libsecp256k1 lib_secp256k1
)
if(NOT SECP256K1_LIB)
diff --git a/src/noscrypt.c b/src/noscrypt.c
index fb6dd4f..a24c804 100644
--- a/src/noscrypt.c
+++ b/src/noscrypt.c
@@ -27,8 +27,10 @@
#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)
@@ -41,8 +43,7 @@
#endif // !NULL
#define CHACHA_NONCE_SIZE 12 //Size of 12 is set by the cipher spec
-#define CHACHA_KEY_SIZE 32
-#define HMAC_KEY_SIZE 32
+#define CHACHA_KEY_SIZE 32 //Size of 32 is set by the cipher spec
/*
* Local macro for secure zero buffer fill
@@ -73,19 +74,31 @@
/* Must include assert.h for assertions */
#include <assert.h>
#define DEBUG_ASSERT(x) assert(x);
- #define DEBUG_ASSERT2(x, message) assert(x && message);
+ #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 nc_expand_keys {
- uint8_t chacha_key[CHACHA_KEY_SIZE];
- uint8_t chacha_nonce[CHACHA_NONCE_SIZE];
- uint8_t hamc_key[HMAC_KEY_SIZE];
-};
-
struct shared_secret {
uint8_t value[NC_SHARED_SEC_SIZE];
};
@@ -99,6 +112,22 @@ struct message_key {
};
/*
+* 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
*/
@@ -115,7 +144,7 @@ static inline int _convertToXonly(const NCContext* ctx, const NCPublicKey* compr
static int _convertToPubKey(const NCContext* ctx, const NCPublicKey* compressedPubKey, secp256k1_pubkey* pubKey)
{
int result;
- uint8_t compressed[NC_PUBKEY_SIZE + 1];
+ uint8_t compressed[sizeof(NCPublicKey) + 1];
DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte key structure")
@@ -125,7 +154,7 @@ static int _convertToPubKey(const NCContext* ctx, const NCPublicKey* compressedP
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->key, NC_PUBKEY_SIZE);
+ MEMMOV((compressed + 1), compressedPubKey, sizeof(NCPublicKey));
result = secp256k1_ec_pubkey_parse(ctx->secpCtx, pubKey, compressed, sizeof(compressed));
@@ -212,7 +241,7 @@ static NCResult _computeSharedSecret(
);
//Clean up sensitive data
- ZERO_FILL(&pubKey, sizeof(secp256k1_pubkey));
+ ZERO_FILL(&pubKey, sizeof(pubKey));
//Result should be 1 on success
return result > 0 ? NC_SUCCESS : E_OPERATION_FAILED;
@@ -260,65 +289,24 @@ static inline NCResult _computeConversationKey(
/*
* Explode the hkdf into the chacha key, chacha nonce, and hmac key.
*/
-static inline void _expandKeysFromHkdf(const struct message_key* hkdf, struct nc_expand_keys* keys)
+static inline const struct nc_expand_keys* _expandKeysFromHkdf(const struct message_key* hkdf)
{
- uint8_t* hkdfBytes;
-
- DEBUG_ASSERT2(hkdf != NULL, "Expected valid hkdf")
- DEBUG_ASSERT2(keys != NULL, "Expected valid key expand structure")
-
- hkdfBytes = (uint8_t*)hkdf;
-
- //Copy segments of the hkdf into the keys struct
- MEMMOV(
- keys->chacha_key,
- hkdfBytes,
- CHACHA_KEY_SIZE
- );
-
- hkdfBytes += CHACHA_KEY_SIZE; //Offset by key size
-
- MEMMOV(
- keys->chacha_nonce,
- hkdfBytes,
- CHACHA_NONCE_SIZE
- );
-
- hkdfBytes += CHACHA_NONCE_SIZE; //Offset by nonce size
-
- MEMMOV(
- keys->hamc_key,
- hkdfBytes,
- HMAC_KEY_SIZE
- );
+ return (const struct nc_expand_keys*)hkdf;
}
static int _chachaEncipher(const struct nc_expand_keys* keys, NCCryptoData* args)
{
- int result;
- mbedtls_chacha20_context chachaCtx;
-
DEBUG_ASSERT2(keys != NULL, "Expected valid keys")
DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
- //Init the chacha context
- mbedtls_chacha20_init(&chachaCtx);
-
- //Set the key and nonce
- result = mbedtls_chacha20_setkey(&chachaCtx, keys->chacha_key);
- DEBUG_ASSERT2(result == 0, "Expected chacha setkey to return 0")
-
- result = mbedtls_chacha20_starts(&chachaCtx, keys->chacha_nonce, 0);
- DEBUG_ASSERT2(result == 0, "Expected chacha starts to return 0")
-
- //Encrypt the plaintext
- result = mbedtls_chacha20_update(&chachaCtx, args->dataSize, args->inputData, args->outputData);
- DEBUG_ASSERT2(result == 0, "Expected chacha update to return 0")
-
- //Clean up the chacha context
- mbedtls_chacha20_free(&chachaCtx);
-
- return result;
+ 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(
@@ -353,16 +341,19 @@ 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;
- struct nc_expand_keys cipherKeys;
+ 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)
@@ -371,10 +362,13 @@ static inline NCResult _encryptEx(
}
//Expand the keys from the hkdf so we can use them in the cipher
- _expandKeysFromHkdf(&messageKey, &cipherKeys);
+ expandedKeys = _expandKeysFromHkdf(&messageKey);
- //CHACHA20
- result = _chachaEncipher(&cipherKeys, args);
+ //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
@@ -392,10 +386,7 @@ static inline NCResult _decryptEx(
{
NCResult result;
struct message_key messageKey;
- struct nc_expand_keys cipherKeys;
-
- //Assume message key buffer is the same size as the expanded key struct
- DEBUG_ASSERT2(sizeof(messageKey) == sizeof(cipherKeys), "Message key size and expanded key sizes do not match")
+ const struct nc_expand_keys* cipherKeys;
DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
DEBUG_ASSERT2(ck != NULL, "Expected valid conversation key")
@@ -409,10 +400,10 @@ static inline NCResult _decryptEx(
}
//Expand the keys from the hkdf so we can use them in the cipher
- _expandKeysFromHkdf(&messageKey, &cipherKeys);
+ cipherKeys = _expandKeysFromHkdf(&messageKey);
- //CHACHA20
- result = _chachaEncipher(&cipherKeys, args);
+ //CHACHA20 (the result will be 0 on success)
+ result = (NCResult) _chachaEncipher(cipherKeys, args);
Cleanup:
//Clean up sensitive data
@@ -421,41 +412,65 @@ Cleanup:
return result;
}
-/*
-* Compute the sha256 digest of the data. This function should always return 0
-* on success.
-*/
-static inline int _computeSha256Digest(const uint8_t* data, size_t length, uint8_t digest[32])
+static NCResult _verifyMacEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCMacVerifyArgs* args
+)
{
- int result;
- mbedtls_sha256_context sha256;
+ 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")
- DEBUG_ASSERT2(data != NULL, "Expected valid data buffer")
- DEBUG_ASSERT2(digest != NULL, "Expected valid digest buffer")
+ sha256Info = _getSha256MdInfo();
- //Init the sha256 context
- mbedtls_sha256_init(&sha256);
+ /*
+ * 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;
+ }
- //starting context should never fail
- result = mbedtls_sha256_starts(&sha256, 0);
- DEBUG_ASSERT2(result == 0, "Expected sha256 starts to return 0")
+ /* Expand keys to get the hmac-key */
+ keys = _expandKeysFromHkdf(&messageKey);
- //may fail if the data is invalid
- if ((result = mbedtls_sha256_update(&sha256, data, length)) != 0)
+ /*
+ * 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;
}
- //Finishing context should never fail
- result = mbedtls_sha256_finish(&sha256, digest);
+ /* constant time compare the macs */
+ result = mbedtls_ct_memcmp(hmacOut, args->mac, NC_ENCRYPTION_MAC_SIZE) == 0 ? NC_SUCCESS : E_OPERATION_FAILED;
Cleanup:
- //Always free the context
- mbedtls_sha256_free(&sha256);
+ /* Clean up sensitive data */
+ ZERO_FILL(&messageKey, sizeof(messageKey));
+ ZERO_FILL(hmacOut, sizeof(hmacOut));
return result;
}
+
/*
* EXTERNAL API FUNCTIONS
*/
@@ -535,8 +550,8 @@ NC_EXPORT NCResult NC_CC NCGetPublicKey(
DEBUG_ASSERT2(result == 1, "Expected x-only pubkey serialize to return 1")
//Clean out keypair
- ZERO_FILL(&keyPair, sizeof(secp256k1_keypair));
- ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+ ZERO_FILL(&keyPair, sizeof(keyPair));
+ ZERO_FILL(&xonly, sizeof(xonly));
return NC_SUCCESS;
}
@@ -594,8 +609,8 @@ NC_EXPORT NCResult NC_CC NCSignDigest(
result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);
//cleanup any sensitive data
- ZERO_FILL(&keyPair, sizeof(secp256k1_keypair));
- ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+ ZERO_FILL(&keyPair, sizeof(keyPair));
+ ZERO_FILL(&xonly, sizeof(xonly));
return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
}
@@ -620,7 +635,7 @@ NC_EXPORT NCResult NC_CC NCSignData(
CHECK_NULL_ARG(sig64, 5)
//Compute sha256 of the data before signing
- if(_computeSha256Digest(data, dataSize, digest) != 0)
+ if(mbedtls_sha256(data, dataSize, digest, 0) != 0)
{
return E_INVALID_ARG;
}
@@ -655,7 +670,7 @@ NC_EXPORT NCResult NC_CC NCVerifyDigest(
result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);
//cleanup any sensitive data
- ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+ ZERO_FILL(&xonly, sizeof(xonly));
return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
}
@@ -677,7 +692,7 @@ NC_EXPORT NCResult NC_CC NCVerifyData(
CHECK_NULL_ARG(sig64, 4)
//Compute sha256 of the data before verifying
- if (_computeSha256Digest(data, dataSize, digest) != 0)
+ if (mbedtls_sha256(data, dataSize, digest, 0) != 0)
{
return E_INVALID_ARG;
}
@@ -770,23 +785,27 @@ Cleanup:
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(args, 2)
+ CHECK_NULL_ARG(hmacKeyOut, 2)
+ CHECK_NULL_ARG(args, 3)
//Validte ciphertext/plaintext
- CHECK_INVALID_ARG(args->inputData, 2)
- CHECK_INVALID_ARG(args->outputData, 2)
- CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 2)
+ 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
);
}
@@ -795,6 +814,7 @@ NC_EXPORT NCResult NC_CC NCEncrypt(
const NCContext* ctx,
const NCSecretKey* sk,
const NCPublicKey* pk,
+ uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE],
NCCryptoData* args
)
{
@@ -807,12 +827,14 @@ NC_EXPORT NCResult NC_CC NCEncrypt(
CHECK_INVALID_ARG(ctx->secpCtx, 0)
CHECK_NULL_ARG(sk, 1)
CHECK_NULL_ARG(pk, 2)
- CHECK_NULL_ARG(args, 3)
+ CHECK_NULL_ARG(hmacKeyOut, 3)
+ CHECK_NULL_ARG(args, 4)
//Validate input/output data
- CHECK_INVALID_ARG(args->inputData, 3)
- CHECK_INVALID_ARG(args->outputData, 3)
- CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)
+ 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();
@@ -828,7 +850,7 @@ NC_EXPORT NCResult NC_CC NCEncrypt(
goto Cleanup;
}
- result = _encryptEx(ctx, mdInfo, &conversationKey, args);
+ result = _encryptEx(ctx, mdInfo, &conversationKey, hmacKeyOut, args);
Cleanup:
//Clean up sensitive data
@@ -838,7 +860,6 @@ Cleanup:
return result;
}
-
NC_EXPORT NCResult NC_CC NCDecryptEx(
const NCContext* ctx,
const uint8_t conversationKey[NC_CONV_KEY_SIZE],
@@ -853,7 +874,8 @@ NC_EXPORT NCResult NC_CC NCDecryptEx(
//Validte ciphertext/plaintext
CHECK_INVALID_ARG(args->inputData, 2)
CHECK_INVALID_ARG(args->outputData, 2)
- CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_MESSAGE_SIZE, 3)
+ 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,
@@ -863,7 +885,6 @@ NC_EXPORT NCResult NC_CC NCDecryptEx(
);
}
-
NC_EXPORT NCResult NC_CC NCDecrypt(
const NCContext* ctx,
const NCSecretKey* sk,
@@ -885,7 +906,8 @@ NC_EXPORT NCResult NC_CC NCDecrypt(
//Validte ciphertext/plaintext
CHECK_INVALID_ARG(args->inputData, 3)
CHECK_INVALID_ARG(args->outputData, 3)
- CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_MESSAGE_SIZE, 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();
@@ -909,3 +931,93 @@ Cleanup:
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;
+} \ No newline at end of file
diff --git a/src/noscrypt.h b/src/noscrypt.h
index f6bfe76..f7265ad 100644
--- a/src/noscrypt.h
+++ b/src/noscrypt.h
@@ -72,6 +72,8 @@
#define NC_PUBKEY_SIZE 32
#define NC_SHARED_SEC_SIZE 32
#define NC_CONV_KEY_SIZE 32
+#define NC_HMAC_KEY_SIZE 32
+#define NC_ENCRYPTION_MAC_SIZE 32
#define NC_MESSAGE_KEY_SIZE NIP44_MESSAGE_KEY_SIZE
/*
@@ -80,8 +82,6 @@
*/
#define NIP44_MIN_ENC_MESSAGE_SIZE 1
#define NIP44_MAX_ENC_MESSAGE_SIZE 65535
-#define NIP44_MIN_DEC_MESSAGE_SIZE 99
-#define NIP44_MAX_DEC_MESSAGE_SIZE 65603
/*
* The Nip44 constant salt
@@ -169,14 +169,45 @@ typedef struct nc_encryption_struct {
} NCCryptoData;
/*
+* A structure for Nip44 message authentication code verification. This structure
+* is used to pass arguments to the NCVerifyMac and NCVerifyMacEx functions.
+*/
+typedef struct nc_mac_verify {
+
+ /* The message authentication code certifying the Nip44 payload */
+ uint8_t mac[NC_ENCRYPTION_MAC_SIZE];
+
+ /* The nonce used for the original message encryption */
+ uint8_t nonce[NC_ENCRYPTION_NONCE_SIZE];
+
+ /* The message payload data */
+ const uint8_t* payload;
+
+ /* The size of the payload data */
+ size_t payloadSize;
+
+} NCMacVerifyArgs;
+
+
+/*
API FUNCTIONS
*/
+/*
+* A helper function to cast a 32byte buffer to a NCSecretKey struct
+* @param key The 32byte buffer to cast
+* @return A pointer to the NCSecretKey struct
+*/
static inline NCSecretKey* NCToSecKey(uint8_t key[NC_SEC_KEY_SIZE])
{
return (NCSecretKey*)key;
}
+/*
+* A helper function to cast a 32byte buffer to a NCPublicKey struct
+* @param key The 32byte buffer to cast
+* @return A pointer to the NCPublicKey struct
+*/
static inline NCPublicKey* NCToPubKey(uint8_t key[NC_PUBKEY_SIZE])
{
return (NCPublicKey*)key;
@@ -377,6 +408,7 @@ NC_EXPORT NCResult NC_CC NCEncrypt(
const NCContext* ctx,
const NCSecretKey* sk,
const NCPublicKey* pk,
+ uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE],
NCCryptoData* args
);
@@ -397,6 +429,22 @@ NC_EXPORT NCResult NC_CC NCDecrypt(
NCCryptoData* args
);
+/*
+* High level api for verifying a Nip44 message authentication code using a secret key
+and a public key. Use the NCVerifyMacEx functions for extended verification functionality.
+* @param ctx A pointer to an existing library context
+* @param sk A pointer to the secret key
+* @param pk A pointer to the 32byte compressed public key (x-only serialized public key)
+* @param args A pointer to the mac verification arguments
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+* the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCVerifyMac(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ NCMacVerifyArgs* args
+);
/*--------------------------------------
* EXTENDED ENCRYPTION API
@@ -462,6 +510,7 @@ the error code and positional argument that caused the error.
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
);
@@ -480,4 +529,37 @@ NC_EXPORT NCResult NC_CC NCDecryptEx(
NCCryptoData* args
);
+/*
+* Verifies a Nip44 message authentication code using the given conversation key.
+* @param ctx A pointer to the existing library context
+* @param conversationKey A pointer to the 32byte conversation key
+* @param args A pointer to the mac verification arguments
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+* the error code and positional argument that caused the error.
+*/
+NC_EXPORT NCResult NC_CC NCVerifyMacEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCMacVerifyArgs* args
+);
+
+/*
+* Computes a message authentication code for a given payload using the given hmacKey and writes the
+* mac to the hmacOut buffer.
+* @param ctx A pointer to the existing library context
+* @param hmacKey A pointer to the 32byte hmac key
+* @param payload A pointer to the payload data buffer
+* @param payloadSize The size of the payload data buffer
+* @param hmacOut A pointer to the 32byte buffer to write the mac to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+* the error code and positional argument that caused the error.
+*/
+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]
+);
+
#endif // !NOSCRYPT_H
diff --git a/tests/hex.h b/tests/hex.h
new file mode 100644
index 0000000..793e9f9
--- /dev/null
+++ b/tests/hex.h
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2024 Vaughn Nugent
+*
+* Package: noscrypt
+* File: hex.h
+*
+* 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/.
+*/
+
+
+#ifndef HEX_HELPERS_H
+#define HEX_HELPERS_H
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+ #include <assert.h>
+ #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
+
+typedef struct hexBytes
+{
+ uint8_t* data;
+ size_t length;
+} HexBytes;
+
+/* Deferred list of HexBytes to be freed on exit */
+static HexBytes* _hdeferList[10];
+static size_t _hdeferListIndex = 0;
+
+/*
+ Allocates a HexBytes and decodes the hexadecimal string into it's binary
+ representation. The string must be a valid hexadecimal string and the length
+ and may not be NULL. The length may be known at compile time and can be used
+ to assert the length of the string literal.
+ @param hexLiteral The hexadecimal string to decode
+ @param strLen The length of the string
+*/
+#define FromHexString(str, len) _fromHexString(str, sizeof(str) - 1); STATIC_ASSERT(sizeof(str)/2 == len && len > 0, "Invalid length hex string literal");
+
+static HexBytes* __allocHexBytes(size_t length)
+{
+ length /= 2;
+
+ HexBytes* hexBytes = (HexBytes*)malloc(length + sizeof(HexBytes));
+ if(!hexBytes)
+ {
+ return NULL;
+ }
+
+ hexBytes->length = length;
+ /* data starts after the structure size */
+ hexBytes-> data = ((uint8_t*)hexBytes) + sizeof(HexBytes);
+ /* add new value to deferred cleanup list */
+ _hdeferList[_hdeferListIndex++] = hexBytes;
+ return hexBytes;
+}
+
+static HexBytes* _fromHexString(const char* hexLiteral, size_t strLen)
+{
+ HexBytes* hexBytes;
+ size_t i;
+
+ if(!hexLiteral)
+ {
+ return NULL;
+ }
+
+ /* alloc the raw bytes */
+ hexBytes = __allocHexBytes(strLen);
+
+ /* read every 2 chars into */
+ for (i = 0; i < strLen; i += 2)
+ {
+ /* slice string into smaller 2 char strings then parse */
+ char byteString[3] = { hexLiteral[i], hexLiteral[i + 1], '\0'};
+ hexBytes->data[i / 2] = (uint8_t)strtol(byteString, NULL, 16);
+ }
+
+ return hexBytes;
+}
+
+/*
+ Frees all the HexBytes that were allocated by the
+ FromHexString function. To be called at the end of
+ the program.
+*/
+static void FreeHexBytes(void)
+{
+ while(_hdeferListIndex > 0)
+ {
+ free(_hdeferList[--_hdeferListIndex]);
+ _hdeferList[_hdeferListIndex] = NULL;
+ }
+}
+
+/*
+* Prints the value of the buffer as a hexadecimal string
+* @param bytes The buffer to print
+* @param len The length of the buffer
+*/
+static void PrintHexRaw(void* bytes, size_t len)
+{
+ size_t i;
+ for (i = 0; i < len; i++)
+ {
+ printf("%02x", ((uint8_t*)bytes)[i]);
+ }
+
+ puts("\n");
+}
+
+/*
+* Prints the value of the HexBytes as a hexadecimal string
+* @param hexBytes A pointer to the HexBytes structure to print the value of
+*/
+static void PrintHexBytes(HexBytes* hexBytes)
+{
+ if (!hexBytes)
+ {
+ puts("NULL");
+ }
+ else
+ {
+ PrintHexRaw(hexBytes->data, hexBytes->length);
+ }
+}
+
+
+#endif // !HEX_HELPERS_H
+
+
diff --git a/tests/test.c b/tests/test.c
index d8fa89c..09e195b 100644
--- a/tests/test.c
+++ b/tests/test.c
@@ -27,7 +27,7 @@
#include <mbedtls/sha256.h>
#include <mbedtls/platform_util.h>
-#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32)
+#ifdef _NC_IS_WINDOWS
#define IS_WINDOWS
#endif
@@ -46,8 +46,8 @@
#endif
/*Prints a string literal to the console*/
-#define PRINTL(x) printf(x); printf("\n");
-#define ENSURE(x) if(!(x)) { printf("Assumption failed!\n"); return 1; }
+#define PRINTL(x) puts(x); puts("\n");
+#define ENSURE(x) if(!(x)) { puts("Assumption failed!\n"); return 1; }
#define TEST(x, expected) printf("\tTesting %s\n", #x); if(((long)x) != ((long)expected)) \
{ printf("FAILED: Expected %ld but got %ld @ callsite %s. Line: %d \n", ((long)expected), ((long)x), #x, __LINE__); return 1; }
@@ -58,6 +58,15 @@
#define ZERO_FILL(x, size) memset(x, 0, size)
#endif
+
+#ifdef IS_WINDOWS
+ #define memmove(dst, src, size) memmove_s(dst, size, src, size)
+#else
+ #include<string.h>
+#endif
+
+#include "hex.h"
+
//Pre-computed constants for argument errors
#define ARG_ERROR_POS_0 E_NULL_PTR
#define ARG_ERROR_POS_1 NCResultWithArgPosition(E_NULL_PTR, 0x01)
@@ -83,11 +92,12 @@
#define ARG_INVALID_ERROR_POS_5 NCResultWithArgPosition(E_INVALID_ARG, 0x05)
#define ARG_INVALID_ERROR_POS_6 NCResultWithArgPosition(E_INVALID_ARG, 0x06)
-
-
+static int RunTests(void);
static void FillRandomData(void* pbBuffer, size_t length);
static int TestEcdsa(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKey);
static int InitKepair(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKey);
+static int TestKnownKeys(NCContext* context);
+static int TestCorrectEncryption(NCContext* context);
#ifndef NC_INPUT_VALIDATION_OFF
static int TestPublicApiArgumentValidation(void);
@@ -98,12 +108,22 @@ static const uint8_t zero64[64] = { 0 };
int main(void)
{
+ int result;
+ result = RunTests();
+
+ FreeHexBytes();
+
+ return 0;
+}
+
+static int RunTests(void)
+{
NCContext ctx;
uint8_t ctxRandom[32];
NCSecretKey secKey;
NCPublicKey pubKey;
- PRINTL("Begining basic noscrypt tests\n")
+ PRINTL("Begining basic noscrypt tests")
FillRandomData(ctxRandom, 32);
@@ -112,27 +132,37 @@ int main(void)
TEST(NCInitContext(&ctx, ctxRandom), NC_SUCCESS)
if (InitKepair(&ctx, &secKey, &pubKey) != 0)
- {
- return 1;
- }
-
+ {
+ return 1;
+ }
+
if (TestEcdsa(&ctx, &secKey, &pubKey) != 0)
{
return 1;
}
+ if (TestKnownKeys(&ctx) != 0)
+ {
+ return 1;
+ }
+
#ifndef NC_INPUT_VALIDATION_OFF
- if(TestPublicApiArgumentValidation() != 0)
- {
- return 1;
- }
+ if (TestPublicApiArgumentValidation() != 0)
+ {
+ return 1;
+ }
#endif
- PRINTL("ECDSA tests passed\n")
+ if (TestCorrectEncryption(&ctx) != 0)
+ {
+ return 1;
+ }
TEST(NCDestroyContext(&ctx), NC_SUCCESS)
- return 0;
+ PRINTL("\nSUCCESS All tests passed")
+
+ return 0;
}
static void _sha256(const uint8_t* data, size_t length, uint8_t digest[32])
@@ -149,7 +179,7 @@ static const char* message = "Test message to sign";
static int InitKepair(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKey)
{
- PRINTL("TEST: Keypair\n")
+ PRINTL("TEST: Keypair")
//Get random private key
FillRandomData(secKey, sizeof(NCSecretKey));
@@ -163,7 +193,7 @@ static int InitKepair(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubK
//Generate a public key from the secret key
TEST(NCGetPublicKey(context, secKey, pubKey), NC_SUCCESS);
- PRINTL("\nPASSED: Keypair tests completed\n")
+ PRINTL("\nPASSED: Keypair tests completed")
return 0;
}
@@ -174,7 +204,7 @@ static int TestEcdsa(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKe
uint8_t sigEntropy[32];
uint8_t invalidSig[64];
- PRINTL("TEST: Ecdsa\n")
+ PRINTL("TEST: Ecdsa")
//Init a new secret key with random data
FillRandomData(invalidSig, sizeof(invalidSig));
@@ -229,7 +259,7 @@ static int TestEcdsa(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKe
TEST(NCVerifyDigest(context, pubKey, digestToSign, invalidSig), E_INVALID_ARG);
}
- PRINTL("\nPASSED: Ecdsa tests completed\n")
+ PRINTL("\nPASSED: Ecdsa tests completed")
return 0;
}
@@ -243,8 +273,9 @@ static int TestPublicApiArgumentValidation(void)
NCSecretKey secKey;
NCPublicKey pubKey;
NCCryptoData cryptoData;
+ uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE];
- PRINTL("TEST: Public API argument validation tests\n")
+ PRINTL("TEST: Public API argument validation tests")
FillRandomData(ctxRandom, 32);
@@ -302,24 +333,25 @@ static int TestPublicApiArgumentValidation(void)
cryptoData.outputData = sig64;
FillRandomData(&cryptoData.nonce, 32);
- TEST(NCEncrypt(NULL, &secKey, &pubKey, &cryptoData), ARG_ERROR_POS_0)
- TEST(NCEncrypt(&ctx, NULL, &pubKey, &cryptoData), ARG_ERROR_POS_1)
- TEST(NCEncrypt(&ctx, &secKey, NULL, &cryptoData), ARG_ERROR_POS_2)
- TEST(NCEncrypt(&ctx, &secKey, &pubKey, NULL), ARG_ERROR_POS_3)
+ TEST(NCEncrypt(NULL, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_ERROR_POS_0)
+ TEST(NCEncrypt(&ctx, NULL, &pubKey, hmacKeyOut, &cryptoData), ARG_ERROR_POS_1)
+ TEST(NCEncrypt(&ctx, &secKey, NULL, hmacKeyOut, &cryptoData), ARG_ERROR_POS_2)
+ TEST(NCEncrypt(&ctx, &secKey, &pubKey, NULL, &cryptoData), ARG_ERROR_POS_3)
+ TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, NULL), ARG_ERROR_POS_4)
//Test invalid data size
cryptoData.dataSize = 0;
- TEST(NCEncrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_RAMGE_ERROR_POS_3)
+ TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_RAMGE_ERROR_POS_4)
//Test null input data
cryptoData.dataSize = 32;
cryptoData.inputData = NULL;
- TEST(NCEncrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3)
+ TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_INVALID_ERROR_POS_4)
//Test null output data
cryptoData.inputData = zero32;
cryptoData.outputData = NULL;
- TEST(NCEncrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3)
+ TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_INVALID_ERROR_POS_4)
//Decrypt
cryptoData.dataSize = 32;
@@ -343,14 +375,137 @@ static int TestPublicApiArgumentValidation(void)
//Test null output data
cryptoData.inputData = zero32;
cryptoData.outputData = NULL;
- TEST(NCDecrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3)
+ TEST(NCDecrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3)
+
+ {
+ uint8_t hmacDataOut[NC_ENCRYPTION_MAC_SIZE];
+ TEST(NCComputeMac(NULL, hmacKeyOut, zero32, 32, hmacDataOut), ARG_ERROR_POS_0)
+ TEST(NCComputeMac(&ctx, NULL, zero32, 32, hmacDataOut), ARG_ERROR_POS_1)
+ TEST(NCComputeMac(&ctx, hmacKeyOut, NULL, 32, hmacDataOut), ARG_ERROR_POS_2)
+ TEST(NCComputeMac(&ctx, hmacKeyOut, zero32, 0, hmacDataOut), ARG_RAMGE_ERROR_POS_3)
+ TEST(NCComputeMac(&ctx, hmacKeyOut, zero32, 32, NULL), ARG_ERROR_POS_4)
+ }
+
+ {
+ NCMacVerifyArgs macArgs;
+ macArgs.payload = zero32;
+ macArgs.payloadSize = 32;
- PRINTL("\nPASSED: Public API argument validation tests completed\n")
+ TEST(NCVerifyMac(NULL, &secKey, &pubKey, &macArgs), ARG_ERROR_POS_0)
+ TEST(NCVerifyMac(&ctx, NULL, &pubKey, &macArgs), ARG_ERROR_POS_1)
+ TEST(NCVerifyMac(&ctx, &secKey, NULL, &macArgs), ARG_ERROR_POS_2)
+ TEST(NCVerifyMac(&ctx, &secKey, &pubKey, NULL), ARG_ERROR_POS_3)
+
+ macArgs.payload = NULL;
+ TEST(NCVerifyMac(&ctx, &secKey, &pubKey, &macArgs), ARG_INVALID_ERROR_POS_3)
+
+ macArgs.payload = zero32;
+ macArgs.payloadSize = 0;
+ TEST(NCVerifyMac(&ctx, &secKey, &pubKey, &macArgs), ARG_RAMGE_ERROR_POS_3)
+ }
+
+ PRINTL("\nPASSED: Public API argument validation tests completed")
return 0;
}
-#endif
+#endif
+
+static int TestKnownKeys(NCContext* context)
+{
+ PRINTL("TEST: Known keys")
+
+ NCPublicKey pubKey;
+
+ HexBytes* secKey1 = FromHexString("98c642360e7163a66cee5d9a842b252345b6f3f3e21bd3b7635d5e6c20c7ea36", sizeof(secKey));
+ HexBytes* pubKey1 = FromHexString("0db15182c4ad3418b4fbab75304be7ade9cfa430a21c1c5320c9298f54ea5406", sizeof(pubKey));
+
+ HexBytes* secKey2 = FromHexString("3032cb8da355f9e72c9a94bbabae80ca99d3a38de1aed094b432a9fe3432e1f2", sizeof(secKey));
+ HexBytes* pubKey2 = FromHexString("421181660af5d39eb95e48a0a66c41ae393ba94ffeca94703ef81afbed724e5a", sizeof(pubKey));
+
+ //Test known keys
+ TEST(NCValidateSecretKey(context, NCToSecKey(secKey1->data)), 1);
+
+ /* Recover a public key from secret key 1 */
+ TEST(NCGetPublicKey(context, NCToSecKey(secKey1->data), &pubKey), NC_SUCCESS);
+
+ /* Ensure the public key matches the known public key value */
+ TEST(memcmp(pubKey1->data, &pubKey, sizeof(pubKey)), 0);
+
+ /* Repeat with second key */
+ TEST(NCValidateSecretKey(context, (NCSecretKey*)secKey2->data), 1);
+ TEST(NCGetPublicKey(context, (NCSecretKey*)secKey2->data, &pubKey), NC_SUCCESS);
+ TEST(memcmp(pubKey2->data, &pubKey, sizeof(pubKey)), 0);
+
+ PRINTL("\nPASSED: Known keys tests completed")
+ return 0;
+}
+
+#define TEST_ENC_DATA_SIZE 128
+
+static int TestCorrectEncryption(NCContext* context)
+{
+ NCSecretKey secKey1;
+ NCPublicKey pubKey1;
+
+ NCSecretKey secKey2;
+ NCPublicKey pubKey2;
+
+ NCCryptoData cryptoData;
+ NCMacVerifyArgs macVerifyArgs;
+ uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE];
+
+ uint8_t plainText[TEST_ENC_DATA_SIZE];
+ uint8_t cipherText[TEST_ENC_DATA_SIZE];
+ uint8_t decryptedText[TEST_ENC_DATA_SIZE];
+
+ PRINTL("TEST: Correct encryption")
+
+ /* init a sending and receiving key */
+ FillRandomData(&secKey1, sizeof(NCSecretKey));
+ FillRandomData(&secKey2, sizeof(NCSecretKey));
+ FillRandomData(plainText, sizeof(plainText));
+
+ ENSURE(NCValidateSecretKey(context, &secKey1) == 1);
+ ENSURE(NCValidateSecretKey(context, &secKey2) == 1);
+
+ ENSURE(NCGetPublicKey(context, &secKey1, &pubKey1) == NC_SUCCESS);
+ ENSURE(NCGetPublicKey(context, &secKey2, &pubKey2) == NC_SUCCESS);
+
+ /* setup the crypto data structure */
+ cryptoData.dataSize = TEST_ENC_DATA_SIZE;
+ cryptoData.inputData = plainText;
+ cryptoData.outputData = cipherText;
+ /* add a random nonce, we will keep it stored in the nonce field of the struct */
+ FillRandomData(cryptoData.nonce, NC_ENCRYPTION_NONCE_SIZE);
+
+ /* Try to encrypt the data from sec1 to pub2 */
+ TEST(NCEncrypt(context, &secKey1, &pubKey2, hmacKeyOut, &cryptoData), NC_SUCCESS);
+
+ //swap texts
+ cryptoData.inputData = cipherText;
+ cryptoData.outputData = decryptedText;
+
+ /* Try to decrypt the data from sec1 to pub2 */
+ TEST(NCDecrypt(context, &secKey2, &pubKey1, &cryptoData), NC_SUCCESS);
+
+ /* Ensure the decrypted text matches the original */
+ TEST(memcmp(plainText, decryptedText, sizeof(plainText)), 0);
+
+ /* Also try to validate the payload mac */
+ memmove(macVerifyArgs.nonce, cryptoData.nonce, NC_ENCRYPTION_NONCE_SIZE);
+ macVerifyArgs.payload = cipherText;
+ macVerifyArgs.payloadSize = TEST_ENC_DATA_SIZE;
+
+ /* Compute message mac on ciphertext */
+ TEST(NCComputeMac(context, hmacKeyOut, cipherText, sizeof(cipherText), macVerifyArgs.mac), NC_SUCCESS);
+
+ /* Verify the mac */
+ TEST(NCVerifyMac(context, &secKey1, &pubKey2, &macVerifyArgs), NC_SUCCESS);
+
+ PRINTL("\nPASSED: Correct encryption tests completed")
+ return 0;
+}
static void FillRandomData(void* pbBuffer, size_t length)
{
@@ -368,4 +523,4 @@ static void FillRandomData(void* pbBuffer, size_t length)
TASSERT(fread(pbBuffer, 1, length, f) == length);
fclose(f);
#endif
-} \ No newline at end of file
+}