From 626a8d8d3df8880991684d6d1a06b82f6685b51a Mon Sep 17 00:00:00 2001 From: vnugent Date: Sun, 28 Jan 2024 19:23:18 -0500 Subject: initial commit --- src/noscrypt.c | 865 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/noscrypt.h | 514 ++++++++++++++++++++++++++++++++++ 2 files changed, 1379 insertions(+) create mode 100644 src/noscrypt.c create mode 100644 src/noscrypt.h (limited to 'src') diff --git a/src/noscrypt.c b/src/noscrypt.c new file mode 100644 index 0000000..6ef273f --- /dev/null +++ b/src/noscrypt.c @@ -0,0 +1,865 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: noscrypt +* Package: noscrypt +* File: noscrypt.c +* +* noscrypt is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published +* by the Free Software Foundation, either version 2 of the License, +* or (at your option) any later version. +* +* noscrypt 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 +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with noscrypt. If not, see http://www.gnu.org/licenses/. +*/ + +#include "noscrypt.h" + +#include +#include + +//Setup mbedtls +#include +#include +#include +#include +#include + +#define CHACHA_NONCE_SIZE 12 //Size of 12 is set by the cipher spec +#define CHACHA_KEY_SIZE 32 +#define HMAC_KEY_SIZE 32 + +/* +* Local macro for secure zero buffer fill +*/ +#define ZERO_FILL(x, size) mbedtls_platform_zeroize(x, size) + +//Include string for memmove +#include +#define MEMMOV(dst, src, size) memmove(dst, src, size) + +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]; +}; + +struct conversation_key { + uint8_t value[NC_CONV_KEY_SIZE]; +}; + +struct message_key { + uint8_t value[NC_MESSAGE_KEY_SIZE]; +}; + +/* +* 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[NC_PUBKEY_SIZE + 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->key, NC_PUBKEY_SIZE); + + 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(secp256k1_pubkey)); + + return (NCResult)result; +} + +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 +) +{ + //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 (returns 0 on success so it can be cast to an NCResult) + return (NCResult)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 + ); +} + + +/* +* 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) +{ + uint8_t* hkdfBytes; + + DEBUG_ASSERT2(hkdf != NULL, "Expected valid hkdf") + + hkdfBytes = (uint8_t*)hkdf; + + //Copy segments of the hkdf into the keys struct + MEMMOV( + keys->chacha_key, + hkdfBytes, + CHACHA_KEY_SIZE + ); + + MEMMOV( + keys->chacha_nonce, + (hkdfBytes + CHACHA_KEY_SIZE), + CHACHA_NONCE_SIZE + ); + + MEMMOV( + keys->hamc_key, + (hkdfBytes + CHACHA_KEY_SIZE + CHACHA_NONCE_SIZE), + HMAC_KEY_SIZE + ); +} + +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") + DEBUG_ASSERT2(sizeof(keys->chacha_nonce) == 12, "Chacha nonce must be 12 exactly bytes in length") + + //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; +} + +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 +) +{ + 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 + return (NCResult)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 + NC_MESSAGE_KEY_SIZE + ); +} + +static inline NCResult _encryptEx( + const NCContext* ctx, + const mbedtls_md_info_t* mdINfo, + const struct conversation_key* ck, + NCCryptoData* args +) +{ + NCResult result; + struct message_key messageKey; + 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") + + //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 + _expandKeysFromHkdf(&messageKey, &cipherKeys); + + //CHACHA20 + result = _chachaEncipher(&cipherKeys, 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; + 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") + + 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 + _expandKeysFromHkdf(&messageKey, &cipherKeys); + + //CHACHA20 + result = _chachaEncipher(&cipherKeys, args); + +Cleanup: + //Clean up sensitive data + ZERO_FILL(&messageKey, sizeof(messageKey)); + + 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]) +{ + int result; + mbedtls_sha256_context sha256; + + DEBUG_ASSERT2(data != NULL, "Expected valid data buffer") + DEBUG_ASSERT2(digest != NULL, "Expected valid digest buffer") + + //Init the sha256 context + mbedtls_sha256_init(&sha256); + + //starting context should never fail + result = mbedtls_sha256_starts(&sha256, 0); + DEBUG_ASSERT2(result == 0, "Expected sha256 starts to return 0") + + //may fail if the data is invalid + if ((result = mbedtls_sha256_update(&sha256, data, length)) != 0) + { + goto Cleanup; + } + + //Finishing context should never fail + result = mbedtls_sha256_finish(&sha256, digest); + +Cleanup: + //Always free the context + mbedtls_sha256_free(&sha256); + + 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_PTR(ctx) + CHECK_NULL_PTR(entropy) + + 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_PTR(ctx) + CHECK_INVALID_ARG(ctx->secpCtx) + CHECK_INVALID_ARG(entropy) + + //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); + + //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_NULL_ARG(sk, 1) + CHECK_NULL_ARG(pk, 2) + CHECK_INVALID_ARG(ctx->secpCtx) + + 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(secp256k1_keypair)); + ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey)); + + return NC_SUCCESS; +} + +NC_EXPORT NCResult NC_CC NCValidateSecretKey( + const NCContext* ctx, + const NCSecretKey* sk +) +{ + CHECK_NULL_PTR(ctx) + CHECK_NULL_PTR(sk) + CHECK_INVALID_ARG(ctx->secpCtx) + + //Validate the secret key + return secp256k1_ec_seckey_verify(ctx->secpCtx, sk->key) ? NC_SUCCESS : E_INVALID_ARG; +} + +//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_NULL_ARG(sk, 1) + CHECK_NULL_ARG(random32, 2) + CHECK_NULL_ARG(digest32, 3) + CHECK_NULL_ARG(sig64, 4) + CHECK_INVALID_ARG(ctx->secpCtx) + + //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(secp256k1_keypair)); + ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey)); + + 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]; + + CHECK_NULL_ARG(data, 2) + //CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3) + + //Compute sha256 of the data before signing + if(_computeSha256Digest(data, dataSize, digest) != 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; + + DEBUG_ASSERT(&xonly != NULL) + + CHECK_NULL_ARG(ctx, 0) + CHECK_NULL_ARG(sig64, 1) + CHECK_NULL_ARG(digest32, 2) + CHECK_NULL_ARG(pk, 3) + CHECK_INVALID_ARG(ctx->secpCtx) + + //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(secp256k1_xonly_pubkey)); + + 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, + uint8_t sig64[64] +) +{ + uint8_t digest[32]; + + CHECK_NULL_ARG(data, 2) + //CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3) + + //Compute sha256 of the data before verifying + if (_computeSha256Digest(data, dataSize, digest) != 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_NULL_ARG(sk, 1) + CHECK_NULL_ARG(otherPk, 2) + CHECK_NULL_ARG(sharedPoint, 3) + CHECK_INVALID_ARG(ctx->secpCtx) + + 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_NULL_ARG(sharedPoint, 1) + CHECK_NULL_ARG(conversationKey, 2) + CHECK_INVALID_ARG(ctx->secpCtx) + + //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_NULL_ARG(sk, 1) + CHECK_NULL_ARG(pk, 2) + CHECK_NULL_ARG(conversationKey, 3) + CHECK_INVALID_ARG(ctx->secpCtx) + + 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], + NCCryptoData* args +) +{ + CHECK_NULL_ARG(ctx, 0) + CHECK_NULL_ARG(conversationKey, 1) + CHECK_NULL_ARG(args, 2) + + //Validate the context + CHECK_INVALID_ARG(ctx->secpCtx) + + //Validte ciphertext/plaintext + CHECK_INVALID_ARG(args->inputData) + CHECK_INVALID_ARG(args->outputData) + CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3) + + return _encryptEx( + ctx, + _getSha256MdInfo(), + (struct conversation_key*)conversationKey, + args + ); +} + +NC_EXPORT NCResult NC_CC NCEncrypt( + const NCContext* ctx, + const NCSecretKey* sk, + const NCPublicKey* pk, + NCCryptoData* args +) +{ + NCResult result; + const mbedtls_md_info_t* mdInfo; + struct shared_secret sharedSecret; + struct conversation_key ck; + + CHECK_NULL_ARG(ctx, 0) + CHECK_NULL_ARG(sk, 1) + CHECK_NULL_ARG(pk, 2) + CHECK_NULL_ARG(args, 3) + + //Validate the context + CHECK_INVALID_ARG(ctx->secpCtx) + + //Validate input/output data + CHECK_INVALID_ARG(args->inputData) + CHECK_INVALID_ARG(args->outputData) + CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3) + + 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, &ck)) != NC_SUCCESS) + { + goto Cleanup; + } + + result = _encryptEx(ctx, mdInfo, &ck, args); + +Cleanup: + //Clean up sensitive data + ZERO_FILL(&sharedSecret, sizeof(sharedSecret)); + ZERO_FILL(&ck, sizeof(ck)); + + 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_NULL_ARG(conversationKey, 1) + CHECK_NULL_ARG(args, 2) + + //Validate the context + CHECK_INVALID_ARG(ctx->secpCtx) + + //Validte ciphertext/plaintext + CHECK_INVALID_ARG(args->inputData) + CHECK_INVALID_ARG(args->outputData) + CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_MESSAGE_SIZE, 3) + + 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_NULL_ARG(sk, 1) + CHECK_NULL_ARG(pk, 2) + CHECK_NULL_ARG(args, 3) + + //Validate the context + CHECK_INVALID_ARG(ctx->secpCtx) + + //Validte ciphertext/plaintext + CHECK_INVALID_ARG(args->inputData) + CHECK_INVALID_ARG(args->outputData) + CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_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; +} + diff --git a/src/noscrypt.h b/src/noscrypt.h new file mode 100644 index 0000000..8a43743 --- /dev/null +++ b/src/noscrypt.h @@ -0,0 +1,514 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: noscrypt +* Package: noscrypt +* File: noscrypt.h +* +* noscrypt is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published +* by the Free Software Foundation, either version 2 of the License, +* or (at your option) any later version. +* +* noscrypt 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 +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with noscrypt. If not, see http://www.gnu.org/licenses/. +*/ + +/* +* noscrypt is a an open-source, strict C89 library that performs the basic +* cryptographic operations found in the Nostr protocol. It is designed to be +* portable and easy to use in any C89 compatible environment. It is also designed +*/ + +#pragma once + +#ifndef NOSCRYPT_H +#define NOSCRYPT_H + +#include +#include + +#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) + #define IS_WINDOWS +#endif + +//Set api export calling convention (allow used to override) +#ifndef NC_CC + #ifdef IS_WINDOWS + //STD for importing to other languages such as .NET + #define NC_CC __stdcall + #else + #define NC_CC + #endif +#endif // !NC_CC + +#ifndef NC_EXPORT //Allow users to disable the export/impoty macro if using source code directly + #ifdef NOSCRYPT_EXPORTING + #ifdef IS_WINDOWS + #define NC_EXPORT __declspec(dllexport) + #else + #define NC_EXPORT __attribute__((visibility("default"))) + #endif // IS_WINDOWS + #else + #ifdef IS_WINDOWS + #define NC_EXPORT __declspec(dllimport) + #else + #define NC_EXPORT + #endif // IS_WINDOWS + #endif // !NOSCRYPT_EXPORTING +#endif // !NC_EXPORT + + +#ifndef IS_WINDOWS + #ifndef inline + #define inline __inline__ + #endif // !inline +#endif // !IS_WINDOWS + +//NULL +#ifndef NULL + #define NULL ((void*)0) +#endif // !NULL + +/* +* CONSTANTS +*/ +#define BIP340_PUBKEY_HEADER_BYTE 0x02 +#define NIP44_MESSAGE_KEY_SIZE 76 +#define NC_ENCRYPTION_NONCE_SIZE 32 +#define NC_SEC_KEY_SIZE 32 +#define NC_PUBKEY_SIZE 32 +#define NC_SHARED_SEC_SIZE 32 +#define NC_CONV_KEY_SIZE 32 +#define NC_MESSAGE_KEY_SIZE NIP44_MESSAGE_KEY_SIZE + +/* +* From spec +* https://github.com/nostr-protocol/nips/blob/master/44.md#decryption +*/ +#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 +* https://github.com/nostr-protocol/nips/blob/master/44.md#encryption +*/ +static const uint8_t Nip44ConstantSalt[8] = { 0x6e, 0x69, 0x70, 0x34, 0x34, 0x2d, 0x76, 0x32 }; + +/* +* ERROR CODES +* +* Error codes are 64bit integers. The lower 8 bits are reserved for +* the error code, and the upper 8 bits are reserved for the argument +* position. +* +* NCResult type is 64bit to also allow for positive return values for +* operations that return a value count. +*/ + +#define ARG_POSITION_OFFSET 8 +#define NC_ERROR_CODE_MASK 0xFF + +#define NC_SUCCESS 0 +#define E_NULL_PTR -1 +#define E_INVALID_ARG -2 +#define E_INVALID_CONTEXT -3 +#define E_ARGUMENT_OUT_OF_RANGE -4 + +/* +* Validation macros +*/ + +#define CHECK_NULL_PTR(ptr) if(ptr == NULL) return E_NULL_PTR; +#define CHECK_INVALID_ARG(x) if(x == NULL) return E_INVALID_ARG; +#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); + +#ifdef DEBUG + +//Must include assert.h for assertions +#include + +#define DEBUG_ASSERT(x) assert(x); +#define DEBUG_ASSERT2(x, message) assert(x && message); +#else +#define DEBUG_ASSERT(x) +#define DEBUG_ASSERT2(x, message) +#endif + +/* A compressed resul/return value, negative values +are failure, 0 is success and positive values are +defined by the operation. +*/ +typedef int64_t NCResult; + +/* + An secp256k1 secret key (aka 32byte private key buffer) +*/ +typedef struct secret_key_struct { + + uint8_t key[NC_SEC_KEY_SIZE]; + +}NCSecretKey; + +/* + An x-only secp256k1 public key +*/ +typedef struct xonly_pubkey_struct { + + uint8_t key[NC_PUBKEY_SIZE]; + +}NCPublicKey; + +/* + An opaque full library context object +*/ +typedef struct ctx_struct { + + void* secpCtx; + +}NCContext; + +/* +* The encryption arguments structure. This structure is used to pass +arguments to the encryption and decryption functions. It stores the +data buffers and required nonce used for the stream cipher. +*/ +typedef struct nc_encryption_struct { + + /* + * The nonce used for the stream cipher. + */ + uint8_t nonce[NC_ENCRYPTION_NONCE_SIZE]; + + /* The input data buffer to encrypt/decrypt */ + const void* inputData; + + /* The output data buffer to write data to */ + void* outputData; + + /* The size of the data buffers. Buffers must + * be the same size or larger than this value + */ + uint32_t dataSize; + +} NCCryptoData; + +/* + API FUNCTIONS +*/ + +static inline NCSecretKey* NCToSecKey(uint8_t key[NC_SEC_KEY_SIZE]) +{ + return (NCSecretKey*)key; +} + +static inline NCPublicKey* NCToPubKey(uint8_t key[NC_PUBKEY_SIZE]) +{ + return (NCPublicKey*)key; +} + +static inline NCResult NCResultWithArgPosition(NCResult err, uint8_t argPosition) +{ + //Store the error code in the lower 8 bits and the argument position in the upper 24 bits + return (err & NC_ERROR_CODE_MASK) | (((uint32_t)argPosition) << ARG_POSITION_OFFSET); +} + +/* +* Parses an error code and returns the error code and the argument position +that caused the error. +* @param result The error code to parse +* @param code A pointer to the error code to write to +* @param argPosition A pointer to the argument position to write to +*/ +NC_EXPORT void NC_CC NCParseErrorCode(NCResult result, int* code, int* argPosition) +{ + //Get the error code from the lower 8 bits and the argument position from the upper 8 bits + *code = result & NC_ERROR_CODE_MASK; + *argPosition = (result >> ARG_POSITION_OFFSET) & 0xFF; +} + +/*-------------------------------------- +* LIB CONTEXT API +*/ + +/* +* Runtime check for the size of the context struct to allow +for dynamic allocation when context size structure is not known. +* @return The size of the context struct in bytes +*/ +NC_EXPORT uint32_t NC_CC NCGetContextStructSize(void); +/* +* Initializes a context struct with the given entropy +* @param ctx A pointer to the context structure to initialize +* @param entropy The 32byte entropy to initialize the context with +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCInitContext( + NCContext* ctx, + const uint8_t entropy[32] +); +/* +* Reinitializes a context struct with the given +* @param ctx A pointer to the context structure to initialize +* @param entropy The 32byte entropy to initialize the context with +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCReInitContext( + NCContext* ctx, + const uint8_t entropy[32] +); + +/* +* Destroys a context struct +* @param ctx A pointer to the existing context structure to destroy +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCDestroyContext(NCContext* ctx); + + + +/*-------------------------------------- +* HIGH LEVEL SIGNING API +*/ + +/* +* Gets a 32byte x-only compressed public key from the given secret key +* @param ctx A pointer to the existing library context +* @param sk A pointer to the secret key +* @param pk A pointer to the compressed public key buffer to write to +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCGetPublicKey( + const NCContext* ctx, + const NCSecretKey* sk, + NCPublicKey* pk +); +/* +* Validates that a given secret key is valid according to the secp256k1 curve. This +is functionally the same as calling secp256k1_ec_seckey_verify. +* @param ctx A pointer to the existing library context +* @param sk A pointer to the secret key to verify +* @return NC_SUCCESS if the secret key is in a valid format, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCValidateSecretKey( + const NCContext* ctx, + const NCSecretKey* sk +); + + +/* +* Signs a raw message after computing the sha256 checksum using the +given secret key and writes the signature to the sig64 buffer. +* @param ctx A pointer to the existing library context +* @param sk A pointer to the secret key to sign with +* @param random32 A pointer to the 32byte random32 buffer to use for signing +* @param data A pointer to the raw data buffer to sign +* @param dataSize The size of the raw data buffer +* @param sig64 A pointer to the 64byte buffer to write the signature to +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCSignData( + const NCContext* ctx, + const NCSecretKey* sk, + const uint8_t random32[32], + const uint8_t* data, + const size_t dataSize, + uint8_t sig64[64] +); + +/* +* Verifies a signature of a raw data buffer matches the output using the given public key. +* @param ctx A pointer to the existing library context +* @param sig64 The 64byte signature to verify +* @param data A pointer to the raw data buffer to verify +* @param dataSize The size of the raw data buffer +* @param pk A pointer to the the x-only compressed public key (x-only serialized public key) +* @return NC_SUCCESS if the signature could be verified, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCVerifyData( + const NCContext* ctx, + const NCPublicKey* pk, + const uint8_t* data, + const size_t dataSize, + uint8_t sig64[64] +); + +/*-------------------------------------- +* EXTENDED SIGNING API +*/ + +/* +* Signs a message using the given secret key and writes the signature to the sig64 buffer +* @param ctx A pointer to the existing library context +* @param sk A pointer to the secret key to sign with +* @param random32 A pointer to the 32byte random32 buffer to use for signing +* @param digest32 A pointer to 32byte sha256 digest32 to sign +* @param sig64 A pointer to the 64byte buffer to write the signature to +* @return NC_SUCCESS if the operation was successful, otherwise an error code +*/ +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] +); + +/* +* Verifies a signature of a digest32 matches the output using the given public key. +Equivalent to calling secp256k1_schnorrsig_verify. +* @param ctx A pointer to the existing library context +* @param sig64 The 64byte signature to verify +* @param digest32 The 32byte digest32 to verify +* @param pk A pointer to the the x-only compressed public key (x-only serialized public key) +* @return NC_SUCCESS if the signature could be verified, otherwise an error code +*/ +NC_EXPORT NCResult NC_CC NCVerifyDigest( + const NCContext* ctx, + const NCPublicKey* pk, + const uint8_t digest32[32], + const uint8_t sig64[64] +); + + + +/*-------------------------------------- +* HIGH LEVEL ENCRYPTION API +*/ + +/* +* NOTES +* +* NIP-44 requires that plaintext/ciphertext must be padded in powers of 2. +* Since this library operates on data at the binary level, and does not do +* ANY runtime heap allocation, it is up to the user to ensure that the +* plaintext/ciphertext buffers are padded properly in The NCryptoData struct +* before calling the encryption/decryption functions. +*/ + +/* +* High level api for encrypting nostr messages using a secret key and a public key. Use +the NCEncryptEx functions for extended encryption functionality +* @param ctx The library context +* @param sk The secret key (the local private key) +* @param pk The 32byte compressed public key (x-only serialized public key) the other user's public key +* @param args The encryption 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 NCEncrypt( + const NCContext* ctx, + const NCSecretKey* sk, + const NCPublicKey* pk, + NCCryptoData* args +); + +/* +* High level api for decrypting nostr messages using a secret key and a public key. Use +the NCDecryptEx functions for extended decryption functionality. +* @param ctx The library context +* @param sk The secret key (the local private key) +* @param pk The 32byte compressed public key (x-only serialized public key) the other user's public key +* @param args The decryption 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 NCDecrypt( + const NCContext* ctx, + const NCSecretKey* sk, + const NCPublicKey* pk, + NCCryptoData* args +); + + +/*-------------------------------------- +* EXTENDED ENCRYPTION API +*/ + +/* +* Computes a NIP-44 shared secret from a secret key and a public key and +stores it in the sharedPoint buffer. +* @param ctx A pointer to the existing library context +* @param sk The secret key +* @param pk The 32byte compressed public key (x-only serialized public key) +* @param sharedPoint The 32byte buffer to store write the secret data 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 NC_CC NCGetSharedSecret( + const NCContext* ctx, + const NCSecretKey* sk, + const NCPublicKey* pk, + uint8_t sharedPoint[NC_SHARED_SEC_SIZE] +); + +/* +* Computes a NIP-44 conversation key from the local secret key and the remote +public key, and stores it in the conversationKey buffer. +* @param ctx A pointer to the existing library context +* @param sk A pointer to the 32byte the secret key +* @param pk A pointer to the 32byte compressed public key (x-only serialized public key) +* @param conversationKey The 32byte buffer to store write the conversation key 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 NC_CC NCGetConversationKey( + const NCContext* ctx, + const NCSecretKey* sk, + const NCPublicKey* pk, + uint8_t conversationKey[NC_CONV_KEY_SIZE] +); +/* +* Computes a NIP-44 conversation key a shared secret/point, and stores it in the +conversationKey buffer. +* @param ctx A pointer to the existing library context +* @param sharedPoint A pointer to the 32byte shared secret/point +* @param conversationKey The 32byte buffer to store write the conversation key 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 NC_CC NCGetConversationKeyEx( + const NCContext* ctx, + const uint8_t sharedPoint[NC_SHARED_SEC_SIZE], + uint8_t conversationKey[NC_CONV_KEY_SIZE] +); + +/* +* Encrypts a message using the given conversation key and writes the encrypted message to the +* output buffer. The output buffer must be at least 99 bytes in size. +* @param ctx A pointer to the existing library context +* @param conversationKey A pointer to the 32byte conversation key +* @param args A pointer to the encryption arguments structure +* @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 NCEncryptEx( + const NCContext* ctx, + const uint8_t conversationKey[NC_CONV_KEY_SIZE], + NCCryptoData* args +); + +/* +* Decrypts a message using the given conversation key and writes the decrypted message to the +* output buffer. +* @param ctx A pointer to the existing library context +* @param conversationKey A pointer to the 32byte conversation key +* @param args A pointer to the decryption arguments structure +* @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 NCDecryptEx( + const NCContext* ctx, + const uint8_t conversationKey[NC_CONV_KEY_SIZE], + NCCryptoData* args +); + +#endif // !NOSCRYPT_H -- cgit