From e7375560d465f6da71aae0483c0e7a72535ccc10 Mon Sep 17 00:00:00 2001 From: vnugent Date: Sat, 4 May 2024 14:06:06 -0400 Subject: Squashed commit of the following: commit 0a40e209d03e8ff9b6f81cd5969d3e845c633bfc Author: vnugent Date: Sat May 4 13:55:19 2024 -0400 ci: Force disable testing for win ci builds commit 55fae189fffc86f07a3448370f0a746670819712 Author: vnugent Date: Thu May 2 21:54:35 2024 -0400 feat: Working and tested openssl impl & defaults commit 6ff8bb11774c51fd341b7699a3938fd894995fbf Author: vnugent Date: Thu Apr 25 17:45:42 2024 -0400 refactor: Finish support and testing for mbedtls commit 7cb7a93de4f6f5e741bc5129e3d928e44f050930 Author: vnugent Date: Tue Apr 23 18:19:31 2024 -0400 refactor!: MbedTLS on Windows, switch to uint32 commit 30e8dda6cbea86bdee6d5dfe48514385d3b9f81b Author: vnugent Date: Tue Apr 23 14:48:05 2024 -0400 refactor: Crypto dep redesign working on Windows commit d09c6c1bd5da3e2d79351daeba304ca99976a726 Author: vnugent Date: Thu Apr 18 00:28:51 2024 -0400 refactor!: Pushing what I have to dev commit 54e06ada7d624ed0d28c6a6db04a149708841bf8 Author: vnugent Date: Sat Apr 13 01:24:00 2024 -0400 fix: convert constants to hex, inline macro, ParseErrorCode commit 4215e3100d9a0d23119080d09638fa5b60d0c6d4 Merge: d3328f4 7485aa5 Author: vnugent Date: Wed Apr 3 18:26:30 2024 -0400 Merge branch 'master' into develop commit d3328f4152b22b28f24c43dda62464287f1efff5 Author: vnugent Date: Wed Apr 3 18:22:56 2024 -0400 build: Included dependency and versions in client builds commit b11bc0bac955fd5c6db65f0da48456bf5e748805 Author: vnugent Date: Wed Apr 3 18:10:08 2024 -0400 fix: Fix c89 compatabilty comments and struct assignment commit 9915bd41799a72413e6b400e150aa9f5fa797e25 Merge: 8e3d6ea 5184d7d Author: vnugent Date: Sat Mar 30 09:57:30 2024 -0400 Merge branch 'master' into develop commit 8e3d6ea5e3c83fe42cb904b6ccc4fe2b73f76aae Author: vnugent Date: Sat Mar 30 09:52:55 2024 -0400 refactor!: Some api (struct) changes and updated tests commit e88e8420520204e20802516f01d4488bb0b1d6ea Merge: 490dfee 21f6c0a Author: vnugent Date: Sun Mar 3 15:02:34 2024 -0500 Merge branch 'master' into develop commit 490dfee4ef22479009627435c6ad728c3cbbab54 Author: vnugent Date: Sun Mar 3 14:59:25 2024 -0500 test: #3 tests for encryption/description and Macs commit efa97490b7ed47f4e2f05bee52e2b33e14e439e6 Merge: 1b84e3c 120022a Author: vnugent Date: Sun Mar 3 14:55:48 2024 -0500 merge master commit 1b84e3c7c2e55b1ff9ffdd09b66873e11c131441 Author: vnugent Date: Sat Mar 2 22:57:36 2024 -0500 fix: #2 constent usage of sizeof() operator on struct types commit 9de5a214c66adea0ef2d0bac63c59449de202a88 Author: vnugent Date: Fri Mar 1 14:30:36 2024 -0500 perf: avoid nc_key struct copy, cast and verify instead commit b917b761120ed684af28d0707673ffadcf14b8fe Author: vnugent Date: Mon Feb 12 22:06:50 2024 -0500 fix: found the constant time memcompare function commit 9f85fff3b9f25da7410569ea94f994b88feb3910 Author: vnugent Date: Fri Feb 9 22:48:35 2024 -0500 feat: added/update MAC functions to sign or verify nip44 payload commit aa5113741bb419b02d6ea416bba571fa3d65db46 Author: vnugent Date: Wed Feb 7 01:37:53 2024 -0500 add missing hmac-key output buffer commit 55f47d22cc9ce4d1e22b70814d608c7ef3b1bbc9 Author: vnugent Date: Sun Feb 4 21:08:13 2024 -0500 simple bug fixes, and public api argument validation tests commit 73c5a713fb164ae8b4ac8a891a8020e08eae0a3b Author: vnugent 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 Date: Fri Feb 2 19:25:17 2024 -0500 change to lgpl license commit 6e79fdb3b6b6739fc7797d47e55a7691306cf736 Author: vnugent Date: Wed Jan 31 21:30:49 2024 -0500 move validation macros, and optionally disable them commit ac1e58837f1ba687939f78b5c03cadd346c10ddd Author: vnugent Date: Tue Jan 30 12:25:05 2024 -0500 couple more tests, renable range checks, set flags for all projects --- include/noscrypt.h | 570 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 570 insertions(+) create mode 100644 include/noscrypt.h (limited to 'include/noscrypt.h') diff --git a/include/noscrypt.h b/include/noscrypt.h new file mode 100644 index 0000000..4d03b8d --- /dev/null +++ b/include/noscrypt.h @@ -0,0 +1,570 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Package: noscrypt +* File: noscrypt.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 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 +#include "platform.h" + +/* Set api export calling convention (allow used to override) */ +#ifndef NC_CC + #ifdef _NC_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 _NC_IS_WINDOWS + #define NC_EXPORT __declspec(dllexport) + #else + #define NC_EXPORT __attribute__((visibility("default"))) + #endif /* _NC_IS_WINDOWS */ + #else + #ifdef _NC_IS_WINDOWS + #define NC_EXPORT __declspec(dllimport) + #else + #define NC_EXPORT + #endif /* _NC_IS_WINDOWS */ + #endif /* !NOSCRYPT_EXPORTING */ +#endif /* !NC_EXPORT */ + +/* +* CONSTANTS +*/ +#define BIP340_PUBKEY_HEADER_BYTE 0x02 +#define NIP44_MESSAGE_KEY_SIZE 0x4c /*32 + 12 + 32 = 76 */ +#define NC_ENCRYPTION_NONCE_SIZE 0x20 +#define NC_SEC_KEY_SIZE 0x20 +#define NC_PUBKEY_SIZE 0x20 +#define NC_CONTEXT_ENTROPY_SIZE 0x20 +#define NC_SHARED_SEC_SIZE 0x20 +#define NC_CONV_KEY_SIZE 0x20 +#define NC_HMAC_KEY_SIZE 0x20 +#define NC_ENCRYPTION_MAC_SIZE 0x20 +#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 0x01 +#define NIP44_MAX_ENC_MESSAGE_SIZE 0xffff + +#define NC_ENC_VERSION_NIP04 0x04 +#define NC_ENC_VERSION_NIP44 0x2c + +/* +* 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 NC_ARG_POSITION_OFFSET 0x08 +#define NC_ERROR_CODE_MASK 0xFF + +#define NC_SUCCESS 0x00 +#define E_NULL_PTR -1 +#define E_INVALID_ARG -2 +#define E_INVALID_CONTEXT -3 +#define E_ARGUMENT_OUT_OF_RANGE -4 +#define E_OPERATION_FAILED -5 +#define E_VERSION_NOT_SUPPORTED -6 + + +/* 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 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. */ + const uint8_t* nonce32; + + /* Writes the hmac key to the buffer during encryption events. + Set to NULL on decryption */ + uint8_t* hmacKeyOut32; + + /* The input data buffer to encrypt/decrypt */ + const uint8_t* inputData; + + /* The output data buffer to write data to */ + uint8_t* outputData; + + /* The size of the data buffers. Buffers must + * be the same size or larger than this value + */ + uint32_t dataSize; + + /* The version of the encryption standard to use */ + uint32_t version; + +} NCEncryptionArgs; + +/* +* 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 */ + const uint8_t* mac32; + + /* The nonce used for the original message encryption */ + const uint8_t* nonce32; + + /* The message payload data */ + const uint8_t* payload; + + /* The size of the payload data */ + uint32_t payloadSize; + +} NCMacVerifyArgs; + + +/* + API FUNCTIONS +*/ + +/* +* A helper function to cast a buffer to a NCSecretKey struct +* @param key The buffer to cast +* @return A pointer to the NCSecretKey struct +*/ +static _nc_fn_inline NCSecretKey* NCToSecKey(uint8_t key[NC_SEC_KEY_SIZE]) +{ + return (NCSecretKey*)key; +} + +/* +* A helper function to cast a buffer to a NCPublicKey struct +* @param key The buffer to cast +* @return A pointer to the NCPublicKey struct +*/ +static _nc_fn_inline NCPublicKey* NCToPubKey(uint8_t key[NC_PUBKEY_SIZE]) +{ + return (NCPublicKey*)key; +} + +static _nc_fn_inline NCResult NCResultWithArgPosition(NCResult err, uint8_t argPosition) +{ + return -(((NCResult)argPosition << NC_ARG_POSITION_OFFSET) | -err); +} + +/* +* 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 argPositionOut A pointer to the argument position to write to +* @return The error code +*/ +static _nc_fn_inline int NCParseErrorCode(NCResult result, uint8_t* argPositionOut) +{ + NCResult asPositive; + int code; + + /* convert result to a positive value*/ + asPositive = -result; + + /* Get the error code from the lower 8 bits and the argument position from the upper 8 bits*/ + code = -(asPositive & NC_ERROR_CODE_MASK); + *argPositionOut = (asPositive >> NC_ARG_POSITION_OFFSET) & 0xFF; + + return code; +} + +/*-------------------------------------- +* 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 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[NC_CONTEXT_ENTROPY_SIZE] +); +/* +* Reinitializes a context struct with the given +* @param ctx A pointer to the context structure to initialize +* @param entropy The 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[NC_CONTEXT_ENTROPY_SIZE] +); + +/* +* 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 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 1 if the secret key is valid, 0 if it is not, 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 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 64-byte 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 uint32_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 uint32_t dataSize, + const 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 random32 buffer to use for signing +* @param digest32 A pointer to sha256 digest32 to sign +* @param sig64 A pointer to the 64-byte 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 A pointer to the 64-byte signature to verify +* @param digest32 A pointer to a 32-byte message digest 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 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, + NCEncryptionArgs* 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 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, + NCEncryptionArgs* 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 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 +*/ + +/* +* 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 compressed public key (x-only serialized public key) +* @param sharedPoint The 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 the secret key +* @param pk A pointer to the compressed public key (x-only serialized public key) +* @param conversationKey The 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 shared secret/point +* @param conversationKey The 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 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], + NCEncryptionArgs* 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 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], + NCEncryptionArgs* 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 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 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 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, + uint32_t payloadSize, + uint8_t hmacOut[NC_ENCRYPTION_MAC_SIZE] +); + +#endif /* !NOSCRYPT_H */ -- cgit