diff options
author | vnugent <public@vaughnnugent.com> | 2024-04-03 18:26:11 -0400 |
---|---|---|
committer | vnugent <public@vaughnnugent.com> | 2024-04-03 18:26:11 -0400 |
commit | 7485aa5a43476c47d54ec51fb96751a14e0ed629 (patch) | |
tree | 9ae8f27b5e0ed25eb9891877fda123b9027e843f | |
parent | 5184d7db93131056215b9263740f4806495f148c (diff) |
Squashed commit of the following:
commit d3328f4152b22b28f24c43dda62464287f1efff5
Author: vnugent <public@vaughnnugent.com>
Date: Wed Apr 3 18:22:56 2024 -0400
build: Included dependency and versions in client builds
commit b11bc0bac955fd5c6db65f0da48456bf5e748805
Author: vnugent <public@vaughnnugent.com>
Date: Wed Apr 3 18:10:08 2024 -0400
fix: Fix c89 compatabilty comments and struct assignment
commit 9915bd41799a72413e6b400e150aa9f5fa797e25
Merge: 8e3d6ea 5184d7d
Author: vnugent <public@vaughnnugent.com>
Date: Sat Mar 30 09:57:30 2024 -0400
Merge branch 'master' into develop
commit 8e3d6ea5e3c83fe42cb904b6ccc4fe2b73f76aae
Author: vnugent <public@vaughnnugent.com>
Date: Sat Mar 30 09:52:55 2024 -0400
refactor!: Some api (struct) changes and updated tests
commit e88e8420520204e20802516f01d4488bb0b1d6ea
Merge: 490dfee 21f6c0a
Author: vnugent <public@vaughnnugent.com>
Date: Sun Mar 3 15:02:34 2024 -0500
Merge branch 'master' into develop
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.txt | 19 | ||||
-rw-r--r-- | Module.Taskfile.yaml | 11 | ||||
-rw-r--r-- | README.md | 83 | ||||
-rw-r--r-- | Taskfile.yaml | 118 | ||||
-rw-r--r-- | src/noscrypt.c | 171 | ||||
-rw-r--r-- | src/noscrypt.h | 22 | ||||
-rw-r--r-- | tests/hex.h | 12 | ||||
-rw-r--r-- | tests/test.c | 140 |
8 files changed, 361 insertions, 215 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index f9a1642..e6034a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,8 @@ set(CMAKE_C_STANDARD 90) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) +target_compile_features(${CMAKE_PROJECT_NAME} PUBLIC c_std_90) + #if debug add_compile_definitions($<$<CONFIG:Debug>:DEBUG>) @@ -84,6 +86,7 @@ unset(SECP256K1_LIB CACHE) find_library(SECP256K1_LIB NAMES secp256k1 libsecp256k1 lib_secp256k1 + PATHS ${LOCAL_SECP256K1_DIR}/src ) if(NOT SECP256K1_LIB) @@ -93,13 +96,18 @@ endif() message(STATUS "secp256k1 library found at ${SECP256K1_LIB}") target_link_libraries(${CMAKE_PROJECT_NAME} ${SECP256K1_LIB}) - #link mbedtls and mbedcrypto shared libraries unset(MBEDCRYPTO_LIB CACHE) unset(MBEDTLS_LIB CACHE) -find_library(MBEDTLS_LIB NAMES mbedtls libmbedtls) -find_library(MBEDCRYPTO_LIB NAMES mbedcrypto libmbedcrypto) +find_library(MBEDTLS_LIB + NAMES mbedtls libmbedtls + PATHS ${LOCAL_MBEDTLS_DIR}/library +) +find_library(MBEDCRYPTO_LIB + NAMES mbedcrypto libmbedcrypto + PATHS ${LOCAL_MBEDTLS_DIR}/library +) if(NOT MBEDCRYPTO_LIB) message(FATAL_ERROR "mbedcrypto library not found on local system") @@ -113,17 +121,18 @@ message(STATUS "mbedcrypto library found at ${MBEDCRYPTO_LIB}") target_link_libraries(${CMAKE_PROJECT_NAME} ${MBEDCRYPTO_LIB} ${MBEDTLS_LIB}) - #TESTS if(BUILD_TESTS) #add test executable and link to library add_executable(nctest tests/test.c) target_link_libraries(nctest ${CMAKE_PROJECT_NAME}) - #link mbedtls crypto sahred library + #link mbedtls crypto shared library directly target_link_libraries(nctest ${MBEDCRYPTO_LIB} ${MBEDTLS_LIB}) target_include_directories(nctest PRIVATE "src") + #enable c11 for testing + target_compile_features(nctest PRIVATE c_std_11) endif() diff --git a/Module.Taskfile.yaml b/Module.Taskfile.yaml index 5da29ee..0a80e30 100644 --- a/Module.Taskfile.yaml +++ b/Module.Taskfile.yaml @@ -15,25 +15,20 @@ tasks: #called by build pipeline to sync repo update: cmds: - - git remote update - git reset --hard + - git remote update - git pull origin {{.BRANCH_NAME}} --verify-signatures - #called by build pipeline to build module build: cmds: - echo "building module {{.MODULE_NAME}}" - postbuild_success: + publish: cmds: - - #git archive in the module binry output directory + #git archive in the module directory - git archive --format {{.ARCHIVE_FILE_FORMAT}} --output {{.ARCHIVE_FILE_NAME}} HEAD - postbuild_failed: - cmds: - - echo "postbuild failed {{.MODULE_NAME}}" #called by build pipeline to clean module clean: @@ -1,10 +1,8 @@ # noscrypt *A compact, C90 cross-platform, cryptography library built specifically for nostr* -At the moment this library is a work in progress, and will be more extensively tested using the suggested nip-44 vector files in [NVault](https://github.com/VnUgE/NVault) - ## What is noscrypt? -A high-level C utility library built specifically for nostr cryptography operations such as those defined in NIP-01 and the new NIP-44. It was designed to simplify the operations that the secp256k1 library was used for, along with data encryption for the new sepc. +A high-level C utility library built specifically for nostr cryptography operations such as those defined in NIP-01 and the new NIP-44. It was designed to simplify the operations that the secp256k1 library was used for, along with data encryption for the new sepc. It is also being built embedded in mind. API Example: ```C @@ -14,6 +12,8 @@ NCSignData() NCVerifyData() NCEncrypt() NCDecrypt() +NCComputeMac() +NCVerifyMac() ... extended functions ``` @@ -24,6 +24,18 @@ At the time of building this project I have not come across any C-only libraries I wanted a compact and efficient utility library that was portable across systems and runtimes. I will primarily be using this library in a .NET environment, but would like to make a hardware signer sometime. +### Testing +Testing is an will be important to a cryptography library, I take that responsibility seriously. There are some basic api validation and correctness tests that can be built into an executable called nctest. Full automated testing suite is done in C# interop as part of my [NVault](https://github.com/vnuge/nvault) package. This includes testing against the official nip44 [vector file](https://github.com/paulmillr/nip44/blob/main/nip44.vectors.json). I'm very dependency adverse so native C90 testing using only stdlibs can get gross in a hurry. It will likely happen in the future but not right now. + +### Hardness +- Time sensitive verification always uses fixed time comparison +- No explicit/dynamic memory allocations +- Public API function input validation is on by default +- All stack allocated structures are securely zeroed before return +- Stack protection is enabled by default for GCC and MSVC compilers (also for deps) +- Schnorr signatures are validated before the signing function returns +- Carefully selected, widley used, tested, and audited dependencies + ### Dependency choices I carefully chose [mbedTls](https://github.com/Mbed-TLS/mbedtls) and [libsecp256k1](https://github.com/bitcoin-core/secp256k1) for the following reasons - Modern, well tested and well trusted @@ -33,8 +45,6 @@ I carefully chose [mbedTls](https://github.com/Mbed-TLS/mbedtls) and [libsecp256 - Simple installations - Great cross-platform build support -Initially I wanted to use [MonoCypher](https://monocypher.org/) for its compatibility and compactness but it did not have support for hdkf which is required for NIP-44. - ### Future Goals - Good support for embedded platforms that wish to implement nostr specific features (would be fun!) - Over all better testing suite @@ -45,47 +55,66 @@ GitHub is simply a mirror for my projects. Extended documentation, pre-compiled [Docs and Articles](https://www.vaughnnugent.com/resources/software/articles?tags=docs,_noscrypt) [Builds and Source](https://www.vaughnnugent.com/resources/software/modules/noscrypt) -## Getting the package +### Getting the package There are 3 ways to get the source code to build this project. -1. Clone the GitHub repo `git clone https://github.com/VnUgE/noscrypt.git` -2. Download an archive from my website above +1. Download the package from my website above (recommended) +2. Clone the GitHub repo `git clone https://github.com/VnUgE/noscrypt.git` 3. Download a github archive or release when they are available -## Compilation -This project was built from the start using cmake as the build platform so it is easily cross platform. Builds produce a shared library and a static library so you can choose how to link it with your project. +## Building +This project was built from the start using cmake as the build generator so it is easily cross platform. Builds produce a shared library and a static library so you can choose how to link it with your project. + +*Extended documentation includes more exhaustive build conditions and supported platforms* ### Prerequisites Before building this library you must install the following dependencies -- [secp256k1](https://github.com/bitcoin-core/secp256k1) -- [mbedtls](https://github.com/Mbed-TLS/mbedtls) +- [task](https://taskfile.dev/installation/) - build exec tool +- git +- [cmake](https://cmake.org) +- Your preferred C compiler. Currently supports GCC and MSVC -These libraries must be installed where cmake can find them, the easiest way is to just install them globally. So for Windows, this means the .lib files need to be available on the system PATH or safe search directories. The build process will fail if those libraries are not available. Follow the instructions for building and installing the libraries using `cmake` before continuing. For Linux libraries must be available in one of the the `lib/` base directories. +>[!NOTE] +>The build process will install dependencies locally (in a deps/ dir) and verify the file hashes. Read extended documentation for installing dependencies manually/globally. -*It is recommended to download the release archives of mbedtls and secp256k1 instead of cloning the repositories.* +### Instructions +After Task is installed you can run the following commands to execute the build steps. I test build steps against Debian, Ubuntu, Fedora, Windows 10 and Windows Server 2019 targets. If you have a platform that is having issues please get in touch. -### Windows users -Windows users can download pre-compiled x64 binaries from my website above when a build is run. You will still need to manually install dependencies +>[!TIP] +> Run `task --list-all` to see all available build commands -### Instructions -Use the following cmake commands to generate and compile the library on your system. This assumes you are in the directory containing the `CMakeLists.txt` file -```shell -cmake -B./build/ -cmake --build build/ --config Release +#### Normal build +The following command will install dependencies and build the libraries in release mode +``` shell +task #or task build ``` -By default building of the test executables are disabled. At the moment testing is very basic, but will grow as time goes on. To enable testing set the `-DENABLE_TESTS=ON` flag during the first stage generation process -```shell -cmake -B./build/ -DENABLE_TESTS=ON +#### Build tests in debug mode +>[!WARNING] +> You may want to clean the entire project before rebuilding in debug mode to cleanup caches +``` shell +task build-tests ``` -This will produce the `nctests` executable file in the build directory. This will likely change a bit in the future. +#### Cleanup +You can delete all build related data (including dependencies) and start over +``` shell +task clean +``` +The task file is configured to cache your dependencies once they are built. If you have issues with a download and need to re-run a command, try using `task <cmd> --force` to override the build caching. + +#### All done +Once building is complete, your library files should be located under `build/libnoscrypt` or `build/Release/noscrypt.dll` on Windows ## Notes -**Builds** build packages on my website are "manual" I use an internal tool called *vnbuild* that just does the work of preparing a package, but I have to run it myself. +#### Builds +Build packages on my website are "manual" I use an internal tool called *vnbuild* that just does the work of preparing a package, but I have to run it myself. -### Branches +#### Branches There are currently 2 branches I use because of my build process. `develop` and `master`. All changes happen in develop, then are merged to master when I feel like they are stable enough. After some testing and time, a tag and release will become available. +#### Windows Dlls +You may notice that I have msvc pre-compiled packages available for download. I have not compatibility tested them yet so they should only support Windows 10/Server version 1904 running amd64 processors. + ## License The software in this repository is licensed to you under the GNU Lesser GPL v2.1 or later. `SPDX-License-Identifier: LGPL-2.1-or-later` see the [LICENSE](LICENSE) file for more details. diff --git a/Taskfile.yaml b/Taskfile.yaml index a1e5b6d..9e48427 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -12,18 +12,106 @@ version: '3' +vars: + INSTALL_DIR: 'deps/' + + #mbed tls variables + MBEDTLS_PACK_URL: 'https://github.com/Mbed-TLS/mbedtls/releases/download/v3.6.0/mbedtls-3.6.0.tar.bz2' + MBEDTLS_PACK_SHA: '3ecf94fcfdaacafb757786a01b7538a61750ebd85c4b024f56ff8ba1490fcd38' + MBED_TLS_VERSION: '3.6.0' + MBED_TLS_DIR: '{{.INSTALL_DIR}}mbedtls-{{.MBED_TLS_VERSION}}' + + #secp256k1 variables + SECP256K1_PACK_URL: 'https://github.com/bitcoin-core/secp256k1/archive/refs/tags/v0.4.1.tar.gz' + SECP256K1_PACK_SHA: '31b1a03c7365dbce7aff4be9526243da966c58a8b88b6255556d51b3016492c5' + SECP256K1_VERSION: '0.4.1' + SCP256K1_DIR: '{{.INSTALL_DIR}}secp256k1-{{.SECP256K1_VERSION}}' + tasks: default: desc: "Build the library for your system" + deps: + - install cmds: - - cmake -S . -B./build/ -DCMAKE_BUILD_TYPE=Release - - cmake --build build/ --config Release - - cmd: echo "Build complete your files can be found in the build/ directory" - silent: true + - task: build-local + vars: { CMAKE_TEST_STATUS: 'Off', BUILD_CONFIG: 'Release' } + + build-tests: + desc: "Build libraries and test executable in debug mode" + deps: + - install + cmds: + - task: build-local + vars: { CMAKE_TEST_STATUS: 'On', BUILD_CONFIG: 'Debug' } + + build-local: + internal: true + cmds: + - cmake -S . -B./build/ -DCMAKE_BUILD_TYPE={{.BUILD_CONFIG}} -DBUILD_TESTS={{.CMAKE_TEST_STATUS}} -DLOCAL_MBEDTLS_DIR={{.MBED_TLS_DIR}}/build -DLOCAL_SECP256K1_DIR={{.SCP256K1_DIR}}/build + - cmake --build build/ --config {{.BUILD_CONFIG}} + - cmd: echo "Build complete your files can be found in the build/ directory" + silent: true + + install: + desc: 'Installs dependencies locally' + cmds: + #make install dir + - cmd: powershell -Command "mkdir {{.INSTALL_DIR}} -Force" + platforms: [windows] + - cmd: mkdir -p {{.INSTALL_DIR}} + platforms: [linux, darwin] + + #nstall deps locally + - task: install-mbedtls + - task: install-secp256k1 + + install-mbedtls: + internal: true + sources: + - '{{.MBED_TLS_DIR}}/*.*' + cmds: + #downlaod mbedtls + - cd {{.INSTALL_DIR}} && curl -L -o mbedtls.tar.bz2 {{.MBEDTLS_PACK_URL}} + + - cmd: cd {{.INSTALL_DIR}} && echo "{{.MBEDTLS_PACK_SHA}} mbedtls.tar.bz2" | sha256sum -c + platforms: [linux, darwin] + - cmd: cd {{.INSTALL_DIR}} && certutil -hashfile mbedtls.tar.bz2 + platforms: [windows] + + #extract mbedtls + - cd {{.INSTALL_DIR}} && tar -xjf mbedtls.tar.bz2 + + #build using cmake + - cd {{.MBED_TLS_DIR}} && cmake -Bbuild/ -DUSE_SHARED_MBEDTLS_LIBRARY=On -DENABLE_TESTING=Off -DENABLE_PROGRAMS=Off -DCMAKE_BUILD_TYPE=Release + - cd {{.MBED_TLS_DIR}} && cmake --build build/ + + install-secp256k1: + internal: true + sources: + - '{{.SCP256K1_DIR}}/*.*' + cmds: + #downlaod mbedtls + - cd {{.INSTALL_DIR}} && curl -L -o secp56k1.tgz {{.SECP256K1_PACK_URL}} + + - cmd: cd {{.INSTALL_DIR}} && echo "{{.SECP256K1_PACK_SHA}} secp56k1.tgz" | sha256sum -c + platforms: [linux, darwin] + - cmd: cd {{.INSTALL_DIR}} && certutil -hashfile secp56k1.tgz + platforms: [windows] + + #extract mbedtls + - cd {{.INSTALL_DIR}} && tar -xzf secp56k1.tgz + + #build using cmake + - cd {{.SCP256K1_DIR}} && cmake -Bbuild/ -DSECP256K1_ENABLE_MODULE_SCHNORRSIG=ON -DCMAKE_BUILD_TYPE=Release + - cd {{.SCP256K1_DIR}} && cmake --build build/ + + +#CI ONLY!! #called by build pipeline to build module build: + desc: "DO NOT RUN! CI Only" cmds: - echo "building project {{.PROJECT_NAME}}" - cmd: powershell -Command "mkdir bin/ -Force" @@ -37,16 +125,29 @@ tasks: clean: desc: "Cleans the artifact directory" + ignore_error: true + cmds: + - for: [ bin/, build/, deps/] + task: clean-internal + vars: { FILE: '{{.ITEM}}'} + + + clean-internal: + internal: true + ignore_error: true cmds: - - cmd: powershell -Command "rm -r bin/ -Force" - ignore_error: + - cmd: rm -rf '{{.FILE}}' + platforms: [linux, darwin] + + - cmd: powershell rm -Recurse '{{.FILE}}' + platforms: [windows] build_win_x64: internal: true vars: - TARGET_DLL: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-win64.tgz' + TARGET_DLL: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/msvc-x64-release-{{.PROJECT_NAME}}.tgz' DLL_FILES: '{{.PROJECT_NAME}}.dll {{.PROJECT_NAME}}.lib license.txt' - TARGET_STATIC: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-win64-static.tgz' + TARGET_STATIC: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/msvc-x64-release-{{.PROJECT_NAME}}-static.tgz' STATIC_FILES: '{{.PROJECT_NAME}}_static.lib license.txt' BUILD_DIR: 'out/build/win-x64' @@ -76,3 +177,4 @@ tasks: #tar up the source - tar -czf "{{.TARGET_SOURCE}}" {{.SOURCE_FILES}} +
\ No newline at end of file diff --git a/src/noscrypt.c b/src/noscrypt.c index d63fe53..8aeeefe 100644 --- a/src/noscrypt.c +++ b/src/noscrypt.c @@ -23,7 +23,7 @@ #include <secp256k1_ecdh.h> #include <secp256k1_schnorrsig.h> -//Setup mbedtls +/* Setup mbedtls */ #include <mbedtls/platform_util.h> #include <mbedtls/md.h> #include <mbedtls/hkdf.h> @@ -35,22 +35,22 @@ /* Non win platforms may need an inline override */ #if !defined(_NC_IS_WINDOWS) && !defined(inline) #define inline __inline__ -#endif // !IS_WINDOWS +#endif /* !IS_WINDOWS */ -//NULL +/* NULL */ #ifndef NULL #define NULL ((void*)0) -#endif // !NULL +#endif /* !NULL */ -#define CHACHA_NONCE_SIZE 12 //Size of 12 is set by the cipher spec -#define CHACHA_KEY_SIZE 32 //Size of 32 is set by the cipher spec +#define CHACHA_NONCE_SIZE 12 /* Size of 12 is set by the cipher spec */ +#define CHACHA_KEY_SIZE 32 /* Size of 32 is set by the cipher spec */ /* * Local macro for secure zero buffer fill */ #define ZERO_FILL(x, size) mbedtls_platform_zeroize(x, size) -//Include string for memmove +/* Include string for memmove */ #include <string.h> #define MEMMOV(dst, src, size) memmove(dst, src, size) @@ -63,11 +63,11 @@ #define CHECK_NULL_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_NULL_PTR, argPos); #define CHECK_ARG_RANGE(x, min, max, argPos) if(x < min || x > max) return NCResultWithArgPosition(E_ARGUMENT_OUT_OF_RANGE, argPos); #else - //empty macros + /* empty macros */ #define CHECK_INVALID_ARG(x) #define CHECK_NULL_ARG(x, argPos) #define CHECK_ARG_RANGE(x, min, max, argPos) -#endif // !NC_DISABLE_INPUT_VALIDATION +#endif /* !NC_DISABLE_INPUT_VALIDATION */ #ifdef DEBUG @@ -88,7 +88,7 @@ */ #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L #define STATIC_ASSERT(x, m) static_assert(x, m) - #else + #elif !defined(STATIC_ASSERT) #define STATIC_ASSERT(x, m) #pragma message("Static assertions are not supported by this language version") #endif @@ -137,7 +137,7 @@ static inline int _convertToXonly(const NCContext* ctx, const NCPublicKey* compr 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 + /* Parse the public key into the x-only structure */ return secp256k1_xonly_pubkey_parse(ctx->secpCtx, xonly, compressedPubKey->key); } @@ -150,15 +150,15 @@ static int _convertToPubKey(const NCContext* ctx, const NCPublicKey* compressedP 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 + /* 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) + /* Copy the compressed public key data into a new buffer (offset by 1 to store the header byte) */ MEMMOV((compressed + 1), compressedPubKey, sizeof(NCPublicKey)); result = secp256k1_ec_pubkey_parse(ctx->secpCtx, pubKey, compressed, sizeof(compressed)); - //zero everything + /* zero everything */ ZERO_FILL(compressed, sizeof(compressed)); return result; @@ -191,16 +191,16 @@ static int _edhHashFuncInternal( void* data ) { - ((void)y32); //unused for nostr + ((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 + /* 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 + return 32; /* Return the number of bytes written to the output buffer */ } static NCResult _computeSharedSecret( @@ -218,7 +218,7 @@ static NCResult _computeSharedSecret( DEBUG_ASSERT(otherPk != NULL) DEBUG_ASSERT(sharedPoint != NULL) - //Recover pubkey from compressed public key data + /* Recover pubkey from compressed public key data */ if (_convertToPubKey(ctx, otherPk, &pubKey) != 1) { return E_INVALID_ARG; @@ -240,17 +240,17 @@ static NCResult _computeSharedSecret( NULL ); - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&pubKey, sizeof(pubKey)); - //Result should be 1 on success + /* Result should be 1 on success */ return result > 0 ? NC_SUCCESS : E_OPERATION_FAILED; } static inline const mbedtls_md_info_t* _getSha256MdInfo(void) { const mbedtls_md_info_t* info; - //Get sha256 md info for hdkf operations + /* 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; @@ -265,23 +265,23 @@ static inline NCResult _computeConversationKey( ) { int opResult; - //Validate internal args + /* 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 + /* Derive the encryption key */ opResult = mbedtls_hkdf_extract( mdInfo, Nip44ConstantSalt, sizeof(Nip44ConstantSalt), - (uint8_t*)sharedSecret, //Shared secret is the input key + (uint8_t*)sharedSecret, /* Shared secret is the input key */ NC_SHARED_SEC_SIZE, - (uint8_t*)ck //Output produces a conversation key + (uint8_t*)ck /* Output produces a conversation key */ ); - //Return success if the hkdf operation was successful + /* Return success if the hkdf operation was successful */ return opResult == 0 ? NC_SUCCESS : E_OPERATION_FAILED; } @@ -302,10 +302,10 @@ static int _chachaEncipher(const struct nc_expand_keys* keys, NCCryptoData* args return mbedtls_chacha20_crypt( keys->chacha_key, keys->chacha_nonce, - 0, //Counter (always starts at 0) - args->dataSize, //Data size (input and output are assumed to be the same size) - args->inputData, //Input data - args->outputData //Output data + 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 */ ); } @@ -323,14 +323,14 @@ static inline NCResult _getMessageKey( 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 + /* Another HKDF to derive the message key with nonce */ result = mbedtls_hkdf_expand( mdInfo, - (uint8_t*)converstationKey, //Conversation key is the input key + (uint8_t*)converstationKey, /* Conversation key is the input key */ NC_CONV_KEY_SIZE, nonce, nonceSize, - (uint8_t*)messageKey, //Output produces a message key (write it directly to struct memory) + (uint8_t*)messageKey, /* Output produces a message key (write it directly to struct memory) */ NC_MESSAGE_KEY_SIZE ); @@ -355,23 +355,23 @@ static inline NCResult _encryptEx( DEBUG_ASSERT2(mdINfo != NULL, "Expected valid md info struct") DEBUG_ASSERT2(hmacKey != NULL, "Expected valid hmac key buffer") - //Failure, bail out + /* Failure, bail out */ if ((result = _getMessageKey(mdINfo, ck, args->nonce32, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS) { goto Cleanup; } - //Expand the keys from the hkdf so we can use them in the cipher + /* Expand the keys from the hkdf so we can use them in the cipher */ expandedKeys = _expandKeysFromHkdf(&messageKey); - //Copy the hmac key into the 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) + /* CHACHA20 (the result will be 0 on success) */ result = (NCResult)_chachaEncipher(expandedKeys, args); Cleanup: - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&messageKey, sizeof(messageKey)); return result; @@ -393,20 +393,20 @@ static inline NCResult _decryptEx( DEBUG_ASSERT2(args != NULL, "Expected valid encryption args") DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md info struct") - //Failure to get message keys, bail out + /* Failure to get message keys, bail out */ if ((result = _getMessageKey(mdInfo, ck, args->nonce32, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS) { goto Cleanup; } - //Expand the keys from the hkdf so we can use them in the cipher + /* Expand the keys from the hkdf so we can use them in the cipher */ cipherKeys = _expandKeysFromHkdf(&messageKey); - //CHACHA20 (the result will be 0 on success) + /* CHACHA20 (the result will be 0 on success) */ result = (NCResult) _chachaEncipher(cipherKeys, args); Cleanup: - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&messageKey, sizeof(messageKey)); return result; @@ -421,6 +421,7 @@ static inline int _computeHmac( DEBUG_ASSERT2(key != NULL, "Expected valid hmac key") DEBUG_ASSERT2(args != NULL, "Expected valid mac verification args") DEBUG_ASSERT2(hmacOut != NULL, "Expected valid hmac output buffer") + DEBUG_ASSERT(args->payload != NULL) return mbedtls_md_hmac( _getSha256MdInfo(), @@ -509,7 +510,7 @@ NC_EXPORT NCResult NC_CC NCInitContext( ctx->secpCtx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); - //Randomize once on init + /* Randomize once on init */ return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG; } @@ -522,7 +523,7 @@ NC_EXPORT NCResult NC_CC NCReInitContext( CHECK_INVALID_ARG(ctx->secpCtx, 0) CHECK_NULL_ARG(entropy, 1) - //Only randomize again + /* Only randomize again */ return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG; } @@ -531,16 +532,16 @@ NC_EXPORT NCResult NC_CC NCDestroyContext(NCContext* ctx) CHECK_NULL_ARG(ctx, 0); CHECK_INVALID_ARG(ctx->secpCtx, 0); - //Destroy secp256k1 context + /* Destroy secp256k1 context */ secp256k1_context_destroy(ctx->secpCtx); - //Wipe the context + /* Wipe the context */ ZERO_FILL(ctx, sizeof(NCContext)); return NC_SUCCESS; } -//KEY Functions +/* KEY Functions */ NC_EXPORT NCResult NC_CC NCGetPublicKey( const NCContext* ctx, const NCSecretKey* sk, @@ -561,15 +562,15 @@ NC_EXPORT NCResult NC_CC NCGetPublicKey( return E_INVALID_ARG; } - //Generate the x-only public key, docs say this should always return 1 + /* 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 + /* Convert to compressed pubkey */ result = _convertFromXonly(ctx, &xonly, pk); DEBUG_ASSERT2(result == 1, "Expected x-only pubkey serialize to return 1") - //Clean out keypair + /* Clean out keypair */ ZERO_FILL(&keyPair, sizeof(keyPair)); ZERO_FILL(&xonly, sizeof(xonly)); @@ -585,11 +586,11 @@ NC_EXPORT NCResult NC_CC NCValidateSecretKey( CHECK_NULL_ARG(sk, 1) CHECK_INVALID_ARG(ctx->secpCtx, 0) - //Validate the secret key + /* Validate the secret key */ return secp256k1_ec_seckey_verify(ctx->secpCtx, sk->key); } -//Ecdsa Functions +/* Ecdsa Functions */ NC_EXPORT NCResult NC_CC NCSignDigest( const NCContext* ctx, @@ -603,7 +604,7 @@ NC_EXPORT NCResult NC_CC NCSignDigest( secp256k1_keypair keyPair; secp256k1_xonly_pubkey xonly; - //Validate arguments + /* Validate arguments */ CHECK_NULL_ARG(ctx, 0) CHECK_INVALID_ARG(ctx->secpCtx, 0) CHECK_NULL_ARG(sk, 1) @@ -611,24 +612,24 @@ NC_EXPORT NCResult NC_CC NCSignDigest( CHECK_NULL_ARG(digest32, 3) CHECK_NULL_ARG(sig64, 4) - //Generate the keypair + /* Generate the keypair */ if (secp256k1_keypair_create(ctx->secpCtx, &keyPair, sk->key) != 1) { return E_INVALID_ARG; } - //Sign the digest + /* 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 + /* 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 + /* Verify the signature is valid */ result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly); - //cleanup any sensitive data + /* cleanup any sensitive data */ ZERO_FILL(&keyPair, sizeof(keyPair)); ZERO_FILL(&xonly, sizeof(xonly)); @@ -646,7 +647,7 @@ NC_EXPORT NCResult NC_CC NCSignData( { uint8_t digest[32]; - //Double check is required because arg position differs + /* Double check is required because arg position differs */ CHECK_NULL_ARG(ctx, 0) CHECK_NULL_ARG(sk, 1) CHECK_NULL_ARG(random32, 2) @@ -654,13 +655,13 @@ NC_EXPORT NCResult NC_CC NCSignData( CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 4) CHECK_NULL_ARG(sig64, 5) - //Compute sha256 of the data before signing + /* Compute sha256 of the data before signing */ if(mbedtls_sha256(data, dataSize, digest, 0) != 0) { return E_INVALID_ARG; } - //Sign the freshly computed digest + /* Sign the freshly computed digest */ return NCSignDigest(ctx, sk, random32, digest, sig64); } @@ -680,16 +681,16 @@ NC_EXPORT NCResult NC_CC NCVerifyDigest( CHECK_NULL_ARG(digest32, 2) CHECK_NULL_ARG(sig64, 3) - //recover the x-only key from a compressed public key + /* recover the x-only key from a compressed public key */ if(_convertToXonly(ctx, pk, &xonly) != 1) { return E_INVALID_ARG; } - //Verify the signature + /* Verify the signature */ result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly); - //cleanup any sensitive data + /* cleanup any sensitive data */ ZERO_FILL(&xonly, sizeof(xonly)); return result == 1 ? NC_SUCCESS : E_INVALID_ARG; @@ -711,17 +712,18 @@ NC_EXPORT NCResult NC_CC NCVerifyData( CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3) CHECK_NULL_ARG(sig64, 4) - //Compute sha256 of the data before verifying + /* Compute sha256 of the data before verifying */ if (mbedtls_sha256(data, dataSize, digest, 0) != 0) { return E_INVALID_ARG; } - //Verify the freshly computed digest + /* Verify the freshly computed digest */ return NCVerifyDigest(ctx, pk, digest, sig64); } -//ECDH Functions +/* ECDH Functions */ + NC_EXPORT NCResult NC_CC NCGetSharedSecret( const NCContext* ctx, const NCSecretKey* sk, @@ -754,7 +756,7 @@ NC_EXPORT NCResult NC_CC NCGetConversationKeyEx( CHECK_NULL_ARG(sharedPoint, 1) CHECK_NULL_ARG(conversationKey, 2) - //Cast the shared point to the shared secret type + /* Cast the shared point to the shared secret type */ return _computeConversationKey( ctx, _getSha256MdInfo(), @@ -779,7 +781,7 @@ NC_EXPORT NCResult NC_CC NCGetConversationKey( CHECK_NULL_ARG(pk, 2) CHECK_NULL_ARG(conversationKey, 3) - //Compute the shared point + /* Compute the shared point */ if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS) { goto Cleanup; @@ -793,7 +795,7 @@ NC_EXPORT NCResult NC_CC NCGetConversationKey( ); Cleanup: - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&sharedSecret, sizeof(sharedSecret)); return result; @@ -812,7 +814,7 @@ NC_EXPORT NCResult NC_CC NCEncryptEx( CHECK_NULL_ARG(hmacKeyOut, 2) CHECK_NULL_ARG(args, 3) - //Validte ciphertext/plaintext + /* Validte ciphertext/plaintext */ CHECK_INVALID_ARG(args->inputData, 3) CHECK_INVALID_ARG(args->outputData, 3) CHECK_INVALID_ARG(args->nonce32, 3) @@ -847,7 +849,7 @@ NC_EXPORT NCResult NC_CC NCEncrypt( CHECK_NULL_ARG(hmacKeyOut, 3) CHECK_NULL_ARG(args, 4) - //Validate input/output data + /* Validate input/output data */ CHECK_INVALID_ARG(args->inputData, 4) CHECK_INVALID_ARG(args->outputData, 4) CHECK_INVALID_ARG(args->nonce32, 4) @@ -855,13 +857,13 @@ NC_EXPORT NCResult NC_CC NCEncrypt( mdInfo = _getSha256MdInfo(); - //Compute the shared point + /* Compute the shared point */ if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS) { goto Cleanup; } - //Compute the conversation key from secret and pubkic keys + /* Compute the conversation key from secret and pubkic keys */ if ((result = _computeConversationKey(ctx, mdInfo, &sharedSecret, &conversationKey)) != NC_SUCCESS) { goto Cleanup; @@ -870,7 +872,7 @@ NC_EXPORT NCResult NC_CC NCEncrypt( result = _encryptEx(ctx, mdInfo, &conversationKey, hmacKeyOut, args); Cleanup: - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&sharedSecret, sizeof(sharedSecret)); ZERO_FILL(&conversationKey, sizeof(conversationKey)); @@ -888,7 +890,7 @@ NC_EXPORT NCResult NC_CC NCDecryptEx( CHECK_NULL_ARG(conversationKey, 1) CHECK_NULL_ARG(args, 2) - //Validte ciphertext/plaintext + /* Validte ciphertext/plaintext */ CHECK_INVALID_ARG(args->inputData, 2) CHECK_INVALID_ARG(args->outputData, 2) CHECK_INVALID_ARG(args->nonce32, 2) @@ -920,7 +922,7 @@ NC_EXPORT NCResult NC_CC NCDecrypt( CHECK_NULL_ARG(pk, 2) CHECK_NULL_ARG(args, 3) - //Validte ciphertext/plaintext + /* Validte ciphertext/plaintext */ CHECK_INVALID_ARG(args->inputData, 3) CHECK_INVALID_ARG(args->outputData, 3) CHECK_INVALID_ARG(args->nonce32, 3) @@ -941,7 +943,7 @@ NC_EXPORT NCResult NC_CC NCDecrypt( result = _decryptEx(ctx, mdInfo, &conversationKey, args); Cleanup: - //Clean up sensitive data + /* Clean up sensitive data */ ZERO_FILL(&sharedSecret, sizeof(sharedSecret)); ZERO_FILL(&conversationKey, sizeof(conversationKey)); @@ -956,22 +958,23 @@ NC_EXPORT NCResult NCComputeMac( uint8_t hmacOut[NC_ENCRYPTION_MAC_SIZE] ) { + NCMacVerifyArgs args; + 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) + + /*Fill args with 0 before use because we are only using some of the properties*/ + ZERO_FILL(&args, sizeof(args)); + args.payload = payload; + args.payloadSize = payloadSize; /* * Compute the hmac of the data using the supplied hmac key */ - - NCMacVerifyArgs args = { - .payload = payload, - .payloadSize = payloadSize - }; - return _computeHmac(hmacKey, &args, hmacOut) == 0 ? NC_SUCCESS : E_OPERATION_FAILED; } diff --git a/src/noscrypt.h b/src/noscrypt.h index 0f9344a..6a40171 100644 --- a/src/noscrypt.h +++ b/src/noscrypt.h @@ -36,31 +36,31 @@ #define _NC_IS_WINDOWS #endif -//Set api export calling convention (allow used to override) +/* 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 + /* STD for importing to other languages such as .NET */ #define NC_CC __stdcall #else #define NC_CC #endif -#endif // !NC_CC +#endif /* !NC_CC */ -#ifndef NC_EXPORT //Allow users to disable the export/impoty macro if using source code directly +#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 + #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 + #endif /* _NC_IS_WINDOWS */ + #endif /* !NOSCRYPT_EXPORTING */ +#endif /* !NC_EXPORT */ /* * CONSTANTS @@ -225,10 +225,10 @@ that caused the error. */ NC_EXPORT void NC_CC NCParseErrorCode(NCResult result, int* code, uint8_t* argPosition) { - //convert result to a positive value + /* convert result to a positive value*/ NCResult asPositive = -result; - //Get the error code from the lower 8 bits and the argument position from the upper 8 bits + /* Get the error code from the lower 8 bits and the argument position from the upper 8 bits*/ *code = -(asPositive & NC_ERROR_CODE_MASK); *argPosition = (asPositive >> NC_ARG_POSITION_OFFSET) & 0xFF; } @@ -560,4 +560,4 @@ NC_EXPORT NCResult NCComputeMac( uint8_t hmacOut[NC_ENCRYPTION_MAC_SIZE] ); -#endif // !NOSCRYPT_H +#endif /* !NOSCRYPT_H */ diff --git a/tests/hex.h b/tests/hex.h index 793e9f9..7c8080a 100644 --- a/tests/hex.h +++ b/tests/hex.h @@ -56,9 +56,11 @@ static size_t _hdeferListIndex = 0; static HexBytes* __allocHexBytes(size_t length) { + HexBytes* hexBytes; + length /= 2; - HexBytes* hexBytes = (HexBytes*)malloc(length + sizeof(HexBytes)); + hexBytes = (HexBytes*)malloc(length + sizeof(HexBytes)); if(!hexBytes) { return NULL; @@ -89,7 +91,11 @@ static HexBytes* _fromHexString(const char* hexLiteral, size_t strLen) 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'}; + char byteString[3] = { '\0' }; + + byteString[0] = hexLiteral[i]; + byteString[1] = hexLiteral[i + 1]; + hexBytes->data[i / 2] = (uint8_t)strtol(byteString, NULL, 16); } @@ -143,6 +149,6 @@ static void PrintHexBytes(HexBytes* hexBytes) } -#endif // !HEX_HELPERS_H +#endif /* !HEX_HELPERS_H */ diff --git a/tests/test.c b/tests/test.c index e3188dc..8d3e115 100644 --- a/tests/test.c +++ b/tests/test.c @@ -67,7 +67,7 @@ #include "hex.h" -//Pre-computed constants for argument errors +/*Pre-computed constants for argument errors */ #define ARG_ERROR_POS_0 E_NULL_PTR #define ARG_ERROR_POS_1 NCResultWithArgPosition(E_NULL_PTR, 0x01) #define ARG_ERROR_POS_2 NCResultWithArgPosition(E_NULL_PTR, 0x02) @@ -104,16 +104,17 @@ static int TestPublicApiArgumentValidation(void); #endif static const uint8_t zero32[32] = { 0 }; -static const uint8_t zero64[64] = { 0 }; int main(void) { int result; + result = RunTests(); + (void)PrintHexBytes; /*avoid unused. I use occasionally for debugging*/ FreeHexBytes(); - return 0; + return result; } static int RunTests(void) @@ -127,7 +128,11 @@ static int RunTests(void) FillRandomData(ctxRandom, 32); - //Context struct size should aways match the size of the struct returned by NCGetContextStructSize + /* + * Context struct size should aways match the size of the + * struct returned by NCGetContextStructSize + */ + TEST(NCGetContextStructSize(), sizeof(NCContext)) TEST(NCInitContext(&ctx, ctxRandom), NC_SUCCESS) @@ -181,16 +186,16 @@ static int InitKepair(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubK { PRINTL("TEST: Keypair") - //Get random private key + /* Get random private key */ FillRandomData(secKey, sizeof(NCSecretKey)); - //Ensure not empty + /* Ensure not empty */ ENSURE(memcmp(zero32, secKey, 32) != 0); - //Ensure the key is valid, result should be 1 on success + /* Ensure the key is valid, result should be 1 on success */ TEST(NCValidateSecretKey(context, secKey), 1); - //Generate a public key from the secret key + /* Generate a public key from the secret key */ TEST(NCGetPublicKey(context, secKey, pubKey), NC_SUCCESS); PRINTL("\nPASSED: Keypair tests completed") @@ -206,55 +211,55 @@ static int TestEcdsa(NCContext* context, NCSecretKey* secKey, NCPublicKey* pubKe PRINTL("TEST: Ecdsa") - //Init a new secret key with random data + /*Init a new secret key with random data */ FillRandomData(invalidSig, sizeof(invalidSig)); FillRandomData(sigEntropy, sizeof(sigEntropy)); - //compute sha256 of the test string + /* compute sha256 of the test string */ _sha256((uint8_t*)message, strlen(message), digestToSign); - //Sign and verify sig64 + /* Sign and verify sig64 */ { uint8_t sig[64]; TEST(NCSignDigest(context, secKey, sigEntropy, digestToSign, sig), NC_SUCCESS); TEST(NCVerifyDigest(context, pubKey, digestToSign, sig), NC_SUCCESS); } - //Sign and verify raw data + /* Sign and verify raw data */ { uint8_t sig[64]; TEST(NCSignData(context, secKey, sigEntropy, (uint8_t*)message, strlen(message), sig), NC_SUCCESS); TEST(NCVerifyData(context, pubKey, (uint8_t*)message, strlen(message), sig), NC_SUCCESS); } - //ensure the signature is the same for signing data and sig64 + /* ensure the signature is the same for signing data and sig64 */ { uint8_t sig1[64]; uint8_t sig2[64]; - //Ensure operations succeed but dont print them as test cases + /* Ensure operations succeed but dont print them as test cases */ ENSURE(NCSignData(context, secKey, sigEntropy, (uint8_t*)message, strlen(message), sig1) == NC_SUCCESS); ENSURE(NCSignDigest(context, secKey, sigEntropy, digestToSign, sig2) == NC_SUCCESS); - //Perform test + /* Perform test */ TEST(memcmp(sig1, sig2, 64), 0); } - //Try signing data then veriyfing the sig64 + /* Try signing data then veriyfing the sig64 */ { uint8_t sig[64]; ENSURE(NCSignData(context, secKey, sigEntropy, (uint8_t*)message, strlen(message), sig) == NC_SUCCESS); TEST(NCVerifyDigest(context, pubKey, digestToSign, sig), NC_SUCCESS); - //Now invert test, zero signature to ensure its overwritten + /* Now invert test, zero signature to ensure its overwritten */ ZERO_FILL(sig, sizeof(sig)); ENSURE(NCSignDigest(context, secKey, sigEntropy, digestToSign, sig) == NC_SUCCESS); TEST(NCVerifyData(context, pubKey, (uint8_t*)message, strlen(message), sig), NC_SUCCESS); } - //test verification of invalid signature + /* test verification of invalid signature */ { TEST(NCVerifyDigest(context, pubKey, digestToSign, invalidSig), E_INVALID_ARG); } @@ -275,51 +280,49 @@ static int TestPublicApiArgumentValidation(void) uint8_t hmacKeyOut[NC_HMAC_KEY_SIZE]; uint8_t nonce[NC_ENCRYPTION_NONCE_SIZE]; - NCCryptoData cryptoData = { - .dataSize = sizeof(zero32), - .inputData = zero32, - .outputData = sig64, //just an arbitrary writeable buffer - .nonce32 = nonce - }; + NCCryptoData cryptoData; + cryptoData.dataSize = sizeof(zero32); + cryptoData.inputData = zero32; + cryptoData.outputData = sig64; /*just an arbitrary writeable buffer*/ PRINTL("TEST: Public API argument validation tests") FillRandomData(ctxRandom, 32); FillRandomData(nonce, sizeof(nonce)); - //Test null context + /*Test null context*/ TEST(NCInitContext(NULL, ctxRandom), ARG_ERROR_POS_0) TEST(NCInitContext(&ctx, NULL), ARG_ERROR_POS_1) - //Test null context + /*Test null context*/ TEST(NCDestroyContext(NULL), ARG_ERROR_POS_0) - //reinit + /*reinit*/ TEST(NCReInitContext(NULL, ctxRandom), ARG_ERROR_POS_0) TEST(NCReInitContext(&ctx, NULL), ARG_ERROR_POS_1) - //Test null secret key + /*Test null secret key*/ TEST(NCGetPublicKey(&ctx, NULL, &pubKey), ARG_ERROR_POS_1) TEST(NCGetPublicKey(&ctx, &secKey, NULL), ARG_ERROR_POS_2) - //Test null secret key + /*Test null secret key*/ TEST(NCValidateSecretKey(NULL, &secKey), ARG_ERROR_POS_0) TEST(NCValidateSecretKey(&ctx, NULL), ARG_ERROR_POS_1) - //Verify sig64 args test + /*Verify sig64 args test*/ TEST(NCVerifyDigest(NULL, &pubKey, zero32, sig64), ARG_ERROR_POS_0) TEST(NCVerifyDigest(&ctx, NULL, zero32, sig64), ARG_ERROR_POS_1) TEST(NCVerifyDigest(&ctx, &pubKey, NULL, sig64), ARG_ERROR_POS_2) TEST(NCVerifyDigest(&ctx, &pubKey, zero32, NULL), ARG_ERROR_POS_3) - //Test verify data args + /*Test verify data args*/ TEST(NCVerifyData(NULL, &pubKey, zero32, 32, sig64), ARG_ERROR_POS_0) TEST(NCVerifyData(&ctx, NULL, zero32, 32, sig64), ARG_ERROR_POS_1) TEST(NCVerifyData(&ctx, &pubKey, NULL, 32, sig64), ARG_ERROR_POS_2) TEST(NCVerifyData(&ctx, &pubKey, zero32, 0, sig64), ARG_RAMGE_ERROR_POS_3) TEST(NCVerifyData(&ctx, &pubKey, zero32, 32, NULL), ARG_ERROR_POS_4) - //Test null sign data args + /*Test null sign data args*/ TEST(NCSignData(NULL, &secKey, zero32, zero32, 32, sig64), ARG_ERROR_POS_0) TEST(NCSignData(&ctx, NULL, zero32, zero32, 32, sig64), ARG_ERROR_POS_1) TEST(NCSignData(&ctx, &secKey, NULL, zero32, 32, sig64), ARG_ERROR_POS_2) @@ -327,35 +330,35 @@ static int TestPublicApiArgumentValidation(void) TEST(NCSignData(&ctx, &secKey, zero32, zero32, 0, sig64), ARG_RAMGE_ERROR_POS_4) TEST(NCSignData(&ctx, &secKey, zero32, zero32, 32, NULL), ARG_ERROR_POS_5) - //Test null sign digest args + /*Test null sign digest args*/ TEST(NCSignDigest(NULL, &secKey, zero32, zero32, sig64), ARG_ERROR_POS_0) TEST(NCSignDigest(&ctx, NULL, zero32, zero32, sig64), ARG_ERROR_POS_1) TEST(NCSignDigest(&ctx, &secKey, NULL, zero32, sig64), ARG_ERROR_POS_2) TEST(NCSignDigest(&ctx, &secKey, zero32, NULL, sig64), ARG_ERROR_POS_3) TEST(NCSignDigest(&ctx, &secKey, zero32, zero32, NULL), ARG_ERROR_POS_4) - //Test null encrypt args + /*Test null encrypt args*/ 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 + /*Test invalid data size*/ cryptoData.dataSize = 0; TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_RAMGE_ERROR_POS_4) - //Test null input data + /*Test null input data */ cryptoData.dataSize = 32; cryptoData.inputData = NULL; TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_INVALID_ERROR_POS_4) - //Test null output data + /*Test null output data */ cryptoData.inputData = zero32; cryptoData.outputData = NULL; TEST(NCEncrypt(&ctx, &secKey, &pubKey, hmacKeyOut, &cryptoData), ARG_INVALID_ERROR_POS_4) - //Decrypt + /* Decrypt */ cryptoData.dataSize = 32; cryptoData.inputData = zero32; cryptoData.outputData = sig64; @@ -365,16 +368,16 @@ static int TestPublicApiArgumentValidation(void) TEST(NCDecrypt(&ctx, &secKey, NULL, &cryptoData), ARG_ERROR_POS_2) TEST(NCDecrypt(&ctx, &secKey, &pubKey, NULL), ARG_ERROR_POS_3) - //Test invalid data size + /* Test invalid data size */ cryptoData.dataSize = 0; TEST(NCDecrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_RAMGE_ERROR_POS_3) - //Test null input data + /* Test null input data */ cryptoData.dataSize = 32; cryptoData.inputData = NULL; TEST(NCDecrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3) - //Test null output data + /*Test null output data */ cryptoData.inputData = zero32; cryptoData.outputData = NULL; TEST(NCDecrypt(&ctx, &secKey, &pubKey, &cryptoData), ARG_INVALID_ERROR_POS_3) @@ -389,12 +392,11 @@ static int TestPublicApiArgumentValidation(void) } { - NCMacVerifyArgs macArgs = { - .payload = zero32, - .payloadSize = 32, - .mac32 = zero32, - .nonce32 = zero32 - }; + NCMacVerifyArgs macArgs; + macArgs.payload = zero32; + macArgs.payloadSize = 32; + macArgs.mac32 = zero32; + macArgs.nonce32 = zero32; TEST(NCVerifyMac(NULL, &secKey, &pubKey, &macArgs), ARG_ERROR_POS_0) TEST(NCVerifyMac(&ctx, NULL, &pubKey, &macArgs), ARG_ERROR_POS_1) @@ -417,18 +419,19 @@ static int TestPublicApiArgumentValidation(void) #endif static int TestKnownKeys(NCContext* context) -{ - PRINTL("TEST: Known keys") - +{ NCPublicKey pubKey; + HexBytes* secKey1, * pubKey1, * secKey2, * pubKey2; - HexBytes* secKey1 = FromHexString("98c642360e7163a66cee5d9a842b252345b6f3f3e21bd3b7635d5e6c20c7ea36", sizeof(secKey)); - HexBytes* pubKey1 = FromHexString("0db15182c4ad3418b4fbab75304be7ade9cfa430a21c1c5320c9298f54ea5406", sizeof(pubKey)); + PRINTL("TEST: Known keys") + + secKey1 = FromHexString("98c642360e7163a66cee5d9a842b252345b6f3f3e21bd3b7635d5e6c20c7ea36", sizeof(NCSecretKey)); + pubKey1 = FromHexString("0db15182c4ad3418b4fbab75304be7ade9cfa430a21c1c5320c9298f54ea5406", sizeof(NCPublicKey)); - HexBytes* secKey2 = FromHexString("3032cb8da355f9e72c9a94bbabae80ca99d3a38de1aed094b432a9fe3432e1f2", sizeof(secKey)); - HexBytes* pubKey2 = FromHexString("421181660af5d39eb95e48a0a66c41ae393ba94ffeca94703ef81afbed724e5a", sizeof(pubKey)); + secKey2 = FromHexString("3032cb8da355f9e72c9a94bbabae80ca99d3a38de1aed094b432a9fe3432e1f2", sizeof(NCSecretKey)); + pubKey2 = FromHexString("421181660af5d39eb95e48a0a66c41ae393ba94ffeca94703ef81afbed724e5a", sizeof(NCPublicKey)); - //Test known keys + /*Test known keys*/ TEST(NCValidateSecretKey(context, NCToSecKey(secKey1->data)), 1); /* Recover a public key from secret key 1 */ @@ -463,21 +466,20 @@ static int TestCorrectEncryption(NCContext* context) uint8_t plainText[TEST_ENC_DATA_SIZE]; uint8_t cipherText[TEST_ENC_DATA_SIZE]; uint8_t decryptedText[TEST_ENC_DATA_SIZE]; + + NCCryptoData cryptoData; + NCMacVerifyArgs macVerifyArgs; /* setup the crypto data structure */ - NCCryptoData cryptoData = { - .dataSize = TEST_ENC_DATA_SIZE, - .inputData = plainText, - .outputData = cipherText, - .nonce32 = nonce - }; - - NCMacVerifyArgs macVerifyArgs = { - .nonce32 = nonce, - .mac32 = mac, - .payload = cipherText, - .payloadSize = TEST_ENC_DATA_SIZE - }; + cryptoData.dataSize = TEST_ENC_DATA_SIZE; + cryptoData.inputData = plainText; + cryptoData.outputData = cipherText; + cryptoData.nonce32 = nonce; + + macVerifyArgs.nonce32 = nonce; + macVerifyArgs.mac32 = mac; + macVerifyArgs.payload = cipherText; + macVerifyArgs.payloadSize = TEST_ENC_DATA_SIZE; PRINTL("TEST: Correct encryption") @@ -497,7 +499,7 @@ static int TestCorrectEncryption(NCContext* context) /* Try to encrypt the data from sec1 to pub2 */ TEST(NCEncrypt(context, &secKey1, &pubKey2, hmacKeyOut, &cryptoData), NC_SUCCESS); - //swap cipher and plain text for decryption + /*swap cipher and plain text for decryption */ cryptoData.inputData = cipherText; cryptoData.outputData = decryptedText; |