From 2fe1083d8e6826e44cd9fd97c94b1a344c04f4ef Mon Sep 17 00:00:00 2001 From: Vishal Pankaj Chandratreya <19171016+tfpf@users.noreply.github.com> Date: Mon, 22 Apr 2024 21:56:35 +0530 Subject: [PATCH] Formatted C and C++ code. (#14) * Added `clang-format`. * Fixed macro formatting using `do { } while (false)`. * Disabled formatting for SHA-256 constants. * Style workflow. --- .clang-format | 192 ++++++++++++++++++++++++++++++++++ .github/workflows/style.yml | 9 ++ benchmarks/benchmarks.cc | 46 ++++---- clang-format.bash | 14 +++ examples/C++/thread-safe.cc | 7 +- examples/C++/thread-unsafe.cc | 7 +- examples/C/thread-safe.c | 9 +- examples/C/thread-unsafe.c | 9 +- include/hdrbg.h | 24 ++--- lib/extras.c | 4 +- lib/hdrbg.c | 74 ++++++------- lib/pyhdrbg.c | 173 +++++++++++++----------------- lib/sha256.c | 37 ++++--- tests/tests.c | 17 +-- 14 files changed, 406 insertions(+), 216 deletions(-) create mode 100644 .clang-format create mode 100644 .github/workflows/style.yml create mode 100755 clang-format.bash diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..dd1354f --- /dev/null +++ b/.clang-format @@ -0,0 +1,192 @@ +--- +Language: Cpp +# BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignArrayOfStructures: None +AlignConsecutiveMacros: None +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: false +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: false +AllowShortLambdasOnASingleLine: false +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: All +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 119 +CommentPragmas: '^ IWYU pragma:' +QualifierAlignment: Leave +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +PackConstructorInitializers: BinPack +BasedOnStyle: '' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +AllowAllConstructorInitializersOnNextLine: true +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +PPIndentWidth: -1 +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + BeforeNonEmptyParentheses: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... + diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml new file mode 100644 index 0000000..a614401 --- /dev/null +++ b/.github/workflows/style.yml @@ -0,0 +1,9 @@ +name: style +on: [push, workflow_dispatch] + +jobs: + C: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - run: ./clang-format.bash check diff --git a/benchmarks/benchmarks.cc b/benchmarks/benchmarks.cc index 4f42005..9456b6c 100644 --- a/benchmarks/benchmarks.cc +++ b/benchmarks/benchmarks.cc @@ -3,31 +3,33 @@ #include #include -#define benchmark(function, iterations) \ -{ \ - auto delay = std::chrono::microseconds::max(); \ - for(int i = 0; i < 32; ++i) \ - { \ - auto begin = std::chrono::high_resolution_clock::now(); \ - for(int i = 0; i < iterations; ++i) \ - { \ - function(0); \ - } \ - auto end = std::chrono::high_resolution_clock::now(); \ - auto delay_ = std::chrono::duration_cast(end - begin); \ - delay = std::min(delay, delay_); \ - } \ - auto result = delay.count() / static_cast(iterations); \ - std::printf("%20s %8.2lf µs\n", #function, result); \ -} +#define benchmark(function, iterations) \ + do \ + { \ + auto delay = std::chrono::microseconds::max(); \ + for (int i = 0; i < 32; ++i) \ + { \ + auto begin = std::chrono::high_resolution_clock::now(); \ + for (int i = 0; i < iterations; ++i) \ + { \ + function(0); \ + } \ + auto end = std::chrono::high_resolution_clock::now(); \ + auto delay_ = std::chrono::duration_cast(end - begin); \ + delay = std::min(delay, delay_); \ + } \ + auto result = delay.count() / static_cast(iterations); \ + std::printf("%20s %8.2lf µs\n", #function, result); \ + } while (false) /****************************************************************************** * Main function. *****************************************************************************/ -int main(void) +int +main(void) { - benchmark(hdrbg_init, 100) - benchmark(hdrbg_reinit, 100) - benchmark(hdrbg_rand, 800) - benchmark(hdrbg_real, 800) + benchmark(hdrbg_init, 100); + benchmark(hdrbg_reinit, 100); + benchmark(hdrbg_rand, 800); + benchmark(hdrbg_real, 800); } diff --git a/clang-format.bash b/clang-format.bash new file mode 100755 index 0000000..53b7216 --- /dev/null +++ b/clang-format.bash @@ -0,0 +1,14 @@ +#! /usr/bin/env bash + +shopt -s globstar + +# Switch to the directory containing the script so that relative paths may be +# used. +cd "${0%/*}" +files=(**/*.c **/*.cc **/*.h) +if [ "$1" = check ] +then + clang-format --verbose --dry-run -Werror ${files[@]} +else + clang-format --verbose -i ${files[@]} +fi diff --git a/examples/C++/thread-safe.cc b/examples/C++/thread-safe.cc index 355c9eb..e34f1c9 100644 --- a/examples/C++/thread-safe.cc +++ b/examples/C++/thread-safe.cc @@ -2,18 +2,19 @@ #include #include -int main(void) +int +main(void) { hdrbg_t *hd = hdrbg_init(true); std::uint8_t r_bytes[64]; hdrbg_fill(hd, false, r_bytes, 64); hdrbg_dump(r_bytes, 64); - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { std::cout << hdrbg_rand(hd) << ' '; } - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { std::cout << hdrbg_real(hd) << ' '; } diff --git a/examples/C++/thread-unsafe.cc b/examples/C++/thread-unsafe.cc index 7590b3e..31ea14d 100644 --- a/examples/C++/thread-unsafe.cc +++ b/examples/C++/thread-unsafe.cc @@ -3,18 +3,19 @@ #include #include -int main(void) +int +main(void) { hdrbg_init(false); std::uint8_t r_bytes[64]; hdrbg_fill(NULL, false, r_bytes, 64); hdrbg_dump(r_bytes, 64); - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { std::cout << hdrbg_rand(NULL) << ' '; } - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { std::cout << hdrbg_real(NULL) << ' '; } diff --git a/examples/C/thread-safe.c b/examples/C/thread-safe.c index ae98161..a70448e 100644 --- a/examples/C/thread-safe.c +++ b/examples/C/thread-safe.c @@ -3,18 +3,19 @@ #include #include -int main(void) +int +main(void) { struct hdrbg_t *hd = hdrbg_init(true); uint8_t r_bytes[64]; hdrbg_fill(hd, false, r_bytes, 64); hdrbg_dump(r_bytes, 64); - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { - printf("%"PRIu64" ", hdrbg_rand(hd)); + printf("%" PRIu64 " ", hdrbg_rand(hd)); } - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { printf("%Lf ", hdrbg_real(hd)); } diff --git a/examples/C/thread-unsafe.c b/examples/C/thread-unsafe.c index 0efd474..0235fc3 100644 --- a/examples/C/thread-unsafe.c +++ b/examples/C/thread-unsafe.c @@ -4,18 +4,19 @@ #include #include -int main(void) +int +main(void) { hdrbg_init(false); uint8_t r_bytes[64]; hdrbg_fill(NULL, false, r_bytes, 64); hdrbg_dump(r_bytes, 64); - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { - printf("%"PRIu64" ", hdrbg_rand(NULL)); + printf("%" PRIu64 " ", hdrbg_rand(NULL)); } - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { printf("%Lf ", hdrbg_real(NULL)); } diff --git a/include/hdrbg.h b/include/hdrbg.h index a4794f9..b1d4dab 100644 --- a/include/hdrbg.h +++ b/include/hdrbg.h @@ -30,18 +30,18 @@ enum hdrbg_err_t extern "C" { #endif -enum hdrbg_err_t hdrbg_err_get(void); -struct hdrbg_t *hdrbg_init(bool dma); -struct hdrbg_t *hdrbg_reinit(struct hdrbg_t *hd); -int hdrbg_fill(struct hdrbg_t *hd, bool prediction_resistance, uint8_t *r_bytes, int long unsigned r_length); -uint64_t hdrbg_rand(struct hdrbg_t *hd); -uint64_t hdrbg_uint(struct hdrbg_t *hd, uint64_t modulus); -int64_t hdrbg_span(struct hdrbg_t *hd, int64_t left, int64_t right); -double long hdrbg_real(struct hdrbg_t *hd); -int hdrbg_drop(struct hdrbg_t *hd, int long long count); -void hdrbg_zero(struct hdrbg_t *hd); -void hdrbg_dump(uint8_t const *m_bytes, size_t m_length); -void hdrbg_tests(struct hdrbg_t *hd, void *tv); + enum hdrbg_err_t hdrbg_err_get(void); + struct hdrbg_t *hdrbg_init(bool dma); + struct hdrbg_t *hdrbg_reinit(struct hdrbg_t *hd); + int hdrbg_fill(struct hdrbg_t *hd, bool prediction_resistance, uint8_t *r_bytes, int long unsigned r_length); + uint64_t hdrbg_rand(struct hdrbg_t *hd); + uint64_t hdrbg_uint(struct hdrbg_t *hd, uint64_t modulus); + int64_t hdrbg_span(struct hdrbg_t *hd, int64_t left, int64_t right); + double long hdrbg_real(struct hdrbg_t *hd); + int hdrbg_drop(struct hdrbg_t *hd, int long long count); + void hdrbg_zero(struct hdrbg_t *hd); + void hdrbg_dump(uint8_t const *m_bytes, size_t m_length); + void hdrbg_tests(struct hdrbg_t *hd, void *tv); #ifdef __cplusplus } #endif diff --git a/lib/extras.c b/lib/extras.c index 611ba17..a164977 100644 --- a/lib/extras.c +++ b/lib/extras.c @@ -29,7 +29,7 @@ uint64_t memcompose(uint8_t const *m_bytes, size_t m_length) { uint64_t value = 0; - while(m_length-- > 0) + while (m_length-- > 0) { value = value << 8 | *m_bytes++; } @@ -49,7 +49,7 @@ memcompose(uint8_t const *m_bytes, size_t m_length) size_t memdecompose(uint8_t *m_bytes, size_t m_length, uint64_t value) { - for(size_t i = m_length; i > 0; --i) + for (size_t i = m_length; i > 0; --i) { m_bytes[i - 1] = value; value >>= 8; diff --git a/lib/hdrbg.c b/lib/hdrbg.c index 7ebcc23..6c7a50c 100644 --- a/lib/hdrbg.c +++ b/lib/hdrbg.c @@ -18,7 +18,8 @@ static atomic_ullong #else static int long long unsigned #endif -seq_num = 0; + seq_num + = 0; #if !(defined __STDC_NO_THREADS__ || defined _WIN32) #include @@ -26,7 +27,8 @@ static thread_local enum hdrbg_err_t #else static enum hdrbg_err_t #endif -hdrbg_err = HDRBG_ERR_NONE; + hdrbg_err + = HDRBG_ERR_NONE; #define HDRBG_SEED_LENGTH 55 #define HDRBG_SECURITY_STRENGTH 32 @@ -49,8 +51,7 @@ struct hdrbg_t uint8_t C[HDRBG_SEED_LENGTH]; uint64_t gen_count; }; -static struct hdrbg_t -hdrbg; +static struct hdrbg_t hdrbg; /****************************************************************************** * Obtain the error status. @@ -77,13 +78,13 @@ static void add_accumulate(uint8_t *a_bytes, size_t a_length, uint8_t const *b_bytes, size_t b_length) { int unsigned carry = 0; - for(; a_length > 0 && b_length > 0; --a_length, --b_length) + for (; a_length > 0 && b_length > 0; --a_length, --b_length) { carry = a_bytes[a_length - 1] + carry + b_bytes[b_length - 1]; a_bytes[a_length - 1] = carry; carry >>= 8; } - for(; a_length > 0; --a_length) + for (; a_length > 0; --a_length) { carry += a_bytes[a_length - 1]; a_bytes[a_length - 1] = carry; @@ -113,7 +114,7 @@ hash_df(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes, size_t h_le // Hash repeatedly. size_t iterations = (h_length - 1) / HDRBG_OUTPUT_LENGTH + 1; - for(size_t i = 1; i <= iterations; ++i) + for (size_t i = 1; i <= iterations; ++i) { m_bytes[0] = i; uint8_t tmp[HDRBG_OUTPUT_LENGTH]; @@ -143,7 +144,7 @@ hash_gen(uint8_t const *m_bytes_, uint8_t *h_bytes, size_t h_length) // Hash repeatedly. size_t iterations = (h_length - 1) / HDRBG_OUTPUT_LENGTH + 1; - for(size_t i = 0; i < iterations; ++i) + for (size_t i = 0; i < iterations; ++i) { uint8_t tmp[HDRBG_OUTPUT_LENGTH]; sha256(m_bytes, HDRBG_SEED_LENGTH, tmp); @@ -187,17 +188,17 @@ static size_t streamtobytes(FILE *fptr_, uint8_t *m_bytes, size_t m_length) { FILE *fptr = fptr_ == NULL ? fopen("/dev/urandom", "rb") : fptr_; - if(fptr == NULL) + if (fptr == NULL) { hdrbg_err = HDRBG_ERR_NO_ENTROPY; return 0; } size_t len = fread(m_bytes, sizeof *m_bytes, m_length, fptr); - if(len < m_length) + if (len < m_length) { hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY; } - if(fptr_ == NULL) + if (fptr_ == NULL) { fclose(fptr); } @@ -211,13 +212,13 @@ struct hdrbg_t * hdrbg_init(bool dma) { struct hdrbg_t *hd = dma ? malloc(sizeof *hd) : &hdrbg; - if(hd == NULL) + if (hd == NULL) { hdrbg_err = HDRBG_ERR_OUT_OF_MEMORY; return NULL; } uint8_t seedmaterial[HDRBG_SECURITY_STRENGTH + HDRBG_NONCE1_LENGTH + HDRBG_NONCE2_LENGTH]; - if(streamtobytes(NULL, seedmaterial, HDRBG_SECURITY_STRENGTH) < HDRBG_SECURITY_STRENGTH) + if (streamtobytes(NULL, seedmaterial, HDRBG_SECURITY_STRENGTH) < HDRBG_SECURITY_STRENGTH) { goto cleanup_hd; } @@ -238,9 +239,9 @@ struct hdrbg_t * hdrbg_reinit(struct hdrbg_t *hd) { hd = hd == NULL ? &hdrbg : hd; - uint8_t reseedmaterial[1 + HDRBG_SEED_LENGTH + HDRBG_SECURITY_STRENGTH] = {0x01U}; + uint8_t reseedmaterial[1 + HDRBG_SEED_LENGTH + HDRBG_SECURITY_STRENGTH] = { 0x01U }; memcpy(reseedmaterial + 1, hd->V + 1, HDRBG_SEED_LENGTH * sizeof *reseedmaterial); - if(streamtobytes(NULL, reseedmaterial + 1 + HDRBG_SEED_LENGTH, HDRBG_SECURITY_STRENGTH) < HDRBG_SECURITY_STRENGTH) + if (streamtobytes(NULL, reseedmaterial + 1 + HDRBG_SEED_LENGTH, HDRBG_SECURITY_STRENGTH) < HDRBG_SECURITY_STRENGTH) { return NULL; } @@ -254,20 +255,20 @@ hdrbg_reinit(struct hdrbg_t *hd) int hdrbg_fill(struct hdrbg_t *hd, bool prediction_resistance, uint8_t *r_bytes, int long unsigned r_length) { - if(r_length > HDRBG_REQUEST_LIMIT) + if (r_length > HDRBG_REQUEST_LIMIT) { hdrbg_err = HDRBG_ERR_INVALID_REQUEST_FILL; return -1; } hd = hd == NULL ? &hdrbg : hd; - if(prediction_resistance || hd->gen_count == HDRBG_RESEED_INTERVAL) + if (prediction_resistance || hd->gen_count == HDRBG_RESEED_INTERVAL) { - if(hdrbg_reinit(hd) == NULL) + if (hdrbg_reinit(hd) == NULL) { return -1; } } - if(r_length > 0) + if (r_length > 0) { hash_gen(hd->V + 1, r_bytes, r_length); } @@ -296,7 +297,7 @@ static int hdrbg_rand_(struct hdrbg_t *hd, uint64_t *r) { uint8_t value[8]; - if(hdrbg_fill(hd, false, value, 8) < 0) + if (hdrbg_fill(hd, false, value, 8) < 0) { return -1; } @@ -311,7 +312,7 @@ uint64_t hdrbg_rand(struct hdrbg_t *hd) { uint64_t r; - if(hdrbg_rand_(hd, &r) == -1) + if (hdrbg_rand_(hd, &r) == -1) { return -1; } @@ -330,7 +331,7 @@ hdrbg_rand(struct hdrbg_t *hd) static int hdrbg_uint_(struct hdrbg_t *hd, uint64_t modulus, uint64_t *r) { - if(modulus == 0) + if (modulus == 0) { hdrbg_err = HDRBG_ERR_INVALID_REQUEST_UINT; return -1; @@ -338,12 +339,11 @@ hdrbg_uint_(struct hdrbg_t *hd, uint64_t modulus, uint64_t *r) uint64_t upper = 0xFFFFFFFFFFFFFFFFU - 0xFFFFFFFFFFFFFFFFU % modulus; do { - if(hdrbg_rand_(hd, r) == -1) + if (hdrbg_rand_(hd, r) == -1) { return -1; } - } - while(*r >= upper); + } while (*r >= upper); *r %= modulus; return 0; } @@ -355,7 +355,7 @@ uint64_t hdrbg_uint(struct hdrbg_t *hd, uint64_t modulus) { uint64_t r; - if(hdrbg_uint_(hd, modulus, &r) == -1) + if (hdrbg_uint_(hd, modulus, &r) == -1) { return -1; } @@ -368,7 +368,7 @@ hdrbg_uint(struct hdrbg_t *hd, uint64_t modulus) int64_t hdrbg_span(struct hdrbg_t *hd, int64_t left, int64_t right) { - if(left >= right) + if (left >= right) { hdrbg_err = HDRBG_ERR_INVALID_REQUEST_SPAN; return -1; @@ -377,7 +377,7 @@ hdrbg_span(struct hdrbg_t *hd, int64_t left, int64_t right) uint64_t uright = right; uint64_t modulus = uright - uleft; uint64_t r; - if(hdrbg_uint_(hd, modulus, &r) == -1) + if (hdrbg_uint_(hd, modulus, &r) == -1) { return -1; } @@ -398,7 +398,7 @@ double long hdrbg_real(struct hdrbg_t *hd) { uint64_t r; - if(hdrbg_rand_(hd, &r) == -1) + if (hdrbg_rand_(hd, &r) == -1) { return -1.0L; } @@ -411,9 +411,9 @@ hdrbg_real(struct hdrbg_t *hd) int hdrbg_drop(struct hdrbg_t *hd, int long long count) { - while(count-- > 0) + while (count-- > 0) { - if(hdrbg_fill(hd, false, NULL, 0) < 0) + if (hdrbg_fill(hd, false, NULL, 0) < 0) { return -1; } @@ -427,7 +427,7 @@ hdrbg_drop(struct hdrbg_t *hd, int long long count) void hdrbg_zero(struct hdrbg_t *hd) { - if(hd == NULL || hd == &hdrbg) + if (hd == NULL || hd == &hdrbg) { memclear(&hdrbg, sizeof hdrbg); return; @@ -442,9 +442,9 @@ hdrbg_zero(struct hdrbg_t *hd) void hdrbg_dump(uint8_t const *m_bytes, size_t m_length) { - while(m_length-- > 0) + while (m_length-- > 0) { - fprintf(stdout, "%02"PRIx8, *m_bytes++); + fprintf(stdout, "%02" PRIx8, *m_bytes++); } fprintf(stdout, "\n"); } @@ -469,7 +469,7 @@ hdrbg_dump(uint8_t const *m_bytes, size_t m_length) static void hdrbg_tests_pr(struct hdrbg_t *hd, bool prediction_resistance, FILE *tv) { - for(int i = 0; i < 60; ++i) + for (int i = 0; i < 60; ++i) { // Initialise. uint8_t seedmaterial[HDRBG_TV_ENTROPY_LENGTH + HDRBG_TV_NONCE_LENGTH]; @@ -477,7 +477,7 @@ hdrbg_tests_pr(struct hdrbg_t *hd, bool prediction_resistance, FILE *tv) hdrbg_seed(hd, seedmaterial, sizeof seedmaterial / sizeof *seedmaterial); // Reinitialise. - uint8_t reseedmaterial[1 + HDRBG_SEED_LENGTH + HDRBG_TV_ENTROPY_LENGTH] = {0x01U}; + uint8_t reseedmaterial[1 + HDRBG_SEED_LENGTH + HDRBG_TV_ENTROPY_LENGTH] = { 0x01U }; memcpy(reseedmaterial + 1, hd->V + 1, HDRBG_SEED_LENGTH * sizeof *reseedmaterial); streamtobytes(tv, reseedmaterial + 1 + HDRBG_SEED_LENGTH, HDRBG_TV_ENTROPY_LENGTH); hdrbg_seed(hd, reseedmaterial, sizeof reseedmaterial / sizeof *reseedmaterial); @@ -487,7 +487,7 @@ hdrbg_tests_pr(struct hdrbg_t *hd, bool prediction_resistance, FILE *tv) hdrbg_fill(hd, false, observed, HDRBG_TV_REQUEST_LENGTH); // Reinitialise. - if(prediction_resistance) + if (prediction_resistance) { memcpy(reseedmaterial + 1, hd->V + 1, HDRBG_SEED_LENGTH * sizeof *reseedmaterial); streamtobytes(tv, reseedmaterial + 1 + HDRBG_SEED_LENGTH, HDRBG_TV_ENTROPY_LENGTH); diff --git a/lib/pyhdrbg.c b/lib/pyhdrbg.c index c913e81..7970485 100644 --- a/lib/pyhdrbg.c +++ b/lib/pyhdrbg.c @@ -7,16 +7,14 @@ #include "hdrbg.h" -#define ERR_CHECK \ -do \ -{ \ - if(err_check() < 0) \ - { \ - return NULL; \ - } \ -} \ -while(false) - +#define ERR_CHECK \ + do \ + { \ + if (err_check() < 0) \ + { \ + return NULL; \ + } \ + } while (false) /****************************************************************************** * Check whether the error indicator is set. If yes, set a Python exception. @@ -26,32 +24,31 @@ while(false) static int err_check(void) { - switch(hdrbg_err_get()) + switch (hdrbg_err_get()) { - case HDRBG_ERR_OUT_OF_MEMORY: - PyErr_Format(PyExc_MemoryError, "insufficient memory"); - return -1; - case HDRBG_ERR_NO_ENTROPY: - PyErr_Format(PyExc_OSError, "entropy source not found"); - return -1; - case HDRBG_ERR_INSUFFICIENT_ENTROPY: - PyErr_Format(PyExc_RuntimeError, "insufficient entropy"); - return -1; - case HDRBG_ERR_INVALID_REQUEST_FILL: - PyErr_Format(PyExc_ValueError, "argument 1 must be less than or equal to 65536"); - return -1; - case HDRBG_ERR_INVALID_REQUEST_UINT: - PyErr_Format(PyExc_ValueError, "argument 1 must be non-zero"); - return -1; - case HDRBG_ERR_INVALID_REQUEST_SPAN: - PyErr_Format(PyExc_ValueError, "argument 1 must be less than argument 2"); - return -1; - default: - return 0; + case HDRBG_ERR_OUT_OF_MEMORY: + PyErr_Format(PyExc_MemoryError, "insufficient memory"); + return -1; + case HDRBG_ERR_NO_ENTROPY: + PyErr_Format(PyExc_OSError, "entropy source not found"); + return -1; + case HDRBG_ERR_INSUFFICIENT_ENTROPY: + PyErr_Format(PyExc_RuntimeError, "insufficient entropy"); + return -1; + case HDRBG_ERR_INVALID_REQUEST_FILL: + PyErr_Format(PyExc_ValueError, "argument 1 must be less than or equal to 65536"); + return -1; + case HDRBG_ERR_INVALID_REQUEST_UINT: + PyErr_Format(PyExc_ValueError, "argument 1 must be non-zero"); + return -1; + case HDRBG_ERR_INVALID_REQUEST_SPAN: + PyErr_Format(PyExc_ValueError, "argument 1 must be less than argument 2"); + return -1; + default: + return 0; } } - static PyObject * Init(PyObject *self, PyObject *args) { @@ -60,7 +57,6 @@ Init(PyObject *self, PyObject *args) Py_RETURN_NONE; } - static PyObject * Reinit(PyObject *self, PyObject *args) { @@ -69,17 +65,16 @@ Reinit(PyObject *self, PyObject *args) Py_RETURN_NONE; } - static PyObject * Fill(PyObject *self, PyObject *args) { int long unsigned r_length; - if(!PyArg_ParseTuple(args, "k", &r_length)) + if (!PyArg_ParseTuple(args, "k", &r_length)) { return NULL; } r_length = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(args, 0)); - if(PyErr_Occurred() != NULL) + if (PyErr_Occurred() != NULL) { return PyErr_Format(PyExc_OverflowError, "argument 1 is out of range of `unsigned long`"); } @@ -92,7 +87,6 @@ Fill(PyObject *self, PyObject *args) return PyBytes_FromStringAndSize((char *)r_bytes, r_length); } - static PyObject * Rand(PyObject *self, PyObject *args) { @@ -101,17 +95,16 @@ Rand(PyObject *self, PyObject *args) return PyLong_FromUnsignedLongLong(r); } - static PyObject * Uint(PyObject *self, PyObject *args) { int long long unsigned modulus; - if(!PyArg_ParseTuple(args, "K", &modulus)) + if (!PyArg_ParseTuple(args, "K", &modulus)) { return NULL; } modulus = PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(args, 0)); - if(PyErr_Occurred() != NULL || modulus > UINT64_MAX) + if (PyErr_Occurred() != NULL || modulus > UINT64_MAX) { return PyErr_Format(PyExc_OverflowError, "argument 1 is out of range of `uint64_t`"); } @@ -120,25 +113,24 @@ Uint(PyObject *self, PyObject *args) return PyLong_FromUnsignedLongLong(r); } - static PyObject * Span(PyObject *self, PyObject *args) { int long long left, right; PyObject *err = NULL; - if(!PyArg_ParseTuple(args, "LL", &left, &right)) + if (!PyArg_ParseTuple(args, "LL", &left, &right)) { err = PyErr_Occurred(); - if(!PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) + if (!PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { return NULL; } } - if(err != NULL) + if (err != NULL) { return PyErr_Format(PyExc_OverflowError, "argument 1 or argument 2 is out of range of `long long`"); } - else if(left < INT64_MIN || left > INT64_MAX || right < INT64_MIN || right > INT64_MAX) + else if (left < INT64_MIN || left > INT64_MAX || right < INT64_MIN || right > INT64_MAX) { return PyErr_Format(PyExc_OverflowError, "argument 1 or argument 2 is out of range of `int64_t`"); } @@ -147,7 +139,6 @@ Span(PyObject *self, PyObject *args) return PyLong_FromLongLong(r); } - static PyObject * Real(PyObject *self, PyObject *args) { @@ -156,21 +147,20 @@ Real(PyObject *self, PyObject *args) return PyFloat_FromDouble(r); } - static PyObject * Drop(PyObject *self, PyObject *args) { int long long count; PyObject *err = NULL; - if(!PyArg_ParseTuple(args, "L", &count)) + if (!PyArg_ParseTuple(args, "L", &count)) { err = PyErr_Occurred(); - if(!PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) + if (!PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { return NULL; } } - if(err != NULL) + if (err != NULL) { return PyErr_Format(PyExc_OverflowError, "argument 1 is out of range of `long long`"); } @@ -179,84 +169,62 @@ Drop(PyObject *self, PyObject *args) Py_RETURN_NONE; } - static void Zero(void) { hdrbg_zero(NULL); } - // Module information. -PyDoc_STRVAR( - init_doc, +PyDoc_STRVAR(init_doc, "_init()\n" - "Initialise (seed) the HDRBG object." -); -PyDoc_STRVAR( - reinit_doc, + "Initialise (seed) the HDRBG object."); +PyDoc_STRVAR(reinit_doc, "_reinit()\n" - "Reinitialise (reseed) the HDRBG object." -); -PyDoc_STRVAR( - bytes_doc, + "Reinitialise (reseed) the HDRBG object."); +PyDoc_STRVAR(bytes_doc, "fill(r_length) -> bytes\n" "Generate cryptographically secure pseudorandom bytes.\n\n" ":param r_length: Number of bytes to generate. At most 65536.\n\n" - ":return: Uniform pseudorandom bytes object." -); -PyDoc_STRVAR( - rand_doc, + ":return: Uniform pseudorandom bytes object."); +PyDoc_STRVAR(rand_doc, "rand() -> int\n" "Generate a cryptographically secure pseudorandom number.\n\n" - ":return: Uniform pseudorandom integer in the range 0 (inclusive) to 2 ** 64 − 1 (inclusive)." -); -PyDoc_STRVAR( - uint_doc, + ":return: Uniform pseudorandom integer in the range 0 (inclusive) to 2 ** 64 − 1 (inclusive)."); +PyDoc_STRVAR(uint_doc, "uint(modulus) -> int\n" "Generate a cryptographically secure pseudorandom residue.\n\n" ":param modulus: Right end of the interval. Must be positive.\n\n" - ":return: Uniform pseudorandom integer in the range 0 (inclusive) to ``modulus`` (exclusive)." -); -PyDoc_STRVAR( - span_doc, + ":return: Uniform pseudorandom integer in the range 0 (inclusive) to ``modulus`` (exclusive)."); +PyDoc_STRVAR(span_doc, "span(left, right) -> int\n" "Generate a cryptographically secure pseudorandom residue offset.\n\n" ":param left: Left end of the interval.\n" ":param right: Right end of the interval. Must be greater than ``left``.\n\n" - ":return: Uniform pseudorandom integer in the range ``left`` (inclusive) to ``right`` (exclusive)." -); -PyDoc_STRVAR( - real_doc, + ":return: Uniform pseudorandom integer in the range ``left`` (inclusive) to ``right`` (exclusive)."); +PyDoc_STRVAR(real_doc, "real() -> float\n" "Generate a cryptographically secure pseudorandom fraction.\n\n" - ":return: Uniform pseudorandom real in the range 0 (inclusive) to 1 (inclusive)." -); -PyDoc_STRVAR( - drop_doc, + ":return: Uniform pseudorandom real in the range 0 (inclusive) to 1 (inclusive)."); +PyDoc_STRVAR(drop_doc, "drop()\n" "Advance the state of the HDRBG object. Equivalent to running ``fill(0)`` ``count`` times and discarding the " - "results." -); -PyDoc_STRVAR( - pyhdrbg_doc, + "results."); +PyDoc_STRVAR(pyhdrbg_doc, "Python API for a C implementation of Hash DRBG " - "(see https://github.com/tfpf/hash-drbg/blob/main/doc for the full documentation)" -); -static PyMethodDef pyhdrbg_methods[] = -{ - {"_init", Init, METH_NOARGS, init_doc}, - {"_reinit", Reinit, METH_NOARGS, reinit_doc}, - {"fill", Fill, METH_VARARGS, bytes_doc}, - {"rand", Rand, METH_NOARGS, rand_doc}, - {"uint", Uint, METH_VARARGS, uint_doc}, - {"span", Span, METH_VARARGS, span_doc}, - {"real", Real, METH_NOARGS, real_doc}, - {"drop", Drop, METH_VARARGS, drop_doc}, - {NULL, NULL, 0, NULL}, + "(see https://github.com/tfpf/hash-drbg/blob/main/doc for the full documentation)"); +static PyMethodDef pyhdrbg_methods[] = { + { "_init", Init, METH_NOARGS, init_doc }, + { "_reinit", Reinit, METH_NOARGS, reinit_doc }, + { "fill", Fill, METH_VARARGS, bytes_doc }, + { "rand", Rand, METH_NOARGS, rand_doc }, + { "uint", Uint, METH_VARARGS, uint_doc }, + { "span", Span, METH_VARARGS, span_doc }, + { "real", Real, METH_NOARGS, real_doc }, + { "drop", Drop, METH_VARARGS, drop_doc }, + { NULL, NULL, 0, NULL }, }; -static PyModuleDef pyhdrbg = -{ +static PyModuleDef pyhdrbg = { PyModuleDef_HEAD_INIT, "hdrbg", pyhdrbg_doc, @@ -268,13 +236,12 @@ static PyModuleDef pyhdrbg = NULL, }; - PyMODINIT_FUNC PyInit_hdrbg(void) { hdrbg_init(false); ERR_CHECK; - if(Py_AtExit(Zero) < 0) + if (Py_AtExit(Zero) < 0) { return NULL; } diff --git a/lib/sha256.c b/lib/sha256.c index fa423bb..6db6927 100644 --- a/lib/sha256.c +++ b/lib/sha256.c @@ -13,16 +13,15 @@ #define ROTR32(x, n) ((x) >> (n) | (x) << (32 - (n))) // Hash initialiser. -static uint32_t const -sha256_init[8] = -{ +static uint32_t const sha256_init[8] = { + // clang-format off 0x6A09E667U, 0xBB67AE85U, 0x3C6EF372U, 0xA54FF53AU, 0x510E527FU, 0x9B05688CU, 0x1F83D9ABU, 0x5BE0CD19U, + // clang-format on }; // Round constants. -static uint32_t const -sha256_rc[64] = -{ +static uint32_t const sha256_rc[64] = { + // clang-format off 0x428A2F98U, 0x71374491U, 0xB5C0FBCFU, 0xE9B5DBA5U, 0x3956C25BU, 0x59F111F1U, 0x923F82A4U, 0xAB1C5ED5U, 0xD807AA98U, 0x12835B01U, 0x243185BEU, 0x550C7DC3U, 0x72BE5D74U, 0x80DEB1FEU, 0x9BDC06A7U, 0xC19BF174U, 0xE49B69C1U, 0xEFBE4786U, 0x0FC19DC6U, 0x240CA1CCU, 0x2DE92C6FU, 0x4A7484AAU, 0x5CB0A9DCU, 0x76F988DAU, @@ -31,11 +30,11 @@ sha256_rc[64] = 0xA2BFE8A1U, 0xA81A664BU, 0xC24B8B70U, 0xC76C51A3U, 0xD192E819U, 0xD6990624U, 0xF40E3585U, 0x106AA070U, 0x19A4C116U, 0x1E376C08U, 0x2748774CU, 0x34B0BCB5U, 0x391C0CB3U, 0x4ED8AA4AU, 0x5B9CCA4FU, 0x682E6FF3U, 0x748F82EEU, 0x78A5636FU, 0x84C87814U, 0x8CC70208U, 0x90BEFFFAU, 0xA4506CEBU, 0xBEF9A3F7U, 0xC67178F2U, + // clang-format on }; // Hash output. -static uint8_t -sha256_bytes[32]; +static uint8_t sha256_bytes[32]; /****************************************************************************** * Calculate the hash of the given data. @@ -65,30 +64,30 @@ sha256(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes) // Store the padding bytes in a sufficiently large array. size_t p_length = ((1 + zeros) >> 3) + 8; - uint8_t p_bytes[72] = {0x80U}; + uint8_t p_bytes[72] = { 0x80U }; memdecompose(p_bytes + p_length - 8, 8, nbits); // Process each 512-bit chunk. uint8_t const *m_iter = m_bytes_; size_t m_length = m_length_ + p_length; - for(size_t i = 0; i < m_length; i += 64) + for (size_t i = 0; i < m_length; i += 64) { // Expand to 2048 bits. - uint32_t schedule[64] = {0}; - for(int j = 0; j < 16; ++j) + uint32_t schedule[64] = { 0 }; + for (int j = 0; j < 16; ++j) { uint8_t const *m_iter_ = m_iter + 4; - if(m_iter < m_bytes_ + m_length_ && m_iter_ >= m_bytes_ + m_length_) + if (m_iter < m_bytes_ + m_length_ && m_iter_ >= m_bytes_ + m_length_) { // Reading four bytes will cross the message-padding boundary. // Switch over from message bytes to padding bytes. int k; - for(k = 0; m_iter < m_bytes_ + m_length_; ++k, ++m_iter) + for (k = 0; m_iter < m_bytes_ + m_length_; ++k, ++m_iter) { schedule[j] = schedule[j] << 8 | *m_iter; } m_iter = p_bytes; - for(; k < 4; ++k, ++m_iter) + for (; k < 4; ++k, ++m_iter) { schedule[j] = schedule[j] << 8 | *m_iter; } @@ -99,7 +98,7 @@ sha256(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes) m_iter = m_iter_; } } - for(int j = 16; j < 64; ++j) + for (int j = 16; j < 64; ++j) { uint32_t sigma0 = ROTR32(schedule[j - 15], 7) ^ ROTR32(schedule[j - 15], 18) ^ schedule[j - 15] >> 3; uint32_t sigma1 = ROTR32(schedule[j - 2], 17) ^ ROTR32(schedule[j - 2], 19) ^ schedule[j - 2] >> 10; @@ -109,7 +108,7 @@ sha256(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes) // Compress to 256 bits. uint32_t curr[8]; memcpy(curr, h_words, sizeof curr); - for(int j = 0; j < 64; ++j) + for (int j = 0; j < 64; ++j) { uint32_t Sigma0 = ROTR32(curr[0], 2) ^ ROTR32(curr[0], 13) ^ ROTR32(curr[0], 22); uint32_t Sigma1 = ROTR32(curr[4], 6) ^ ROTR32(curr[4], 11) ^ ROTR32(curr[4], 25); @@ -127,7 +126,7 @@ sha256(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes) } // Calculate the intermediate hash. - for(int j = 0; j < 8; ++j) + for (int j = 0; j < 8; ++j) { h_words[j] += curr[j]; } @@ -136,7 +135,7 @@ sha256(uint8_t const *m_bytes_, size_t m_length_, uint8_t *h_bytes) // Copy the hash to the output array. h_bytes = h_bytes == NULL ? sha256_bytes : h_bytes; uint8_t *h_iter = h_bytes; - for(int i = 0; i < 8; ++i) + for (int i = 0; i < 8; ++i) { h_iter += memdecompose(h_iter, 4, h_words[i]); } diff --git a/tests/tests.c b/tests/tests.c index 91ff6fe..b3df297 100644 --- a/tests/tests.c +++ b/tests/tests.c @@ -16,13 +16,14 @@ * * @return Ignored. *****************************************************************************/ -int hdrbg_tests_custom(void *hd_) +int +hdrbg_tests_custom(void *hd_) { struct hdrbg_t *hd = hd_; - for(int long i = 0; i < CUSTOM_ITERATIONS; ++i) + for (int long i = 0; i < CUSTOM_ITERATIONS; ++i) { uint64_t r = hdrbg_rand(hd); - if(r > 0) + if (r > 0) { assert(hdrbg_uint(hd, r) < r); assert(hdrbg_err_get() == HDRBG_ERR_NONE); @@ -31,14 +32,14 @@ int hdrbg_tests_custom(void *hd_) assert(hdrbg_err_get() == HDRBG_ERR_INVALID_REQUEST_UINT); assert(hdrbg_err_get() == HDRBG_ERR_NONE); } - for(int long i = 0; i < CUSTOM_ITERATIONS; ++i) + for (int long i = 0; i < CUSTOM_ITERATIONS; ++i) { uint64_t uleft = hdrbg_rand(hd); int64_t left = *(int64_t *)&uleft; uint64_t uright = hdrbg_rand(hd); int64_t right = *(int64_t *)&uright; int64_t middle = hdrbg_span(hd, left, right); - if(left < right) + if (left < right) { assert(left <= middle && middle < right); } @@ -61,7 +62,8 @@ int hdrbg_tests_custom(void *hd_) * @param hd HDRBG object. * @param tv Test vectors file. *****************************************************************************/ -void tests(struct hdrbg_t *hd, FILE *tv) +void +tests(struct hdrbg_t *hd, FILE *tv) { hdrbg_tests(hd, tv); hdrbg_tests_custom(hd); @@ -70,7 +72,8 @@ void tests(struct hdrbg_t *hd, FILE *tv) /****************************************************************************** * Main function. *****************************************************************************/ -int main(void) +int +main(void) { printf("Testing a dynamically-allocated HDRBG object.\n"); FILE *tv = fopen("Hash_DRBG.dat", "rb");