├── .github └── workflows │ └── build-test.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── CMakeLists.txt ├── CMakePresets.json ├── LICENSE ├── __init__.py ├── build.py ├── cmake ├── Config.cmake.in ├── cryptoToolsBuildOptions.cmake ├── cryptoToolsConfig.cmake ├── cryptoToolsConfigVersion.cmake ├── cryptoToolsDepHelper.cmake ├── cryptoToolsFindBuildDir.cmake └── install.cmake ├── cryptoTools ├── CMakeLists.txt ├── Circuit │ ├── BetaCircuit.cpp │ ├── BetaCircuit.h │ ├── BetaLibrary.cpp │ ├── BetaLibrary.h │ ├── Gate.h │ ├── MxBit.cpp │ ├── MxBit.h │ ├── MxCircuit.cpp │ ├── MxCircuit.h │ ├── MxCircuitLibrary.cpp │ ├── MxCircuitLibrary.h │ └── MxTypes.h ├── Common │ ├── Aligned.h │ ├── Bit.h │ ├── BitIterator.h │ ├── BitVector.cpp │ ├── BitVector.h │ ├── CLP.cpp │ ├── CLP.h │ ├── CuckooIndex.cpp │ ├── CuckooIndex.h │ ├── Defines.cpp │ ├── Defines.h │ ├── Finally.h │ ├── Log.cpp │ ├── Log.h │ ├── Matrix.h │ ├── MatrixView.h │ ├── Range.h │ ├── TestCollection.cpp │ ├── TestCollection.h │ ├── ThreadBarrier.h │ ├── Timer.cpp │ ├── Timer.h │ ├── Version.h │ ├── block.cpp │ ├── block.h │ └── config.h.in ├── Crypto │ ├── AES.cpp │ ├── AES.h │ ├── Blake2.cpp │ ├── Blake2.h │ ├── Commit.h │ ├── Hashable.h │ ├── MultiKeyAES.h │ ├── PRNG.cpp │ ├── PRNG.h │ ├── RCurve.cpp │ ├── RCurve.h │ ├── RandomOracle.h │ ├── Rijndael256.cpp │ ├── Rijndael256.h │ ├── SodiumCurve.cpp │ ├── SodiumCurve.h │ └── blake2 │ │ ├── c │ │ ├── blake2-impl.h │ │ ├── blake2.h │ │ ├── blake2b-ref.cpp │ │ ├── blake2bp-ref.cpp │ │ ├── blake2s-ref.cpp │ │ ├── blake2sp-ref.cpp │ │ ├── blake2xb-ref.cpp │ │ └── blake2xs-ref.cpp │ │ └── sse │ │ ├── blake2-config.h │ │ ├── blake2-impl.h │ │ ├── blake2.h │ │ ├── blake2b-load-sse2.h │ │ ├── blake2b-load-sse41.h │ │ ├── blake2b-round.h │ │ ├── blake2b.cpp │ │ ├── blake2bp.cpp │ │ └── blake2xb.cpp └── Network │ ├── Channel.cpp │ ├── Channel.h │ ├── Endpoint.h │ ├── IOService.cpp │ ├── IOService.h │ ├── IoBuffer.cpp │ ├── IoBuffer.h │ ├── Session.cpp │ ├── Session.h │ ├── SocketAdapter.cpp │ ├── SocketAdapter.h │ ├── TLS.cpp │ ├── TLS.h │ └── util.h ├── frontend_cryptoTools ├── CMakeLists.txt ├── Tutorials │ ├── Network.cpp │ └── Network.h ├── certs │ ├── ca-cert.der │ ├── ca-cert.pem │ ├── dh2048.der │ └── dh2048.pem ├── frontend_cryptoTools.args.json ├── main.cpp ├── signalHandle.cpp └── signalHandle.h ├── icon.PNG ├── readme.md ├── tests_cryptoTools ├── AES_Tests.cpp ├── AES_Tests.h ├── BtChannel_Tests.cpp ├── BtChannel_Tests.h ├── CMakeLists.txt ├── Circuit_Tests.cpp ├── Circuit_Tests.h ├── Circuit_aes_Tests.cpp ├── Common.cpp ├── Common.h ├── Cuckoo_Tests.cpp ├── Cuckoo_Tests.h ├── Misc_Tests.cpp ├── Misc_Tests.h ├── MxCircuit_Tests.cpp ├── MxCircuit_Tests.h ├── REcc_Tests.cpp ├── REcc_Tests.h ├── Rijndael256_Tests.cpp ├── Rijndael256_Tests.h ├── SimpleCuckoo.cpp ├── SimpleCuckoo.h ├── UnitTests.cpp ├── UnitTests.h ├── WolfSSL_Tests.cpp ├── WolfSSL_Tests.h ├── block_Tests.cpp ├── block_Tests.h └── cmakeTests │ ├── CMakeLists.txt │ └── main.cpp ├── thirdparty ├── fetch.cmake ├── findvs.ps1 ├── getCoproto.cmake ├── getLibDivide.cmake ├── getRelic.cmake ├── getSodium.cmake └── getSpanLite.cmake └── title.PNG /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | .vs/ 9 | *.args.json 10 | 11 | out/* 12 | CMakeFiles/* 13 | *Makefile* 14 | *install_manifest.txt* 15 | */CMakeFiles/* 16 | *cmake_install.cmake 17 | config.h 18 | 19 | CMakeCache.txt 20 | */CMakeCache.txt 21 | *.a 22 | cryptoTools/Common/config.h 23 | frontend_cryptoTools/frontend_cryptoTools 24 | 25 | frontend_cryptoTools/certs/* 26 | 27 | .DS_Store 28 | */.DS_Store 29 | __pycache__/ 30 | 31 | # Build results 32 | [Dd]ebug/ 33 | [Dd]ebugPublic/ 34 | [Rr]elease/ 35 | x64/ 36 | build/ 37 | bld/ 38 | [Bb]in/ 39 | [Oo]bj/ 40 | 41 | # Roslyn cache directories 42 | *.ide/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | #NUNIT 49 | *.VisualState.xml 50 | TestResult.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | *.opendb 57 | 58 | *_i.c 59 | *_p.c 60 | *_i.h 61 | *.ilk 62 | *.meta 63 | *.obj 64 | *.pch 65 | *.pdb 66 | *.pgc 67 | *.pgd 68 | *.rsp 69 | *.sbr 70 | *.tlb 71 | *.tli 72 | *.tlh 73 | *.tmp 74 | *.tmp_proj 75 | *.log 76 | *.vspscc 77 | *.vssscc 78 | .builds 79 | *.pidb 80 | *.svclog 81 | *.scc 82 | 83 | # Chutzpah Test files 84 | _Chutzpah* 85 | 86 | # Visual C++ cache files 87 | ipch/ 88 | *.aps 89 | *.ncb 90 | *.opensdf 91 | *.sdf 92 | *.cachefile 93 | 94 | # Visual Studio profiler 95 | *.psess 96 | *.vsp 97 | *.vspx 98 | 99 | # TFS 2012 Local Workspace 100 | $tf/ 101 | 102 | # Guidance Automation Toolkit 103 | *.gpState 104 | 105 | # ReSharper is a .NET coding add-in 106 | _ReSharper*/ 107 | *.[Rr]e[Ss]harper 108 | *.DotSettings.user 109 | 110 | # JustCode is a .NET coding addin-in 111 | .JustCode 112 | 113 | # TeamCity is a build add-in 114 | _TeamCity* 115 | 116 | # DotCover is a Code Coverage Tool 117 | *.dotCover 118 | 119 | # NCrunch 120 | _NCrunch_* 121 | .*crunch*.local.xml 122 | 123 | # MightyMoose 124 | *.mm.* 125 | AutoTest.Net/ 126 | 127 | # Web workbench (sass) 128 | .sass-cache/ 129 | 130 | # Installshield output folder 131 | [Ee]xpress/ 132 | 133 | # DocProject is a documentation generator add-in 134 | DocProject/buildhelp/ 135 | DocProject/Help/*.HxT 136 | DocProject/Help/*.HxC 137 | DocProject/Help/*.hhc 138 | DocProject/Help/*.hhk 139 | DocProject/Help/*.hhp 140 | DocProject/Help/Html2 141 | DocProject/Help/html 142 | 143 | # Click-Once directory 144 | publish/ 145 | 146 | # Publish Web Output 147 | *.[Pp]ublish.xml 148 | *.azurePubxml 149 | ## TODO: Comment the next line if you want to checkin your 150 | ## web deploy settings but do note that will include unencrypted 151 | ## passwords 152 | #*.pubxml 153 | 154 | # NuGet Packages Directory 155 | packages/* 156 | ## TODO: If the tool you use requires repositories.config 157 | ## uncomment the next line 158 | #!packages/repositories.config 159 | 160 | # Enable "build/" folder in the NuGet Packages folder since 161 | # NuGet packages use it for MSBuild targets. 162 | # This line needs to be after the ignore of the build folder 163 | # (and the packages folder if the line above has been uncommented) 164 | !packages/build/ 165 | 166 | # Windows Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Windows Store app package directory 171 | AppPackages/ 172 | 173 | # Others 174 | sql/ 175 | *.Cache 176 | ClientBin/ 177 | [Ss]tyle[Cc]op.* 178 | ~$* 179 | *~ 180 | *.dbmdl 181 | *.dbproj.schemaview 182 | *.pfx 183 | *.publishsettings 184 | node_modules/ 185 | 186 | # RIA/Silverlight projects 187 | Generated_Code/ 188 | 189 | # Backup & report files from converting an old project file 190 | # to a newer Visual Studio version. Backup files are not needed, 191 | # because we have git ;-) 192 | _UpgradeReport_Files/ 193 | Backup*/ 194 | UpgradeLog*.XML 195 | UpgradeLog*.htm 196 | 197 | # SQL Server files 198 | *.mdf 199 | *.ldf 200 | 201 | # Business Intelligence projects 202 | *.rdl.data 203 | *.bim.layout 204 | *.bim_*.settings 205 | 206 | # Microsoft Fakes 207 | FakesAssemblies/ 208 | 209 | # LightSwitch generated files 210 | GeneratedArtifacts/ 211 | _Pvt_Extensions/ 212 | ModelManifest.xml 213 | kProbe_data_* 214 | 215 | *.VC.db 216 | 217 | CodeDB 218 | LinuxFrontEnd/VisualGDBCache 219 | testout.txt 220 | lib 221 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "(lldb) Launch", 9 | "type": "lldb", 10 | "request": "launch", 11 | "program": "${workspaceFolder}/bin/frontend_cryptoTools", 12 | "args": ["-u","-loop", "100"], 13 | "stopAtEntry": false, 14 | "cwd": "${workspaceFolder}", 15 | "environment": [], 16 | "externalConsole": false, 17 | "MIMode": "lldb" 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.default.configurationProvider": "vector-of-bool.cmake-tools", 3 | "files.associations": { 4 | "__bit_reference": "cpp", 5 | "__config": "cpp", 6 | "__debug": "cpp", 7 | "__errc": "cpp", 8 | "__functional_base": "cpp", 9 | "__hash_table": "cpp", 10 | "__locale": "cpp", 11 | "__mutex_base": "cpp", 12 | "__node_handle": "cpp", 13 | "__nullptr": "cpp", 14 | "__split_buffer": "cpp", 15 | "__string": "cpp", 16 | "__threading_support": "cpp", 17 | "__tree": "cpp", 18 | "__tuple": "cpp", 19 | "algorithm": "cpp", 20 | "array": "cpp", 21 | "atomic": "cpp", 22 | "bit": "cpp", 23 | "bitset": "cpp", 24 | "cctype": "cpp", 25 | "chrono": "cpp", 26 | "cinttypes": "cpp", 27 | "clocale": "cpp", 28 | "cmath": "cpp", 29 | "codecvt": "cpp", 30 | "complex": "cpp", 31 | "condition_variable": "cpp", 32 | "csetjmp": "cpp", 33 | "csignal": "cpp", 34 | "cstdarg": "cpp", 35 | "cstddef": "cpp", 36 | "cstdint": "cpp", 37 | "cstdio": "cpp", 38 | "cstdlib": "cpp", 39 | "cstring": "cpp", 40 | "ctime": "cpp", 41 | "cwchar": "cpp", 42 | "cwctype": "cpp", 43 | "deque": "cpp", 44 | "exception": "cpp", 45 | "coroutine": "cpp", 46 | "forward_list": "cpp", 47 | "fstream": "cpp", 48 | "functional": "cpp", 49 | "future": "cpp", 50 | "initializer_list": "cpp", 51 | "iomanip": "cpp", 52 | "ios": "cpp", 53 | "iosfwd": "cpp", 54 | "iostream": "cpp", 55 | "istream": "cpp", 56 | "iterator": "cpp", 57 | "limits": "cpp", 58 | "list": "cpp", 59 | "locale": "cpp", 60 | "map": "cpp", 61 | "memory": "cpp", 62 | "mutex": "cpp", 63 | "new": "cpp", 64 | "numeric": "cpp", 65 | "optional": "cpp", 66 | "ostream": "cpp", 67 | "queue": "cpp", 68 | "random": "cpp", 69 | "ratio": "cpp", 70 | "regex": "cpp", 71 | "scoped_allocator": "cpp", 72 | "set": "cpp", 73 | "shared_mutex": "cpp", 74 | "sstream": "cpp", 75 | "stack": "cpp", 76 | "stdexcept": "cpp", 77 | "streambuf": "cpp", 78 | "string": "cpp", 79 | "string_view": "cpp", 80 | "strstream": "cpp", 81 | "system_error": "cpp", 82 | "thread": "cpp", 83 | "tuple": "cpp", 84 | "type_traits": "cpp", 85 | "typeindex": "cpp", 86 | "typeinfo": "cpp", 87 | "unordered_map": "cpp", 88 | "unordered_set": "cpp", 89 | "utility": "cpp", 90 | "valarray": "cpp", 91 | "variant": "cpp", 92 | "vector": "cpp", 93 | "*.ipp": "cpp", 94 | "__functional_03": "cpp" 95 | } 96 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "cmake build", 8 | "type": "shell", 9 | "command": "cmake --build ./build --target all -- -j" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.18) 2 | if (POLICY CMP0048) 3 | cmake_policy(SET CMP0048 NEW) 4 | endif (POLICY CMP0048) 5 | 6 | project(cryptoTools VERSION 1.10.1) 7 | 8 | 9 | 10 | 11 | if("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}") 12 | 13 | ############################################ 14 | # If top level cmake # 15 | ############################################ 16 | 17 | if(${CMAKE_VERSION} VERSION_LESS "3.12.0") 18 | message("Please consider updating CMake to 3.12+") 19 | endif() 20 | 21 | 22 | # Set a default build type for single-configuration 23 | # CMake generators if no build type is set. 24 | if(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE) 25 | SET(CMAKE_BUILD_TYPE Release) 26 | endif() 27 | 28 | if(MSVC) 29 | else() 30 | # Select flags. 31 | set(CMAKE_C_FLAGS "-Wall -Wfatal-errors") 32 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS}") 33 | SET(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG") 34 | SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO " -O2 -g -ggdb") 35 | SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -ggdb") 36 | endif() 37 | #set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE) 38 | 39 | endif() 40 | 41 | 42 | ############################################# 43 | # cryptoTools, tests, frontend # 44 | ############################################# 45 | include("${CMAKE_CURRENT_LIST_DIR}/cmake/cryptoToolsBuildOptions.cmake") 46 | include("${CMAKE_CURRENT_LIST_DIR}/cmake/cryptoToolsDepHelper.cmake") 47 | 48 | 49 | add_subdirectory(cryptoTools) 50 | add_subdirectory(tests_cryptoTools) 51 | add_subdirectory(frontend_cryptoTools) 52 | 53 | configure_file(cryptoTools/Common/config.h.in "cryptoTools/Common/config.h" ) 54 | 55 | 56 | include("cmake/install.cmake") 57 | -------------------------------------------------------------------------------- /CMakePresets.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 2, 3 | "configurePresets": [ 4 | { 5 | "name": "linux", 6 | "displayName": "Linux Debug", 7 | "description": "Target the Windows Subsystem for Linux (WSL) or a remote Linux system.", 8 | "generator": "Ninja", 9 | "binaryDir": "${sourceDir}/out/build/${presetName}", 10 | "cacheVariables": { 11 | "CMAKE_BUILD_TYPE": "Release", 12 | "FETCH_AUTO": true, 13 | "ENABLE_BOOST": true, 14 | "CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}" 15 | }, 16 | "vendor": { 17 | "microsoft.com/VisualStudioSettings/CMake/1.0": { "hostOS": [ "Linux" ] }, 18 | "microsoft.com/VisualStudioRemoteSettings/CMake/1.0": { "sourceDir": "$env{HOME}/.vs/$ms{projectDirName}" } 19 | } 20 | }, 21 | { 22 | "name": "x64-Debug", 23 | "displayName": "Windows x64 Debug", 24 | "description": "Target Windows with the Visual Studio development environment.", 25 | "generator": "Ninja", 26 | "binaryDir": "${sourceDir}/out/build/${presetName}", 27 | "architecture": { 28 | "value": "x64", 29 | "strategy": "external" 30 | }, 31 | "cacheVariables": { 32 | "CMAKE_BUILD_TYPE": "Debug", 33 | "ENABLE_RELIC": false, 34 | "ENABLE_SODIUM": true, 35 | "ENABLE_CIRCUITS": false, 36 | "FETCH_AUTO": true, 37 | "CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}" 38 | }, 39 | "vendor": { "microsoft.com/VisualStudioSettings/CMake/1.0": { "hostOS": [ "Windows" ] } } 40 | }, 41 | { 42 | "name": "x64-Release", 43 | "displayName": "Windows x64 Release", 44 | "description": "Target Windows with the Visual Studio development environment.", 45 | "generator": "Ninja", 46 | "binaryDir": "${sourceDir}/out/build/${presetName}", 47 | "architecture": { 48 | "value": "x64", 49 | "strategy": "external" 50 | }, 51 | "cacheVariables": { 52 | "CMAKE_BUILD_TYPE": "RelWithDebInfo", 53 | "ENABLE_RELIC": false, 54 | "ENABLE_CIRCUITS": false, 55 | "FETCH_AUTO": true, 56 | "CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}" 57 | }, 58 | "vendor": { "microsoft.com/VisualStudioSettings/CMake/1.0": { "hostOS": [ "Windows" ] } } 59 | } 60 | ] 61 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Dual-licensed under Unlicense or MIT. 2 | 3 | 4 | ----------------------- Unlicense --------------------------- 5 | 6 | This is free and unencumbered software released into the public domain. 7 | 8 | Anyone is free to copy, modify, publish, use, compile, sell, or 9 | distribute this software, either in source code form or as a compiled 10 | binary, for any purpose, commercial or non-commercial, and by any 11 | means. 12 | 13 | In jurisdictions that recognize copyright laws, the author or authors 14 | of this software dedicate any and all copyright interest in the 15 | software to the public domain. We make this dedication for the benefit 16 | of the public at large and to the detriment of our heirs and 17 | successors. We intend this dedication to be an overt act of 18 | relinquishment in perpetuity of all present and future rights to this 19 | software under copyright law. 20 | 21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 24 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 25 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 26 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | OTHER DEALINGS IN THE SOFTWARE. 28 | 29 | For more information, please refer to 30 | 31 | 32 | ----------------------- MIT --------------------------- 33 | Copyright 2021 Peter Rindal 34 | 35 | Permission is hereby granted, free of charge, to any person obtaining a copy of this 36 | software and associated documentation files (the "Software"), to deal in the Software 37 | without restriction, including without limitation the rights to use, copy, modify, 38 | merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 39 | permit persons to whom the Software is furnished to do so, subject to the following 40 | conditions: 41 | 42 | The above copyright notice and this permission notice shall be included in all copies 43 | or substantial portions of the Software. 44 | 45 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 46 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 47 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 48 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 49 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 50 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 51 | 52 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ladnir/cryptoTools/c2735302694ff4c0c44dff3732deb4d7e2fd304e/__init__.py -------------------------------------------------------------------------------- /build.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | import sys 4 | import multiprocessing 5 | 6 | def getParallel(args): 7 | par = multiprocessing.cpu_count() 8 | for x in args: 9 | if x.startswith("--par="): 10 | val = x.split("=",1)[1] 11 | par = int(val) 12 | if par < 1: 13 | par = 1 14 | idx = args.index(x) 15 | args[idx] = "" 16 | return (args,par) 17 | 18 | 19 | def replace(list, find, replace): 20 | if find in list: 21 | idx = list.index(find) 22 | list[idx] = replace; 23 | return list 24 | 25 | def Build(projectName, argv, install, par, sudo, noConfig): 26 | 27 | osStr = (platform.system()) 28 | buildDir = "" 29 | config = "" 30 | buildType = "" 31 | setup = "--setup" in argv; 32 | argv = replace(argv, "--setup", "") 33 | 34 | if "--debug" in argv: 35 | buildType = "Debug" 36 | else: 37 | buildType = "Release" 38 | argv = replace(argv, "--debug", "") 39 | 40 | 41 | if osStr == "Windows": 42 | buildDir = "out/build/x64-{0}".format(buildType) 43 | config = "--config {0}".format(buildType) 44 | elif osStr == "Darwin": 45 | buildDir = "out/build/osx" 46 | else: 47 | buildDir = "out/build/linux" 48 | 49 | if not any("DCMAKE_BUILD_TYPE" in s for s in argv): 50 | argv.append("-DCMAKE_BUILD_TYPE={0}".format(buildType)) 51 | 52 | argStr = "" 53 | for a in argv: 54 | argStr = argStr + " " + a 55 | 56 | parallel = "" 57 | if par != 1: 58 | parallel = " --parallel " + str(par) 59 | 60 | mkDirCmd = "mkdir -p {0}".format(buildDir); 61 | CMakeCmd = "cmake -S . -B {0} {1}".format(buildDir, argStr) 62 | BuildCmd = "cmake --build {0} {1} {2} ".format(buildDir, config, parallel) 63 | 64 | 65 | InstallCmd = "" 66 | if sudo: 67 | sudo = "sudo " 68 | else: 69 | sudo = "" 70 | 71 | 72 | if install: 73 | InstallCmd = sudo 74 | InstallCmd += "cmake --install {0} {1} ".format(buildDir, config) 75 | 76 | 77 | print("\n\n====== build.py ("+projectName+") ========") 78 | if not noConfig: 79 | print(mkDirCmd) 80 | print(CMakeCmd) 81 | 82 | if not setup: 83 | print(BuildCmd) 84 | if len(InstallCmd): 85 | print(InstallCmd) 86 | print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n\n") 87 | 88 | if not noConfig: 89 | os.system(mkDirCmd) 90 | os.system(CMakeCmd) 91 | 92 | if not setup: 93 | os.system(BuildCmd) 94 | 95 | if len(sudo) > 0: 96 | print("installing "+projectName+": {0}\n".format(InstallCmd)) 97 | 98 | os.system(InstallCmd) 99 | 100 | 101 | 102 | def help(): 103 | 104 | print(" --install \n\tInstructs the script to install whatever is currently being built to the default location.") 105 | print(" --install=prefix \n\tinstall to the provided predix.") 106 | print(" --sudo \n\twhen installing, use sudo. May require password.") 107 | print(" --par=n \n\twhen building do use parallel builds with n threads. default = num cores.") 108 | print(" --noauto \n\twhen building do not automaticly fetch dependancies.") 109 | print(" --par=n \n\twhen building do use parallel builds with n threads. default = num cores.") 110 | print(" --debug \n\tdebug build.") 111 | print("any additioanl arguments are forwared to cmake.\n") 112 | 113 | print("-build the library") 114 | print(" python build.py") 115 | print("-build the library with cmake configurations") 116 | print(" python build.py --debug -DENABLE_SSE=ON") 117 | print("-build the library and install with sudo") 118 | print(" python build.py --install --sudo") 119 | print("-build the library and install to prefix") 120 | print(" python build.py --install=~/my/install/dir ") 121 | 122 | 123 | 124 | def parseInstallArgs(args): 125 | prefix = "" 126 | doInstall = False 127 | for x in args: 128 | if x.startswith("--install="): 129 | prefix = x.split("=",1)[1] 130 | prefix = os.path.abspath(os.path.expanduser(prefix)) 131 | idx = args.index(x) 132 | args[idx] = "-DCMAKE_INSTALL_PREFIX=" + prefix 133 | doInstall = True 134 | if x == "--install": 135 | idx = args.index(x) 136 | osStr = (platform.system()) 137 | if osStr == "Windows": 138 | args[idx] = "-DCMAKE_INSTALL_PREFIX=c:/lib" 139 | else: 140 | args[idx] = "-DCMAKE_INSTALL_PREFIX=/usr/local" 141 | doInstall = True 142 | 143 | return (args, doInstall) 144 | 145 | def main(projectName, argv): 146 | 147 | if "--help" in argv: 148 | help() 149 | return 150 | 151 | sudo = "--sudo" in argv; 152 | if not sudo: 153 | argv.append("-DSUDO_FETCH=OFF") 154 | 155 | if "--noauto" in argv: 156 | argv = replace(argv, "--noauto", "") 157 | argv.append("-DFETCH_AUTO=OFF") 158 | else: 159 | argv.append("-DFETCH_AUTO=ON") 160 | 161 | argv = replace(argv, "--relic", "-DENABLE_RELIC=ON -DFETCH_RELIC=ON") 162 | argv = replace(argv, "--boost", "-DENABLE_BOOST=ON -DFETCH_BOOST=ON") 163 | argv = replace(argv, "--sodium", "-DENABLE_SODIUM=ON -DFETCH_SODIUM=ON") 164 | argv = replace(argv, "--openssl", "-DENABLE_OPENSSL=ON") 165 | argv = replace(argv, "--sudo", "-DSUDO_FETCH=ON") 166 | 167 | argv, install = parseInstallArgs(argv) 168 | argv, par = getParallel(argv) 169 | 170 | argv.append("-DPARALLEL_FETCH="+str(par)) 171 | 172 | noConfig = "--nc" in argv 173 | argv = replace(argv, "--nc", "") 174 | 175 | 176 | Build(projectName, argv, install, par, sudo, noConfig) 177 | 178 | if __name__ == "__main__": 179 | 180 | main("cryptoTools", sys.argv[1:]) 181 | -------------------------------------------------------------------------------- /cmake/Config.cmake.in: -------------------------------------------------------------------------------- 1 | @PACKAGE_INIT@ 2 | 3 | 4 | if(NOT CRYPTOTOOLS_FIND_QUIETLY AND NOT CRYPTOTOOLS_CONFIG_MESSAGE_DONE) 5 | message("cryptoToolsConfig.cmake: ${CMAKE_CURRENT_LIST_DIR}") 6 | endif() 7 | 8 | 9 | 10 | set(ENABLE_SPAN_LITE @ENABLE_SPAN_LITE@) 11 | set(ENABLE_RELIC @ENABLE_RELIC@) 12 | set(ENABLE_SODIUM @ENABLE_SODIUM@) 13 | set(ENABLE_CIRCUITS @ENABLE_CIRCUITS@) 14 | set(ENABLE_NET_LOG @ENABLE_NET_LOG@) 15 | set(ENABLE_WOLFSSL @ENABLE_WOLFSSL@) 16 | set(ENABLE_SSE @ENABLE_SSE@) 17 | set(ENABLE_AVX @ENABLE_AVX@) 18 | set(ENABLE_BOOST @ENABLE_BOOST@) 19 | set(ENABLE_OPENSSL @ENABLE_OPENSSL@) 20 | set(ENABLE_COPROTO @ENABLE_COPROTO@) 21 | set(CRYPTO_TOOLS_STD_VER @CRYPTO_TOOLS_STD_VER@) 22 | 23 | include("${CMAKE_CURRENT_LIST_DIR}/cryptoToolsDepHelper.cmake") 24 | include("${CMAKE_CURRENT_LIST_DIR}/cryptoToolsTargets.cmake") 25 | 26 | 27 | 28 | foreach(component ${cryptoTools_FIND_COMPONENTS}) 29 | if(${component} STREQUAL boost) 30 | if(NOT ENABLE_BOOST) 31 | set(cryptoTools_FOUND False) 32 | set(cryptoTools_NOT_FOUND_MESSAGE "boost not enabled in cryptoTools.") 33 | endif() 34 | elseif(${component} STREQUAL relic) 35 | if(NOT ENABLE_RELIC) 36 | set(cryptoTools_FOUND False) 37 | set(cryptoTools_NOT_FOUND_MESSAGE "relic not enabled in cryptoTools.") 38 | endif() 39 | elseif(${component} STREQUAL sodium) 40 | if(NOT ENABLE_SODIUM) 41 | set(cryptoTools_FOUND False) 42 | set(cryptoTools_NOT_FOUND_MESSAGE "sodium not enabled in cryptoTools.") 43 | endif() 44 | elseif(${component} STREQUAL circuits) 45 | if(NOT ENABLE_CIRCUITS) 46 | set(cryptoTools_FOUND False) 47 | set(cryptoTools_NOT_FOUND_MESSAGE "circuits not enabled in cryptoTools.") 48 | endif() 49 | elseif(${component} STREQUAL sse) 50 | if(NOT ENABLE_SSE) 51 | set(cryptoTools_FOUND False) 52 | set(cryptoTools_NOT_FOUND_MESSAGE "sse not enabled in cryptoTools.") 53 | endif() 54 | elseif(${component} STREQUAL avx) 55 | if(NOT ENABLE_AVX) 56 | set(cryptoTools_FOUND False) 57 | set(cryptoTools_NOT_FOUND_MESSAGE "avx not enabled in cryptoTools.") 58 | endif() 59 | elseif(${component} STREQUAL no_sse) 60 | if(ENABLE_SSE) 61 | set(cryptoTools_FOUND False) 62 | set(cryptoTools_NOT_FOUND_MESSAGE "sse enabled in cryptoTools.") 63 | endif() 64 | elseif(${component} STREQUAL no_avx) 65 | message("\n\nENABLE_AVX=${ENABLE_AVX}") 66 | if(ENABLE_AVX) 67 | set(cryptoTools_FOUND False) 68 | set(cryptoTools_NOT_FOUND_MESSAGE "avx enabled in cryptoTools.") 69 | endif() 70 | elseif(${component} STREQUAL openssl) 71 | if(NOT ENABLE_OPENSSL) 72 | set(cryptoTools_FOUND False) 73 | set(cryptoTools_NOT_FOUND_MESSAGE "openssl not enabled in cryptoTools.") 74 | endif() 75 | else() 76 | set(cryptoTools_FOUND False) 77 | set(cryptoTools_NOT_FOUND_MESSAGE "unknown cryptoTools component \"${component}\".") 78 | endif() 79 | endforeach() -------------------------------------------------------------------------------- /cmake/cryptoToolsBuildOptions.cmake: -------------------------------------------------------------------------------- 1 | 2 | include_guard(GLOBAL) 3 | 4 | set(CRYPTOTOOLS_BUILD ON) 5 | 6 | macro(EVAL var) 7 | if(${ARGN}) 8 | set(${var} ON) 9 | else() 10 | set(${var} OFF) 11 | endif() 12 | endmacro() 13 | 14 | if(DEFINED OC_PIC) 15 | message("warning, setting ENABLE_PIC as OC_PIC = ${OC_PIC}") 16 | set(ENABLE_PIC ${OC_PIC}) 17 | unset(OC_PIC CACHE) 18 | endif() 19 | 20 | if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm") 21 | # Code for ARM architecture 22 | message(STATUS "Building for ARM") 23 | set(ENABLE_ARM_AES_DEFAULT true) 24 | set(ENABLE_SSE_DEFAULT false) 25 | else() 26 | # Code for other architectures 27 | message(STATUS "Building for x86-64") 28 | set(ENABLE_ARM_AES_DEFAULT false) 29 | set(ENABLE_SSE_DEFAULT true) 30 | endif() 31 | 32 | 33 | 34 | ############################################# 35 | # CONFIGURE # 36 | ############################################# 37 | option(ENABLE_SPAN_LITE "use the span-lite library" ON) 38 | option(ENABLE_GMP "use the GMP library" OFF) 39 | option(ENABLE_RELIC "use the relic library" OFF) 40 | option(ENABLE_SODIUM "use libsodium" OFF) 41 | option(ENABLE_CIRCUITS "compile the circuit module" OFF) 42 | option(ENABLE_NET_LOG "compile with network logging" OFF) 43 | option(ENABLE_WOLFSSL "compiler with WolfSSL enabled" OFF) 44 | option(ENABLE_ARM_AES "compile with ARM AES instructions" ${ENABLE_ARM_AES_DEFAULT}) 45 | option(ENABLE_SSE "compile with SSE instructions" ${ENABLE_SSE_DEFAULT}) 46 | option(ENABLE_AVX "compile with AVX instructions" ${ENABLE_SSE}) 47 | option(ENABLE_BOOST "compile with BOOST networking integration" OFF) 48 | option(ENABLE_OPENSSL "compile with OpenSSL networking integration" OFF) 49 | option(ENABLE_ASAN "build with asan" OFF) 50 | option(ENABLE_PIC "compile with -fPIC " OFF) 51 | option(VERBOSE_FETCH "" ON) 52 | 53 | if(NOT DEFINED CRYPTO_TOOLS_STD_VER) 54 | set(CRYPTO_TOOLS_STD_VER 20) 55 | endif() 56 | if(NOT ENABLE_SSE AND ENABLE_AVX) 57 | message("AVX requires SSE to be enabled.") 58 | set(ENABLE_AVX OFF) 59 | endif() 60 | 61 | if(ENABLE_BOOST AND (CRYPTO_TOOLS_STD_VER EQUAL 14 OR CRYPTO_TOOLS_STD_VER EQUAL 17)) 62 | message(FATAL_ERROR "boost requires cpp 20 or newer.") 63 | endif() 64 | 65 | option(FETCH_AUTO "automatically download and build dependencies" OFF) 66 | 67 | #option(FETCH_SPAN_LITE "download and build span" OFF)) 68 | EVAL(FETCH_SPAN_LITE_IMPL 69 | (DEFINED FETCH_SPAN_LITE AND FETCH_SPAN_LITE) OR 70 | ((NOT DEFINED FETCH_SPAN_LITE) AND (FETCH_AUTO AND ENABLE_SPAN_LITE))) 71 | 72 | if(CRYPTO_TOOLS_STD_VER EQUAL 14 OR CRYPTO_TOOLS_STD_VER EQUAL 17) 73 | set(ENABLE_SPAN_LITE ON) 74 | else() 75 | set(ENABLE_SPAN_LITE OFF) 76 | set(FETCH_SPAN_LITE_IMPL OFF) 77 | endif() 78 | 79 | if(NOT ENABLE_SSE AND NOT ENABLE_ARM_AES) 80 | set(ENABLE_PORTABLE_AES true) 81 | endif() 82 | 83 | #option(FETCH_SPAN_LITE "download and build span" OFF)) 84 | EVAL(FETCH_GMP_IMPL 85 | (DEFINED FETCH_GMP AND FETCH_GMP) OR 86 | ((NOT DEFINED FETCH_GMP) AND (FETCH_AUTO AND ENABLE_GMP))) 87 | 88 | #option(FETCH_RELIC "download and build Relic" OFF)) 89 | EVAL(FETCH_RELIC_IMPL 90 | (DEFINED FETCH_RELIC AND FETCH_RELIC) OR 91 | ((NOT DEFINED FETCH_RELIC) AND (FETCH_AUTO AND ENABLE_RELIC))) 92 | 93 | #option(FETCH_SODIUM "download and build Sodium" OFF)) 94 | EVAL(FETCH_SODIUM_IMPL 95 | (DEFINED FETCH_SODIUM AND FETCH_SODIUM) OR 96 | ((NOT DEFINED FETCH_SODIUM) AND (FETCH_AUTO AND ENABLE_SODIUM))) 97 | 98 | #option(FETCH_BOOST "download and build Boost" OFF)) 99 | EVAL(FETCH_BOOST_IMPL 100 | (DEFINED FETCH_BOOST AND FETCH_BOOST) OR 101 | ((NOT DEFINED FETCH_BOOST) AND (FETCH_AUTO AND ENABLE_BOOST))) 102 | 103 | if(ENABLE_BOOST) 104 | set(ENABLE_COPROTO true) 105 | endif() 106 | 107 | #option(FETCH_BOOST "download and build Boost" OFF)) 108 | EVAL(FETCH_COPROTO_IMPL 109 | (DEFINED FETCH_COPROTO AND FETCH_COPROTO) OR 110 | ((NOT DEFINED FETCH_COPROTO) AND (FETCH_AUTO AND ENABLE_COPROTO))) 111 | 112 | 113 | EVAL(FETCH_LIBDIVIDE_IMPL 114 | (DEFINED FETCH_LIBDIVIDE AND FETCH_LIBDIVIDE) OR 115 | ((NOT DEFINED FETCH_LIBDIVIDE) AND (FETCH_AUTO))) 116 | 117 | 118 | option(VERBOSE_FETCH "Print build info for fetched libraries" ON) 119 | 120 | 121 | 122 | message(STATUS "cryptoTools options\n=======================================================") 123 | 124 | message(STATUS "Option: CRYPTO_TOOLS_STD_VER = ${CRYPTO_TOOLS_STD_VER}\n") 125 | 126 | message(STATUS "Option: NO_SYSTEM_PATH = ${NO_SYSTEM_PATH}") 127 | message(STATUS "Option: FETCH_AUTO = ${FETCH_AUTO}") 128 | message(STATUS "Option: VERBOSE_FETCH = ${VERBOSE_FETCH}\n") 129 | 130 | message(STATUS "Option: FETCH_RELIC = ${FETCH_RELIC}") 131 | message(STATUS "Option: FETCH_SODIUM = ${FETCH_SODIUM}") 132 | message(STATUS "Option: FETCH_BOOST = ${FETCH_BOOST}") 133 | message(STATUS "Option: FETCH_COPROTO = ${FETCH_COPROTO}") 134 | message(STATUS "Option: FETCH_LIBDIVIDE = ${FETCH_LIBDIVIDE_IMPL}\n") 135 | 136 | message(STATUS "Option: CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}\n\tRelease\n\tDebug\n\tRelWithDebInfo") 137 | message(STATUS "Option: ENABLE_SPAN_LITE = ${ENABLE_SPAN_LITE}") 138 | message(STATUS "Option: ENABLE_GMP = ${ENABLE_GMP}") 139 | message(STATUS "Option: ENABLE_RELIC = ${ENABLE_RELIC}") 140 | message(STATUS "Option: ENABLE_SODIUM = ${ENABLE_SODIUM}") 141 | message(STATUS "Option: ENABLE_BOOST = ${ENABLE_BOOST}") 142 | message(STATUS "Option: ENABLE_OPENSSL = ${ENABLE_OPENSSL}") 143 | message(STATUS "Option: ENABLE_COPROTO = ${ENABLE_COPROTO}") 144 | message(STATUS "Option: ENABLE_CIRCUITS = ${ENABLE_CIRCUITS}") 145 | 146 | message(STATUS "Option: ENABLE_ARM_AES = ${ENABLE_ARM_AES}") 147 | message(STATUS "Option: ENABLE_PORTABLE_AES = ${ENABLE_PORTABLE_AES}") 148 | 149 | message(STATUS "Option: ENABLE_SSE = ${ENABLE_SSE}") 150 | message(STATUS "Option: ENABLE_AVX = ${ENABLE_AVX}") 151 | message(STATUS "Option: ENABLE_PIC = ${ENABLE_PIC}") 152 | message(STATUS "Option: ENABLE_ASAN = ${ENABLE_ASAN}\n\n") 153 | 154 | -------------------------------------------------------------------------------- /cmake/cryptoToolsConfig.cmake: -------------------------------------------------------------------------------- 1 | # these are just pass through config file for the ones that are placed in the build directory. 2 | 3 | 4 | if(NOT DEFINED OC_CONFIG) 5 | 6 | if(MSVC) 7 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") 8 | set(OC_CONFIG "x64-Debug") 9 | else() 10 | set(OC_CONFIG "x64-Release") 11 | endif() 12 | elseif(APPLE) 13 | set(OC_CONFIG "osx") 14 | else() 15 | set(OC_CONFIG "linux") 16 | endif() 17 | endif() 18 | if(NOT DEFINED OC_THIRDPARTY_HINT) 19 | set(OC_THIRDPARTY_HINT "${CMAKE_CURRENT_LIST_DIR}/../out/install/${OC_CONFIG}") 20 | endif() 21 | 22 | 23 | include("${CMAKE_CURRENT_LIST_DIR}/cryptoToolsFindBuildDir.cmake") 24 | set(CMAKE_PREFIX_PATH "${CRYPTOTOOLS_BUILD_DIR}/macoro;${CMAKE_PREFIX_PATH}") 25 | set(CMAKE_PREFIX_PATH "${CRYPTOTOOLS_BUILD_DIR}/coproto;${CMAKE_PREFIX_PATH}") 26 | include("${CRYPTOTOOLS_BUILD_DIR}/cryptoToolsConfig.cmake") 27 | 28 | -------------------------------------------------------------------------------- /cmake/cryptoToolsConfigVersion.cmake: -------------------------------------------------------------------------------- 1 | # these are just pass through config file for the ones that are placed in the build directory. 2 | 3 | 4 | include("${CMAKE_CURRENT_LIST_DIR}/cryptoToolsFindBuildDir.cmake") 5 | include("${CRYPTOTOOLS_BUILD_DIR}/cryptoToolsConfigVersion.cmake") 6 | if(NOT EXISTS "${CRYPTOTOOLS_BUILD_DIR}") 7 | message("failed to find the cryptoTools build directory. Looked at CRYPTOTOOLS_BUILD_DIR: ${CRYPTOTOOLS_BUILD_DIR}") 8 | set(PACKAGE_VERSION_UNSUITABLE TRUE) 9 | endif() 10 | 11 | -------------------------------------------------------------------------------- /cmake/cryptoToolsFindBuildDir.cmake: -------------------------------------------------------------------------------- 1 | 2 | 3 | if(NOT DEFINED CMAKE_BUILD_TYPE) 4 | set(OC_BUILD_TYPE "Release") 5 | else() 6 | set(OC_BUILD_TYPE "${CMAKE_BUILD_TYPE}") 7 | endif() 8 | 9 | if(MSVC) 10 | set(OC_CONFIG "x64-${OC_BUILD_TYPE}") 11 | elseif(APPLE) 12 | set(OC_CONFIG "osx") 13 | else() 14 | set(OC_CONFIG "linux") 15 | endif() 16 | 17 | 18 | if(NOT CRYPTOTOOLS_BUILD_DIR) 19 | set(CRYPTOTOOLS_BUILD_DIR "${CMAKE_CURRENT_LIST_DIR}/../out/build/${OC_CONFIG}") 20 | else() 21 | if(NOT DEFINED LIBOTE_BUILD_DIR) 22 | message(STATUS "CRYPTOTOOLS_BUILD_DIR preset to ${CRYPTOTOOLS_BUILD_DIR}") 23 | endif() 24 | endif() 25 | 26 | -------------------------------------------------------------------------------- /cmake/install.cmake: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ############################################# 8 | # Install # 9 | ############################################# 10 | 11 | 12 | configure_file("${CMAKE_CURRENT_LIST_DIR}/cryptoToolsDepHelper.cmake" "cryptoToolsDepHelper.cmake" COPYONLY) 13 | 14 | # make cache variables for install destinations 15 | include(GNUInstallDirs) 16 | include(CMakePackageConfigHelpers) 17 | 18 | 19 | # generate the config file that is includes the exports 20 | configure_package_config_file( 21 | "${CMAKE_CURRENT_LIST_DIR}/Config.cmake.in" 22 | "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsConfig.cmake" 23 | INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cryptoTools 24 | NO_SET_AND_CHECK_MACRO 25 | NO_CHECK_REQUIRED_COMPONENTS_MACRO 26 | ) 27 | 28 | if(NOT DEFINED cryptoTools_VERSION_MAJOR) 29 | message("\n\n\n\n warning, cryptoTools_VERSION_MAJOR not defined ${cryptoTools_VERSION_MAJOR}") 30 | endif() 31 | 32 | set_property(TARGET cryptoTools PROPERTY VERSION ${cryptoTools_VERSION}) 33 | 34 | # generate the version file for the config file 35 | write_basic_package_version_file( 36 | "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsConfigVersion.cmake" 37 | VERSION "${cryptoTools_VERSION_MAJOR}.${cryptoTools_VERSION_MINOR}.${cryptoTools_VERSION_PATCH}" 38 | COMPATIBILITY AnyNewerVersion 39 | ) 40 | 41 | # install the configuration file 42 | install(FILES 43 | "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsConfig.cmake" 44 | "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsConfigVersion.cmake" 45 | "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsDepHelper.cmake" 46 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cryptoTools 47 | ) 48 | 49 | # install library 50 | install( 51 | TARGETS cryptoTools tests_cryptoTools 52 | DESTINATION ${CMAKE_INSTALL_LIBDIR} 53 | EXPORT cryptoToolsTargets) 54 | 55 | # install headers 56 | install( 57 | DIRECTORY "${CMAKE_CURRENT_LIST_DIR}/../cryptoTools" 58 | DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/" 59 | FILES_MATCHING PATTERN "*.h") 60 | #install config header 61 | install( 62 | DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/cryptoTools" 63 | DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/" 64 | FILES_MATCHING PATTERN "*.h") 65 | 66 | # tests_cryptoTools headers 67 | install( 68 | DIRECTORY "${CMAKE_CURRENT_LIST_DIR}/../tests_cryptoTools" 69 | DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/" 70 | FILES_MATCHING PATTERN "*.h") 71 | 72 | # install config 73 | install(EXPORT cryptoToolsTargets 74 | FILE cryptoToolsTargets.cmake 75 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cryptoTools 76 | NAMESPACE oc:: 77 | ) 78 | export(EXPORT cryptoToolsTargets 79 | FILE "${CMAKE_CURRENT_BINARY_DIR}/cryptoToolsTargets.cmake" 80 | NAMESPACE oc:: 81 | ) -------------------------------------------------------------------------------- /cryptoTools/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(cryptoTools) 2 | 3 | include(FindPkgConfig) 4 | 5 | get_directory_property(hasParent PARENT_DIRECTORY) 6 | 7 | # add the source files 8 | file(GLOB_RECURSE SRCS *.cpp *.c) 9 | add_library(cryptoTools STATIC ${SRCS}) 10 | 11 | # make projects that include cryptoTools use this as an include folder 12 | target_include_directories(cryptoTools PUBLIC 13 | $ 14 | $) 15 | target_include_directories(cryptoTools PUBLIC 16 | $ 17 | $) 18 | 19 | 20 | if(MSVC) 21 | if(ENABLE_ASAN) 22 | message("Warning: ASAN is enabled for cryptoTools") 23 | target_compile_options(cryptoTools PUBLIC "/fsanitize=address") 24 | endif() 25 | 26 | target_compile_options(cryptoTools PRIVATE $<$:/std:c++${CRYPTO_TOOLS_STD_VER}>) 27 | 28 | else() 29 | target_compile_options(cryptoTools PRIVATE $<$:-std=c++${CRYPTO_TOOLS_STD_VER}> -pthread) 30 | 31 | target_link_options(cryptoTools PUBLIC -pthread) 32 | 33 | 34 | if(ENABLE_SSE) 35 | target_compile_options(cryptoTools PUBLIC -maes -msse2 -msse3 -mssse3 -msse4.1 -mpclmul) 36 | endif() 37 | if(ENABLE_AVX) 38 | target_compile_options(cryptoTools PUBLIC -mavx2) 39 | endif() 40 | if(ENABLE_ARM_AES) 41 | if(NOT DEFINED ARM_ARCHITECTURE) 42 | set(ARM_ARCHITECTURE native) 43 | endif() 44 | target_compile_options(cryptoTools PUBLIC -march=${ARM_ARCHITECTURE}+crypto) 45 | endif() 46 | if(ENABLE_PIC) 47 | target_compile_options(cryptoTools PUBLIC -fPIC) 48 | endif() 49 | 50 | 51 | if(ENABLE_ASAN) 52 | message("Warning: ASAN is enabled for cryptoTools") 53 | target_compile_options(cryptoTools PUBLIC "-fsanitize=address") 54 | target_link_options(cryptoTools PUBLIC "-fsanitize=address") 55 | endif() 56 | endif() 57 | 58 | 59 | target_link_libraries(cryptoTools libdivide) 60 | 61 | ## span-lite 62 | ########################################################################### 63 | 64 | if(ENABLE_SPAN_LITE) 65 | target_link_libraries(cryptoTools nonstd::span-lite) 66 | endif() 67 | 68 | ## span-lite 69 | ########################################################################### 70 | 71 | if (ENABLE_SPAN_LITE) 72 | target_link_libraries(cryptoTools nonstd::span-lite) 73 | endif (ENABLE_SPAN_LITE) 74 | 75 | ## Relic 76 | ########################################################################### 77 | 78 | if (ENABLE_RELIC) 79 | target_link_libraries(cryptoTools relic) 80 | endif (ENABLE_RELIC) 81 | 82 | # libsodium 83 | ########################################################################### 84 | 85 | if (ENABLE_SODIUM) 86 | target_link_libraries(cryptoTools sodium) 87 | endif (ENABLE_SODIUM) 88 | 89 | 90 | # coproto 91 | ########################################################################### 92 | 93 | if (ENABLE_COPROTO) 94 | target_link_libraries(cryptoTools coproto) 95 | endif (ENABLE_COPROTO) 96 | 97 | 98 | if(ENABLE_GMP) 99 | target_link_libraries(cryptoTools GMP::libgmp GMP::libgmpxx) 100 | endif() 101 | 102 | ### WolfSSL 103 | ############################################################################ 104 | # 105 | #if(ENABLE_WOLFSSL) 106 | # target_include_directories(cryptoTools PUBLIC 107 | # $ 108 | # $) 109 | # target_link_libraries(cryptoTools ${WOLFSSL_LIB}) 110 | #endif(ENABLE_WOLFSSL) 111 | # 112 | ### Boost 113 | ############################################################################ 114 | # 115 | # 116 | #if(ENABLE_BOOST) 117 | # target_include_directories(cryptoTools PUBLIC 118 | # $ 119 | # $) 120 | # target_link_libraries(cryptoTools ${Boost_LIBRARIES}) 121 | #endif() 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /cryptoTools/Circuit/Gate.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #ifdef ENABLE_CIRCUITS 4 | #include 5 | #include 6 | 7 | namespace osuCrypto { 8 | 9 | typedef u64 Wire; 10 | 11 | inline u8 PermuteBit(const block& b) 12 | { 13 | return *(u8*)&(b)& 1; 14 | } 15 | 16 | enum class GateType : u8 17 | { 18 | Zero = 0, //0000, 19 | Nor = 1, //0001 20 | nb_And = 2, //0010 21 | nb = 3, //0011 22 | na_And = 4, //0100 23 | na = 5, //0101 24 | Xor = 6, //0110 25 | Nand = 7, //0111 26 | And = 8, //1000 27 | Nxor = 9, //1001 28 | a = 10, //1010 29 | nb_Or = 11, //1011 30 | b = 12, //1100 31 | na_Or = 13,//1101 32 | Or = 14,//1110 33 | One = 15 //1111 34 | }; 35 | 36 | 37 | inline std::string gateToString(GateType type) 38 | { 39 | if(type == GateType::Zero )return "Zero "; 40 | if(type == GateType::Nor )return "Nor "; 41 | if(type == GateType::nb_And)return "nb_And"; 42 | if(type == GateType::nb )return "nb "; 43 | if(type == GateType::na_And)return "na_And"; 44 | if(type == GateType::na )return "na "; 45 | if(type == GateType::Xor )return "Xor "; 46 | if(type == GateType::Nand )return "Nand "; 47 | if(type == GateType::And )return "And "; 48 | if(type == GateType::Nxor )return "Nxor "; 49 | if(type == GateType::a )return "a "; 50 | if(type == GateType::nb_Or )return "nb_Or "; 51 | if(type == GateType::b )return "b "; 52 | if(type == GateType::na_Or )return "na_Or "; 53 | if(type == GateType::Or )return "Or "; 54 | if(type == GateType::One )return "One "; 55 | return ""; 56 | } 57 | 58 | inline bool isLinear(GateType type) 59 | { 60 | return 61 | type == GateType::Xor || 62 | type == GateType::Nxor || 63 | type == GateType::a || 64 | type == GateType::Zero || 65 | type == GateType::nb || 66 | type == GateType::na || 67 | type == GateType::b || 68 | type == GateType::One; 69 | } 70 | 71 | inline u8 GateEval(GateType type, bool a, bool b) 72 | { 73 | u8 v = ((u8(a) & 1) | (u8(b) <<1)); 74 | return ((u8)type & (1 << v)) ? 1 : 0; 75 | } 76 | 77 | struct Gate 78 | { 79 | u8 eval(u64 i) const 80 | { 81 | return ((u8)mType & (1 << i))? 1 : 0; 82 | } 83 | 84 | Gate(u64 input0, u64 input1, u64 output, GateType gt) 85 | { 86 | mInput = { { input0, input1 } }; 87 | mType = gt; 88 | mWireIdx = output; 89 | 90 | // compute the gate modifier variables 91 | //mAAlpha = (gt == GateType::Nor || gt == GateType::na_And || gt == GateType::nb_Or || gt == GateType::Or); 92 | //mBAlpha = (gt == GateType::Nor || gt == GateType::nb_And || gt == GateType::na_Or || gt == GateType::Or); 93 | //mCAlpha = (gt == GateType::Nand || gt == GateType::nb_Or || gt == GateType::na_Or || gt == GateType::Or); 94 | } 95 | 96 | std::array mInput; 97 | u64 mWireIdx; 98 | inline const GateType& Type() const { return mType; } 99 | private: 100 | GateType mType; 101 | }; 102 | 103 | 104 | template 105 | struct GarbledGate// : public Gate 106 | { 107 | public: 108 | std::array mGarbledTable; 109 | //GarbledGate(const Gate& gate) 110 | // : Gate(gate) 111 | //{} 112 | }; 113 | } 114 | #endif -------------------------------------------------------------------------------- /cryptoTools/Circuit/MxBit.cpp: -------------------------------------------------------------------------------- 1 | #include "MxBit.h" 2 | #ifdef ENABLE_CIRCUITS 3 | 4 | #include "MxCircuit.h" 5 | 6 | namespace osuCrypto 7 | { 8 | 9 | namespace Mx 10 | { 11 | 12 | 13 | 14 | 15 | Bit& Bit::operator=(bool b) 16 | { 17 | mCir = (Circuit*)(b ? 1ull : 0ull); 18 | mAddress = {}; 19 | return *this; 20 | } 21 | 22 | 23 | Bit Bit::operator^(const Bit& b)const 24 | { 25 | return addGate(OpType::Xor, b); 26 | } 27 | Bit Bit::operator&(const Bit& b)const 28 | { 29 | return addGate(OpType::And, b); 30 | } 31 | Bit Bit::operator|(const Bit& b)const 32 | { 33 | return addGate(OpType::Or, b); 34 | } 35 | Bit Bit::operator!() const 36 | { 37 | if (isConst()) 38 | { 39 | Bit r; 40 | r.mCir = (Circuit*)((u64)mCir ^ 1); 41 | return r; 42 | } 43 | 44 | return circuit()->negate(*this); 45 | } 46 | Bit Bit::operator~() const 47 | { 48 | return !*this; 49 | } 50 | 51 | Bit Bit::addGate(OpType t, const Bit& b) const 52 | { 53 | 54 | if (isConst() || b.isConst()) 55 | { 56 | if (isConst() && b.isConst()) 57 | { 58 | switch (t) 59 | { 60 | case osuCrypto::Mx::OpType::Xor: 61 | return constValue() ^ b.constValue(); 62 | case osuCrypto::Mx::OpType::And: 63 | return constValue() && b.constValue(); 64 | case osuCrypto::Mx::OpType::Or: 65 | return constValue() || b.constValue(); 66 | default: 67 | throw std::runtime_error("Bit::addGate(...) for OpType that is not implemented. " LOCATION); 68 | } 69 | } 70 | else 71 | { 72 | auto c = isConst() ? constValue() : b.constValue(); 73 | auto& w = isConst() ? b : *this; 74 | auto cir = isConst() ? b.circuit() : circuit(); 75 | 76 | switch (t) 77 | { 78 | case osuCrypto::Mx::OpType::Xor: 79 | return c ? cir->negate(w) : w; 80 | case osuCrypto::Mx::OpType::And: 81 | return c ? w : 0; 82 | case osuCrypto::Mx::OpType::Or: 83 | return c ? 1 : w; 84 | default: 85 | throw std::runtime_error("Bit::addGate(...) for OpType that is not implemented. " LOCATION); 86 | } 87 | } 88 | } 89 | 90 | return circuit()->addGate(t, *this, b); 91 | } 92 | } 93 | 94 | } 95 | #endif 96 | -------------------------------------------------------------------------------- /cryptoTools/Circuit/MxCircuitLibrary.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "cryptoTools/Common/Defines.h" 3 | #ifdef ENABLE_CIRCUITS 4 | 5 | #include "cryptoTools/Common/Matrix.h" 6 | #include "MxBit.h" 7 | 8 | namespace osuCrypto 9 | { 10 | namespace Mx 11 | { 12 | 13 | 14 | enum class Optimized 15 | { 16 | Size, 17 | Depth 18 | }; 19 | 20 | enum class IntType 21 | { 22 | TwosComplement, 23 | Unsigned 24 | }; 25 | enum class AdderType 26 | { 27 | Addition, 28 | Subtraction 29 | }; 30 | 31 | // takes a integer `a` as input. If `it` is twos complement, then we 32 | // append the MSB of `a` until it is `size` bits. Otherwise we append 33 | // 0. 34 | inline std::vector signExtendResize(span a, u64 size, IntType it) 35 | { 36 | std::vector b(a.begin(), a.end()); 37 | if (it == IntType::TwosComplement) 38 | { 39 | while (b.size() < size) 40 | b.push_back(b.back()); 41 | } 42 | else 43 | { 44 | while (b.size() < size) 45 | b.push_back(Bit(0)); 46 | } 47 | b.resize(size); 48 | return b; 49 | } 50 | 51 | // add or substracts a1 and a2. Does this with O(n log n) AND gates. 52 | // and O(log n) depth. 53 | void parallelPrefix( 54 | span a1, 55 | span a2, 56 | span sum, 57 | IntType it, 58 | AdderType at); 59 | 60 | // compare a1 and a2 for equality. Must be the same size. 61 | Bit parallelEquality(span a1, span a2); 62 | 63 | // ripple carry adder with parameters 64 | // a1, a2 and carry in cIn. The output 65 | // is sum = a1[i] ^ a2[i] ^ cIn 66 | // and the carry out bit cOut. Works 67 | // for addition and subtraction. 68 | void rippleAdder( 69 | Bit a1, 70 | Bit a2, 71 | Bit cIn, 72 | Bit& sum, 73 | Bit& cOut, 74 | AdderType at); 75 | 76 | // ripple carry adder with parameters 77 | // a1, a2. The output 78 | // is sum = a1+a2. Works 79 | // for addition and subtraction. 80 | void rippleAdder( 81 | span a1, 82 | span a2, 83 | span sum, 84 | IntType it, 85 | AdderType at); 86 | 87 | inline void add(span a1_, span a2_, span sum, IntType it, AdderType at, Optimized op) 88 | { 89 | if (op == Optimized::Size) 90 | rippleAdder(a1_, a2_, sum, it, at); 91 | else 92 | parallelPrefix(a1_, a2_, sum, it, at); 93 | } 94 | 95 | // compute the summation x[0] + x[1] + ... 96 | void parallelSummation( 97 | span> x, 98 | span sum, 99 | Optimized op, 100 | IntType it 101 | ); 102 | 103 | void negate( 104 | span a1, 105 | span ret, 106 | Optimized op); 107 | 108 | 109 | void removeSign( 110 | span a1, 111 | span ret, 112 | Optimized op); 113 | 114 | 115 | void addSign( 116 | Bit sign, 117 | span a1, 118 | span ret, 119 | Optimized op); 120 | 121 | 122 | void lessThan( 123 | span a1, 124 | span a2, 125 | Bit& ret, 126 | IntType it, 127 | Optimized op); 128 | 129 | // computes dst = a1 * a2; 130 | void multiply( 131 | span a1, 132 | span a2, 133 | span dst, 134 | Optimized op, 135 | IntType it); 136 | 137 | void divideRemainder( 138 | span dividend, 139 | span divider, 140 | span quotient, 141 | span rem, 142 | Optimized op, 143 | IntType it); 144 | } 145 | 146 | } 147 | #endif 148 | -------------------------------------------------------------------------------- /cryptoTools/Common/CLP.cpp: -------------------------------------------------------------------------------- 1 | #include "CLP.h" 2 | #include 3 | #include 4 | #include "Defines.h" 5 | 6 | namespace osuCrypto 7 | { 8 | 9 | void CLP::parse(int argc, char const*const* argv) 10 | { 11 | if (argc > 0) 12 | { 13 | std::stringstream ss; 14 | auto ptr = argv[0]; 15 | while (*ptr != 0) 16 | ss << *ptr++; 17 | mProgramName = ss.str(); 18 | } 19 | 20 | for (int i = 1; i < argc;) 21 | { 22 | mFullStr += std::string(argv[i]) + " "; 23 | 24 | auto ptr = argv[i]; 25 | if (*ptr++ != '-') 26 | { 27 | throw CommandLineParserError("While parsing the argv string, one of the leading terms did not start with a - indicator."); 28 | } 29 | 30 | std::stringstream ss; 31 | 32 | while (*ptr != 0) 33 | ss << *ptr++; 34 | 35 | ++i; 36 | ptr = argv[i]; 37 | 38 | std::pair> keyValues; 39 | keyValues.first = ss.str();; 40 | 41 | while (i < argc && (ptr[0] != '-' || (ptr[0] == '-' && ptr[1] >= '0' && ptr[1] <= '9'))) 42 | { 43 | ss.str(""); 44 | 45 | while (*ptr != 0) 46 | ss << *ptr++; 47 | 48 | keyValues.second.push_back(ss.str()); 49 | 50 | ++i; 51 | ptr = argv[i]; 52 | } 53 | 54 | mKeyValues.emplace(keyValues); 55 | } 56 | } 57 | std::vector split(const std::string& s, char delim); 58 | 59 | void CLP::setDefault(std::string key, std::string value) 60 | { 61 | if (hasValue(key) == false) 62 | { 63 | if (isSet(key)) 64 | { 65 | mKeyValues[key].emplace_back(value); 66 | } 67 | else 68 | { 69 | auto parts = split(value, ' '); 70 | mKeyValues.emplace(std::make_pair(key, std::list{ parts.begin(), parts.end()})); 71 | } 72 | } 73 | 74 | } 75 | void CLP::setDefault(std::vector keys, std::string value) 76 | { 77 | if (hasValue(keys) == false) 78 | { 79 | setDefault(keys[0], value); 80 | } 81 | } 82 | 83 | void CLP::set(std::string name) 84 | { 85 | mKeyValues[name]; 86 | } 87 | 88 | bool CLP::isSet(std::string name)const 89 | { 90 | return mKeyValues.find(name) != mKeyValues.end(); 91 | } 92 | bool CLP::isSet(std::vector names)const 93 | { 94 | for (auto name : names) 95 | { 96 | if (isSet(name)) 97 | { 98 | return true; 99 | } 100 | } 101 | return false; 102 | } 103 | 104 | bool CLP::hasValue(std::string name)const 105 | { 106 | return mKeyValues.find(name) != mKeyValues.end() && mKeyValues.at(name).size(); 107 | } 108 | bool CLP::hasValue(std::vector names)const 109 | { 110 | for (auto name : names) 111 | { 112 | if (hasValue(name)) 113 | { 114 | return true; 115 | } 116 | } 117 | return false; 118 | } 119 | 120 | const std::list& CLP::getList(std::vector names) const 121 | { 122 | for (auto name : names) 123 | { 124 | if (isSet(name)) 125 | { 126 | return mKeyValues.find(name)->second; 127 | } 128 | } 129 | throw CommandLineParserError("key not set"); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /cryptoTools/Common/Defines.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace osuCrypto 9 | { 10 | 11 | 12 | 13 | block PRF(const block& b, u64 i) 14 | { 15 | return AES(b).ecbEncBlock(toBlock(i)); 16 | } 17 | 18 | void split(const std::string &s, char delim, std::vector &elems) { 19 | std::stringstream ss(s); 20 | std::string item; 21 | while (std::getline(ss, item, delim)) { 22 | elems.push_back(item); 23 | } 24 | } 25 | 26 | std::vector split(const std::string &s, char delim) { 27 | std::vector elems; 28 | split(s, delim, elems); 29 | return elems; 30 | } 31 | 32 | block sysRandomSeed() 33 | { 34 | std::random_device rd; 35 | auto ret = std::array{rd(), rd(), rd(), rd()}; 36 | block blk; 37 | memcpy(&blk, &ret, sizeof(block)); 38 | return blk; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /cryptoTools/Common/Finally.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace osuCrypto 6 | { 7 | 8 | class Finally 9 | { 10 | std::function mFinalizer; 11 | Finally() = delete; 12 | 13 | public: 14 | Finally(const Finally& other) = delete; 15 | Finally(std::function finalizer) 16 | : mFinalizer(finalizer) 17 | { 18 | } 19 | ~Finally() 20 | { 21 | if (mFinalizer) 22 | mFinalizer(); 23 | } 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /cryptoTools/Common/Log.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #ifdef _MSC_VER 5 | #include 6 | #endif 7 | 8 | 9 | namespace osuCrypto 10 | { 11 | std::chrono::time_point gStart = std::chrono::system_clock::now(); 12 | 13 | 14 | ostreamLocker lout(std::cout); 15 | std::mutex gIoStreamMtx; 16 | 17 | void setThreadName(const std::string name) 18 | { 19 | setThreadName(name.c_str()); 20 | } 21 | void setThreadName(const char* name) 22 | { 23 | #ifndef NDEBUG 24 | #ifdef _MSC_VER 25 | const DWORD MS_VC_EXCEPTION = 0x406D1388; 26 | 27 | #pragma pack(push,8) 28 | typedef struct tagTHREADNAME_INFO 29 | { 30 | DWORD dwType; // Must be 0x1000. 31 | LPCSTR szName; // Pointer to name (in user addr space). 32 | DWORD dwThreadID; // Thread ID (-1=caller thread). 33 | DWORD dwFlags; // Reserved for future use, must be zero. 34 | } THREADNAME_INFO; 35 | #pragma pack(pop) 36 | 37 | 38 | THREADNAME_INFO info; 39 | info.dwType = 0x1000; 40 | info.szName = name; 41 | info.dwThreadID = -1; 42 | info.dwFlags = 0; 43 | 44 | __try 45 | { 46 | RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); 47 | } 48 | __except (EXCEPTION_EXECUTE_HANDLER) 49 | { 50 | } 51 | #endif 52 | #endif 53 | } 54 | 55 | const Color ColorDefault([]() -> Color { 56 | #ifdef _MSC_VER 57 | CONSOLE_SCREEN_BUFFER_INFO csbi; 58 | HANDLE m_hConsole = GetStdHandle(STD_OUTPUT_HANDLE); 59 | GetConsoleScreenBufferInfo(m_hConsole, &csbi); 60 | 61 | return (Color)(csbi.wAttributes & 255); 62 | #else 63 | return Color::White; 64 | #endif 65 | 66 | }()); 67 | 68 | #ifdef _MSC_VER 69 | static const HANDLE __m_hConsole(GetStdHandle(STD_OUTPUT_HANDLE)); 70 | #endif 71 | #define RESET "\033[0m" 72 | #define BLACK "\033[30m" /* Black */ 73 | #define RED "\033[31m" /* Red */ 74 | #define GREEN "\033[32m" /* Green */ 75 | #define YELLOW "\033[33m" /* Yellow */ 76 | #define BLUE "\033[34m" /* Blue */ 77 | #define MAGENTA "\033[35m" /* Magenta */ 78 | #define CYAN "\033[36m" /* Cyan */ 79 | #define WHITE "\033[37m" /* White */ 80 | #define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ 81 | #define BOLDRED "\033[1m\033[31m" /* Bold Red */ 82 | #define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ 83 | #define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ 84 | #define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ 85 | #define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ 86 | #define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ 87 | #define BOLDWHITE "\033[1m\033[37m" /* Bold White */ 88 | 89 | std::array colorMap 90 | { 91 | "", // -- = 0, 92 | "", // -- = 1, 93 | GREEN, // LightGreen = 2, 94 | BLACK, // LightGrey = 3, 95 | RED, // LightRed = 4, 96 | WHITE, // OffWhite1 = 5, 97 | WHITE, // OffWhite2 = 6, 98 | "", // = 7 99 | BLACK, // Grey = 8, 100 | "", // -- = 9, 101 | BOLDGREEN, // Green = 10, 102 | BOLDBLUE, // Blue = 11, 103 | BOLDRED, // Red = 12, 104 | BOLDCYAN, // Pink = 13, 105 | BOLDYELLOW, // Yellow = 14, 106 | RESET // White = 15 107 | }; 108 | 109 | std::ostream& operator<<(std::ostream& out, Color tag) 110 | { 111 | if (tag == Color::Default) 112 | tag = ColorDefault; 113 | #ifdef _MSC_VER 114 | SetConsoleTextAttribute(__m_hConsole, (WORD)tag | (240 & (WORD)ColorDefault) ); 115 | #else 116 | 117 | out << colorMap[15 & (char)tag]; 118 | #endif 119 | return out; 120 | } 121 | 122 | 123 | std::ostream& operator<<(std::ostream& out, IoStream tag) 124 | { 125 | if (tag == IoStream::lock) 126 | { 127 | gIoStreamMtx.lock(); 128 | } 129 | else 130 | { 131 | gIoStreamMtx.unlock(); 132 | } 133 | 134 | return out; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /cryptoTools/Common/Log.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | 11 | namespace osuCrypto 12 | { 13 | extern std::chrono::time_point gStart; 14 | class Log 15 | { 16 | public: 17 | Log() = default; 18 | Log(const Log& c) { 19 | 20 | std::lock_guardl(const_cast(c.mLock)); 21 | mMessages = c.mMessages; 22 | } 23 | 24 | std::vector> mMessages; 25 | std::mutex mLock; 26 | 27 | void push(const std::string& msg) 28 | { 29 | std::lock_guardl(mLock); 30 | 31 | 32 | auto now = std::chrono::system_clock::now(); 33 | auto ts = std::chrono::duration_cast(now - gStart).count(); 34 | 35 | mMessages.emplace_back(ts, msg); 36 | } 37 | 38 | }; 39 | inline std::ostream& operator<<(std::ostream& o, Log& log) 40 | { 41 | std::lock_guardl(log.mLock); 42 | for (u64 i = 0; i < log.mMessages.size(); ++i) 43 | { 44 | o << "[" << i << ", " << log.mMessages[i].first / 1000.0 << "ms ] " << log.mMessages[i].second << std::endl; 45 | } 46 | 47 | return o; 48 | } 49 | class LogAdapter 50 | { 51 | public: 52 | Log* mLog = nullptr; 53 | 54 | LogAdapter() = default; 55 | LogAdapter(const LogAdapter&) = default; 56 | LogAdapter(Log& log) : mLog(&log) {} 57 | 58 | void push(const std::string& msg) 59 | { 60 | if (mLog) 61 | mLog->push(msg); 62 | } 63 | 64 | void setLog(Log& log) 65 | { 66 | mLog = &log; 67 | } 68 | }; 69 | 70 | inline std::ostream& operator<<(std::ostream& o, LogAdapter& log) 71 | { 72 | if (log.mLog) 73 | o << *log.mLog; 74 | else 75 | o << "{null log}"; 76 | return o; 77 | } 78 | 79 | enum class Color { 80 | LightGreen = 2, 81 | LightGrey = 3, 82 | LightRed = 4, 83 | OffWhite1 = 5, 84 | OffWhite2 = 6, 85 | Grey = 8, 86 | Green = 10, 87 | Blue = 11, 88 | Red = 12, 89 | Pink = 13, 90 | Yellow = 14, 91 | White = 15, 92 | Default 93 | }; 94 | 95 | extern const Color ColorDefault; 96 | 97 | 98 | std::ostream& operator<<(std::ostream& out, Color color); 99 | 100 | enum class IoStream 101 | { 102 | lock, 103 | unlock 104 | }; 105 | 106 | extern std::mutex gIoStreamMtx; 107 | 108 | struct ostreamLock 109 | { 110 | std::ostream& out; 111 | std::unique_lock mLock; 112 | 113 | ostreamLock(ostreamLock&&) = default; 114 | 115 | ostreamLock(std::ostream& o, std::mutex& lock = gIoStreamMtx) : 116 | out(o), 117 | mLock(lock) 118 | {} 119 | 120 | template 121 | ostreamLock& operator<<(const T& v) 122 | { 123 | out << v; 124 | return *this; 125 | } 126 | 127 | template 128 | ostreamLock& operator<<(T& v) 129 | { 130 | out << v; 131 | return *this; 132 | } 133 | ostreamLock& operator<< (std::ostream& (*v)(std::ostream&)) 134 | { 135 | out << v; 136 | return *this; 137 | } 138 | ostreamLock& operator<< (std::ios& (*v)(std::ios&)) 139 | { 140 | out << v; 141 | return *this; 142 | } 143 | ostreamLock& operator<< (std::ios_base& (*v)(std::ios_base&)) 144 | { 145 | out << v; 146 | return *this; 147 | } 148 | }; 149 | 150 | 151 | struct ostreamLocker 152 | { 153 | std::ostream& out; 154 | 155 | ostreamLocker(std::ostream& o) : 156 | out(o) 157 | {} 158 | 159 | template 160 | ostreamLock operator<<(const T& v) 161 | { 162 | ostreamLock r(out); 163 | r << v; 164 | 165 | #ifndef NO_RETURN_ELISION 166 | return r; 167 | #else 168 | return std::move(r); 169 | #endif 170 | } 171 | 172 | template 173 | ostreamLock operator<<(T& v) 174 | { 175 | ostreamLock r(out); 176 | r << v; 177 | #ifndef NO_RETURN_ELISION 178 | return r; 179 | #else 180 | return std::move(r); 181 | #endif 182 | } 183 | ostreamLock operator<< (std::ostream& (*v)(std::ostream&)) 184 | { 185 | ostreamLock r(out); 186 | r << v; 187 | #ifndef NO_RETURN_ELISION 188 | return r; 189 | #else 190 | return std::move(r); 191 | #endif 192 | } 193 | ostreamLock operator<< (std::ios& (*v)(std::ios&)) 194 | { 195 | ostreamLock r(out); 196 | r << v; 197 | #ifndef NO_RETURN_ELISION 198 | return r; 199 | #else 200 | return std::move(r); 201 | #endif 202 | } 203 | ostreamLock operator<< (std::ios_base& (*v)(std::ios_base&)) 204 | { 205 | ostreamLock r(out); 206 | r << v; 207 | #ifndef NO_RETURN_ELISION 208 | return r; 209 | #else 210 | return std::move(r); 211 | #endif 212 | } 213 | }; 214 | extern ostreamLocker lout; 215 | 216 | std::ostream& operator<<(std::ostream& out, IoStream color); 217 | 218 | 219 | void setThreadName(const std::string name); 220 | void setThreadName(const char* name); 221 | 222 | } 223 | -------------------------------------------------------------------------------- /cryptoTools/Common/MatrixView.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #include 5 | #include 6 | 7 | namespace osuCrypto 8 | { 9 | 10 | template 11 | class MatrixView 12 | { 13 | public: 14 | 15 | using iterator = typename span::iterator; 16 | using const_iterator = typename span::iterator; 17 | 18 | using reverse_iterator = std::reverse_iterator; 19 | using const_reverse_iterator = std::reverse_iterator; 20 | 21 | typedef T value_type; 22 | typedef value_type* pointer; 23 | typedef u64 size_type; 24 | 25 | 26 | MatrixView() 27 | :mStride(0) 28 | { 29 | } 30 | 31 | MatrixView(const MatrixView& av) : 32 | mView(av.mView), 33 | mStride(av.mStride) 34 | { } 35 | 36 | MatrixView(pointer data, size_type numRows, size_type stride) : 37 | mView(data, numRows * stride), 38 | mStride(stride) 39 | {} 40 | 41 | MatrixView(pointer start, pointer end, size_type stride) : 42 | mView(start, end - ((end - start) % stride)), 43 | mStride(stride) 44 | { 45 | } 46 | 47 | template 48 | MatrixView(Iter start, Iter end, size_type stride, typename Iter::iterator_category * = 0) : 49 | mView(start, end/* - ((end - start) % stride)*/), 50 | mStride(stride) 51 | { 52 | //std::ignore = p; 53 | } 54 | 55 | template class C, typename... Args> 56 | MatrixView(const C& cont, size_type stride, typename C::value_type* = 0) : 57 | MatrixView(cont.begin(), cont.end(), stride) 58 | { 59 | //std::ignore = p; 60 | } 61 | 62 | const MatrixView& operator=(const MatrixView& copy) 63 | { 64 | mView = copy.mView; 65 | mStride = copy.mStride; 66 | return copy; 67 | } 68 | 69 | 70 | void reshape(size_type rows, size_type columns) 71 | { 72 | if (rows * columns != size()) 73 | throw std::runtime_error(LOCATION); 74 | 75 | mView = span(mView.data(), rows * columns); 76 | mStride = columns; 77 | } 78 | 79 | const size_type size() const { return mView.size(); } 80 | const size_type stride() const { return mStride; } 81 | 82 | // returns the number of rows followed by the stride. 83 | std::array bounds() const { return { rows(), stride() }; } 84 | 85 | u64 rows() const { 86 | return stride() ? size() / stride() : 0; 87 | } 88 | u64 cols() const { return stride(); } 89 | 90 | pointer data() const { return mView.data(); }; 91 | pointer data(u64 rowIdx) const 92 | { 93 | #ifndef NDEBUG 94 | if (rowIdx >= rows()) throw std::runtime_error(LOCATION); 95 | #endif 96 | return mView.data() + rowIdx * stride(); 97 | }; 98 | 99 | iterator begin() const { return mView.begin(); }; 100 | iterator end() const { return mView.end(); } 101 | 102 | T& operator()(size_type idx) 103 | { 104 | return mView[idx]; 105 | } 106 | 107 | const T& operator()(size_type idx) const 108 | { 109 | return mView[idx]; 110 | } 111 | 112 | T& operator()(size_type rowIdx, size_type colIdx) 113 | { 114 | return mView[rowIdx * stride() + colIdx]; 115 | } 116 | 117 | const T& operator()(size_type rowIdx, size_type colIdx) const 118 | { 119 | return mView[rowIdx * stride() + colIdx]; 120 | } 121 | 122 | const span operator[](size_type rowIdx) const 123 | { 124 | #ifndef NDEBUG 125 | if (rowIdx >= rows()) throw std::runtime_error(LOCATION); 126 | #endif 127 | 128 | return span(mView.data() + rowIdx * stride(), stride()); 129 | } 130 | 131 | 132 | operator MatrixView() 133 | { 134 | return { data(), rows(), cols() }; 135 | } 136 | 137 | operator span() 138 | { 139 | return mView; 140 | } 141 | 142 | 143 | template 144 | typename std::enable_if< 145 | std::is_standard_layout::value&& 146 | std::is_trivial::value>::type setZero() 147 | { 148 | static_assert(std::is_same::value, ""); 149 | 150 | if (mView.size()) 151 | memset(mView.data(), 0, mView.size() * sizeof(T)); 152 | } 153 | 154 | protected: 155 | span mView; 156 | size_type mStride = 0; 157 | 158 | 159 | }; 160 | } 161 | 162 | -------------------------------------------------------------------------------- /cryptoTools/Common/Range.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "Defines.h" 4 | namespace osuCrypto 5 | { 6 | template 7 | class Increment 8 | { 9 | public: 10 | inline void operator()(T& v) const 11 | { 12 | v += step; 13 | } 14 | }; 15 | template 16 | class Deccrement 17 | { 18 | public: 19 | inline void operator()(T& v) const 20 | { 21 | v -= step; 22 | } 23 | }; 24 | 25 | template> 26 | class Range 27 | { 28 | public: 29 | 30 | struct Iterator 31 | { 32 | T mVal; 33 | Inc mInc; 34 | 35 | template 36 | Iterator(V&& v,I&&i) 37 | : mVal(std::forward(v)) 38 | , mInc(std::forward(i)) 39 | {} 40 | 41 | T operator*() const { return mVal; } 42 | 43 | Iterator& operator++() 44 | { 45 | mInc(mVal); 46 | return *this; 47 | } 48 | Iterator operator++(int) const 49 | { 50 | auto v = *this; 51 | mInc(v.mVal); 52 | return v; 53 | } 54 | 55 | bool operator==(const Iterator& v) const 56 | { 57 | return v.mVal == mVal; 58 | } 59 | 60 | bool operator!=(const Iterator& v) const 61 | { 62 | return v.mVal != mVal; 63 | } 64 | }; 65 | 66 | Iterator mBegin, mEnd; 67 | 68 | auto begin() const { return mBegin; } 69 | auto end() const { return mEnd; } 70 | 71 | template 72 | Range(B&& begin, E&& end, Inc&& step) 73 | : mBegin(std::forward(begin), step) 74 | , mEnd(std::forward(end), std::move(step)) 75 | {} 76 | }; 77 | 78 | 79 | 80 | template 81 | Range rng(B&& begin, E&& end, Inc&& inc) 82 | { 83 | return Range(std::forward(begin), std::forward(end), std::forward(inc)); 84 | } 85 | 86 | template 87 | Range rng(B&& begin, E&& end) 88 | { 89 | using Inc = Increment; 90 | return rng(std::forward(begin), std::forward(end), Inc{}); 91 | } 92 | 93 | template 94 | Range rng(V&& end) 95 | { 96 | return rng(0, std::forward(end)); 97 | } 98 | 99 | 100 | 101 | } -------------------------------------------------------------------------------- /cryptoTools/Common/TestCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | //#include 8 | 9 | //#define OSU_CRYPTO_PP_CAT(a, b) OSU_CRYPTO_PP_CAT_I(a, b) 10 | //#define OSU_CRYPTO_PP_CAT_I(a, b) OSU_CRYPTO_PP_CAT_II(~, a ## b) 11 | //#define OSU_CRYPTO_PP_CAT_II(p, res) res 12 | //#define OSU_CRYPTO_UNIQUE_NAME(base) OSU_CRYPTO_PP_CAT(base, __COUNTER__) 13 | // 14 | // 15 | #define OSU_CRYPTO_ADD_TEST(harness, test) 16 | //static int OSU_CRYPTO_UNIQUE_NAME(__add_test_) = []() { 17 | // harness.add(STRINGIZE(test), test); 18 | // return 0; 19 | //}(); 20 | 21 | namespace osuCrypto 22 | { 23 | class CLP; 24 | class TestCollection 25 | { 26 | public: 27 | struct Test 28 | { 29 | std::string mName; 30 | std::function mTest; 31 | }; 32 | TestCollection() = default; 33 | TestCollection(std::function init) 34 | { 35 | init(*this); 36 | } 37 | 38 | std::vector mTests; 39 | 40 | enum class Result 41 | { 42 | passed, 43 | skipped, 44 | failed 45 | }; 46 | 47 | Result runOne(u64 idx, CLP const * cmd = nullptr); 48 | Result run(std::vector testIdxs, u64 repeatCount = 1, CLP const * cmd = nullptr); 49 | Result runAll(uint64_t repeatCount = 1, CLP const * cmd = nullptr); 50 | Result runIf(CLP& cmd); 51 | void list(); 52 | 53 | std::vector search(const std::list& s); 54 | 55 | 56 | void add(std::string name, std::function test); 57 | void add(std::string name, std::function test); 58 | 59 | void operator+=(const TestCollection& add); 60 | }; 61 | 62 | 63 | class UnitTestFail : public std::exception 64 | { 65 | std::string mWhat; 66 | public: 67 | explicit UnitTestFail(std::string reason) 68 | :std::exception(), 69 | mWhat(reason) 70 | {} 71 | 72 | explicit UnitTestFail() 73 | :std::exception(), 74 | mWhat("UnitTestFailed exception") 75 | { 76 | } 77 | 78 | virtual const char* what() const throw() 79 | { 80 | return mWhat.c_str(); 81 | } 82 | }; 83 | 84 | class UnitTestSkipped : public std::runtime_error 85 | { 86 | public: 87 | UnitTestSkipped() 88 | : std::runtime_error("skipping test") 89 | {} 90 | 91 | UnitTestSkipped(std::string r) 92 | : std::runtime_error(r) 93 | {} 94 | }; 95 | 96 | extern TestCollection globalTests; 97 | } -------------------------------------------------------------------------------- /cryptoTools/Common/ThreadBarrier.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "cryptoTools/Common/Defines.h" 3 | #include 4 | #include 5 | 6 | namespace osuCrypto 7 | { 8 | 9 | class ThreadBarrier 10 | { 11 | std::promise mProm; 12 | std::shared_future mFuture; 13 | std::atomic mCount; 14 | public: 15 | ThreadBarrier(u64 count = 0) 16 | : mFuture(mProm.get_future()) 17 | , mCount(count) 18 | { 19 | } 20 | 21 | void decrementWait() 22 | { 23 | if (--mCount) 24 | { 25 | mFuture.get(); 26 | } 27 | else 28 | { 29 | mProm.set_value(); 30 | } 31 | } 32 | 33 | 34 | ThreadBarrier& operator--() 35 | { 36 | decrementWait(); 37 | return *this; 38 | } 39 | 40 | 41 | void reset(u64 count) 42 | { 43 | mCount = count; 44 | mProm = std::promise(); 45 | mFuture = mProm.get_future(); 46 | } 47 | 48 | }; 49 | } 50 | -------------------------------------------------------------------------------- /cryptoTools/Common/Timer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace osuCrypto 10 | { 11 | const Timer::timeUnit& Timer::setTimePoint(const std::string& msg) 12 | { 13 | if (mLocking) 14 | { 15 | std::lock_guard lock(mMtx); 16 | mTimes.push_back(std::make_pair(timeUnit::clock::now(), msg)); 17 | return mTimes.back().first; 18 | } 19 | else 20 | { 21 | mTimes.push_back(std::make_pair(timeUnit::clock::now(), msg)); 22 | return mTimes.back().first; 23 | 24 | } 25 | } 26 | 27 | void Timer::reset() 28 | { 29 | setTimePoint("__Begin__"); 30 | mTimes.clear(); 31 | } 32 | 33 | std::ostream& operator<<(std::ostream& out, const Timer& timer) 34 | { 35 | if (timer.mTimes.size() > 1) 36 | { 37 | u64 maxStars = 10; 38 | u64 p = 9; 39 | u64 width = 0; 40 | auto maxLog = 1.0; 41 | 42 | { 43 | auto prev = timer.mTimes.begin(); 44 | auto iter = timer.mTimes.begin(); ++iter; 45 | 46 | while (iter != timer.mTimes.end()) 47 | { 48 | width = std::max(width, iter->second.size()); 49 | auto diff = std::chrono::duration_cast(iter->first - prev->first).count() / 1000.0; 50 | maxLog = std::max(maxLog, std::log2(diff)); 51 | ++iter; 52 | ++prev; 53 | } 54 | } 55 | width += 3; 56 | 57 | 58 | out << std::left << std::setw(width) << "Label " << " " << std::setw(p) << "Time (ms)" << " " << std::setw(p) << "diff (ms)\n__________________________________" << std::endl; 59 | 60 | auto prev = timer.mTimes.begin(); 61 | auto iter = timer.mTimes.begin(); ++iter; 62 | 63 | while (iter != timer.mTimes.end()) 64 | { 65 | auto time = std::chrono::duration_cast(iter->first - timer.mTimes.front().first).count() / 1000.0; 66 | auto diff = std::chrono::duration_cast(iter->first - prev->first).count() / 1000.0; 67 | u64 numStars = static_cast(std::round(std::max(0.1, std::log2(diff)) * maxStars / maxLog)); 68 | 69 | out << std::setw(width) << std::left << iter->second 70 | << " " << std::right << std::fixed << std::setprecision(1) << std::setw(p) << time 71 | << " " << std::right << std::fixed << std::setprecision(3) << std::setw(p) << diff 72 | << " " << std::string(numStars, '*') << std::endl;; 73 | 74 | ++prev; 75 | ++iter; 76 | } 77 | } 78 | return out; 79 | } 80 | 81 | Timer gTimer(true); 82 | 83 | } 84 | -------------------------------------------------------------------------------- /cryptoTools/Common/Timer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | namespace osuCrypto 11 | { 12 | 13 | class Timer 14 | { 15 | public: 16 | 17 | typedef std::chrono::system_clock::time_point timeUnit; 18 | 19 | std::list> mTimes; 20 | bool mLocking; 21 | std::mutex mMtx; 22 | 23 | Timer(bool locking = false) 24 | :mLocking(locking) 25 | { 26 | reset(); 27 | } 28 | 29 | const timeUnit& setTimePoint(const std::string& msg); 30 | 31 | 32 | friend std::ostream& operator<<(std::ostream& out, const Timer& timer); 33 | 34 | void reset(); 35 | }; 36 | 37 | extern Timer gTimer; 38 | class TimerAdapter 39 | { 40 | public: 41 | void setTimer(Timer& timer) 42 | { 43 | mTimer = &timer; 44 | } 45 | 46 | Timer& getTimer() 47 | { 48 | if (mTimer) 49 | return *mTimer; 50 | 51 | throw std::runtime_error("Timer net set. "); 52 | } 53 | 54 | Timer::timeUnit setTimePoint(const std::string& msg) 55 | { 56 | if(mTimer) return getTimer().setTimePoint(msg); 57 | else return {}; 58 | } 59 | 60 | Timer::timeUnit setTimePoint(const char* msg) 61 | { 62 | if (mTimer) return getTimer().setTimePoint(msg); 63 | else return {}; 64 | } 65 | 66 | Timer* mTimer = nullptr; 67 | }; 68 | 69 | 70 | } 71 | -------------------------------------------------------------------------------- /cryptoTools/Common/Version.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | #define CRYPTO_TOOLS_VERSION_MAJOR 1 5 | #define CRYPTO_TOOLS_VERSION_MINOR 9 6 | #define CRYPTO_TOOLS_VERSION_PATCH 0 7 | 8 | 9 | #define CRYPTO_TOOLS_VERSION (CRYPTO_TOOLS_VERSION_MAJOR * 10000 + CRYPTO_TOOLS_VERSION_MINOR * 100 + CRYPTO_TOOLS_VERSION_PATCH) -------------------------------------------------------------------------------- /cryptoTools/Common/block.cpp: -------------------------------------------------------------------------------- 1 | #include "block.h" 2 | 3 | #include "Defines.h" 4 | #include 5 | #include "BitIterator.h" 6 | #include 7 | #include 8 | #include "cryptoTools/Crypto/AES.h" 9 | 10 | namespace osuCrypto 11 | { 12 | 13 | const block ZeroBlock = toBlock(0, 0); 14 | const block OneBlock = toBlock(0, 1); 15 | const block AllOneBlock = toBlock(u64(-1), u64(-1)); 16 | const std::array zeroAndAllOne = { { ZeroBlock, AllOneBlock } }; 17 | const block CCBlock = toBlock(0xcccccccccccccccc, 0xcccccccccccccccc); 18 | // ([]() {block cc; memset(&cc, 0xcc, sizeof(block)); return cc; })(); 19 | 20 | template 21 | void setBit(T& b, u64 idx) 22 | { 23 | *BitIterator((u8*)&b, idx) = 1; 24 | } 25 | 26 | std::array shiftMod(u64 s) 27 | { 28 | 29 | if (s > 127) 30 | throw RTE_LOC; 31 | 32 | static const constexpr std::array mod 33 | { 34 | 0, 1, 2, 7, 128 35 | }; 36 | //= 0b10000111; 37 | std::array mm{ ZeroBlock, ZeroBlock }; 38 | for (auto b : mod) 39 | { 40 | setBit(mm, b + s); 41 | 42 | } 43 | return mm; 44 | } 45 | 46 | namespace { 47 | 48 | template 49 | std::string bits(T x, u64 width = 99999999) 50 | { 51 | std::stringstream ss; 52 | BitIterator iter((u8*)&x, 0); 53 | for (u64 i = 0; i < sizeof(T) * 8; ++i) 54 | { 55 | if (i && (i % width == 0)) 56 | ss << " "; 57 | ss << *iter; 58 | 59 | ++iter; 60 | } 61 | return ss.str(); 62 | } 63 | } 64 | 65 | 66 | block block::cc_gf128Reduce(const block& x1) const 67 | { 68 | std::array x{ *this, x1 }; 69 | 70 | BitIterator iter((u8*)x.data(), 255); 71 | 72 | for (int i = 127; i >= 0; --i) 73 | { 74 | if (*iter) 75 | { 76 | //std::cout << " 1 " << std::endl; 77 | //auto xx = x; 78 | 79 | auto mod = shiftMod(i); 80 | x[0] = x[0] ^ mod[0]; 81 | x[1] = x[1] ^ mod[1]; 82 | 83 | //std::cout << " " << bits(xx, 128) << std::endl; 84 | //std::cout << " m" << bits(mod, 128) << std::endl; 85 | //std::cout << " =" << bits(x, 128) << std::endl; 86 | } 87 | 88 | --iter; 89 | } 90 | return x[0]; 91 | } 92 | 93 | } 94 | 95 | 96 | std::ostream& operator<<(std::ostream& out, const oc::block& blk) 97 | { 98 | using namespace oc; 99 | out << std::hex; 100 | u64* data = (u64*)&blk; 101 | 102 | out << std::setw(16) << std::setfill('0') << data[1] 103 | << std::setw(16) << std::setfill('0') << data[0]; 104 | 105 | out << std::dec << std::setw(0); 106 | return out; 107 | } 108 | 109 | 110 | namespace 111 | { 112 | oc::AES defaultBlockHasher(oc::block(4632453, 57432)); 113 | } 114 | 115 | std::size_t std::hash::operator()(const oc::block& k) const 116 | { 117 | auto h = defaultBlockHasher.ecbEncBlock(k) ^ k; 118 | return h.get()[0]; 119 | } -------------------------------------------------------------------------------- /cryptoTools/Common/config.h.in: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | // use the miracl library for curves 5 | #cmakedefine ENABLE_MIRACL @ENABLE_MIRACL@ 6 | 7 | // use the relic library for curves 8 | #cmakedefine ENABLE_RELIC @ENABLE_RELIC@ 9 | 10 | // use the libsodium library for curves 11 | #cmakedefine ENABLE_SODIUM @ENABLE_SODIUM@ 12 | 13 | // does the libsodium library support noclamp operations on Montgomery curves? 14 | #cmakedefine SODIUM_MONTGOMERY @SODIUM_MONTGOMERY@ 15 | 16 | // compile the circuit library 17 | #cmakedefine ENABLE_CIRCUITS @ENABLE_CIRCUITS@ 18 | 19 | // include the span-lite 20 | #cmakedefine ENABLE_SPAN_LITE @ENABLE_SPAN_LITE@ 21 | 22 | // defined if we should use cpp 14 and undefined means cpp 11 23 | #cmakedefine ENABLE_CPP_14 @ENABLE_CPP_14@ 24 | 25 | // Turn on Channel logging for debugging. 26 | #cmakedefine ENABLE_NET_LOG @ENABLE_NET_LOG@ 27 | 28 | 29 | // enable the wolf ssl socket layer. 30 | #cmakedefine ENABLE_WOLFSSL @ENABLE_WOLFSSL@ 31 | 32 | // enable integration with boost for networking. 33 | #cmakedefine ENABLE_BOOST @ENABLE_BOOST@ 34 | 35 | // enable the use of ARM AES instructions. 36 | #cmakedefine ENABLE_ARM_AES @ENABLE_ARM_AES@ 37 | 38 | // enable the use of intel SSE instructions. 39 | #cmakedefine ENABLE_SSE @ENABLE_SSE@ 40 | 41 | // enable the use of intel AVX instructions. 42 | #cmakedefine ENABLE_AVX @ENABLE_AVX@ 43 | 44 | // enable the use of the portable AES implementation. 45 | #cmakedefine ENABLE_PORTABLE_AES @ENABLE_PORTABLE_AES@ 46 | 47 | #if (defined(_MSC_VER) || defined(__SSE2__)) && defined(ENABLE_SSE) 48 | #define ENABLE_SSE_BLAKE2 ON 49 | #define OC_ENABLE_SSE2 ON 50 | #endif 51 | 52 | #if (defined(_MSC_VER) || defined(__PCLMUL__)) && defined(ENABLE_SSE) 53 | #define OC_ENABLE_PCLMUL 54 | #endif 55 | 56 | #if (defined(_MSC_VER) || defined(__AES__)) && defined(ENABLE_SSE) 57 | #define OC_ENABLE_AESNI ON 58 | #endif 59 | 60 | #if defined(ENABLE_PORTABLE_AES) 61 | #define OC_ENABLE_PORTABLE_AES ON 62 | #endif 63 | 64 | #if (defined(_MSC_VER) || defined(__AVX2__)) && defined(ENABLE_AVX) 65 | #define OC_ENABLE_AVX2 ON 66 | #endif 67 | 68 | 69 | 70 | 71 | 72 | #ifdef __CUDACC__ 73 | #define OC_CUDA_CALLABLE __host__ __device__ 74 | #define OC_CUDA_DEVICE __device__ 75 | #define OC_CUDA_HOST __host__ 76 | 77 | #ifdef OC_ENABLE_PCLMUL 78 | #undef OC_ENABLE_PCLMUL 79 | #endif 80 | #ifdef OC_ENABLE_SSE2 81 | #undef OC_ENABLE_SSE2 82 | #endif 83 | 84 | #ifdef ENABLE_SSE 85 | #undef ENABLE_SSE 86 | #endif 87 | #ifdef OC_ENABLE_SSE 88 | #undef OC_ENABLE_SSE 89 | #endif 90 | #ifdef ENABLE_AVX 91 | #undef ENABLE_AVX 92 | #endif 93 | #ifdef ENABLE_ARM_AES 94 | #undef ENABLE_ARM_AES 95 | #endif 96 | #if !defined(ENABLE_PORTABLE_AES) 97 | #define ENABLE_PORTABLE_AES 98 | #endif 99 | #else 100 | #define OC_CUDA_CALLABLE 101 | #define OC_CUDA_DEVICE 102 | #define OC_CUDA_HOST 103 | 104 | #endif 105 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/Blake2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace osuCrypto 4 | { 5 | const u64 Blake2::HashSize; 6 | const u64 Blake2::MaxHashSize; 7 | 8 | const Blake2& Blake2::operator=(const Blake2& src) 9 | { 10 | state = src.state; 11 | return *this; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/Blake2.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #include 5 | #ifdef ENABLE_SSE_BLAKE2 6 | #include 7 | #else 8 | #include 9 | #endif 10 | #include 11 | 12 | #include "Hashable.h" 13 | 14 | namespace osuCrypto { 15 | 16 | // An implementation of Blake 2 17 | class Blake2 18 | { 19 | public: 20 | // The default size of the blake digest output by Final(...); 21 | static const u64 HashSize = 20; 22 | 23 | // The maximum size of the blake digest output by Final(...); 24 | static const u64 MaxHashSize = BLAKE2B_OUTBYTES; 25 | 26 | // Default constructor of the class. Initializes the internal state. 27 | Blake2(u64 outputLength = HashSize) { Reset(outputLength); } 28 | 29 | // Resets the interal state. 30 | void Reset() 31 | { 32 | Reset(outputLength()); 33 | } 34 | 35 | // Resets the interal state. 36 | void Reset(u64 outputLength) 37 | { 38 | 39 | #ifdef TRUE_BLAKE2_INIT 40 | blake2b_init(&state, outputLength); 41 | #else 42 | const uint64_t blake2b_IV[8] = 43 | { 44 | 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 45 | 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 46 | 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 47 | 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL 48 | }; 49 | 50 | const unsigned char * v = (const unsigned char *)(blake2b_IV); 51 | std::memset(&state, 0, sizeof(blake2b_state)); 52 | state.outlen = outputLength; 53 | std::memcpy(state.h, v, BLAKE2B_OUTBYTES); 54 | #endif 55 | } 56 | 57 | // Add length bytes pointed to by dataIn to the internal Blake2 state. 58 | template 59 | typename std::enable_if< 60 | std::is_standard_layout::value&& 61 | std::is_trivial::value 62 | >::type Update(const T* dataIn, u64 length) 63 | { 64 | blake2b_update(&state, dataIn, length * sizeof(T)); 65 | } 66 | 67 | template 68 | typename std::enable_if::value>::type Update(const T& t) 69 | { 70 | Hashable::hash(t, *this); 71 | } 72 | 73 | // Finalize the Blake2 hash and output the result to DataOut. 74 | // Required: DataOut must be at least outputLength() bytes long. 75 | void Final(u8* DataOut) 76 | { 77 | blake2b_final(&state, DataOut, state.outlen); 78 | } 79 | 80 | // Finalize the Blake2 hash and output the result to out. 81 | // Only sizeof(T) bytes of the output are written. 82 | template 83 | typename std::enable_if< 84 | std::is_standard_layout::value&& 85 | std::is_trivial::value && 86 | sizeof(T) <= MaxHashSize && 87 | std::is_pointer::value == false 88 | >::type 89 | Final(T& out) 90 | { 91 | if (sizeof(T) != outputLength()) 92 | throw std::runtime_error(LOCATION); 93 | Final((u8*)&out); 94 | } 95 | 96 | // Copy the interal state of a Blake2 computation. 97 | const Blake2& operator=(const Blake2& src); 98 | 99 | // returns the number of bytes that will be written when Final(...) is called. 100 | u64 outputLength() const 101 | { 102 | return state.outlen; 103 | } 104 | private: 105 | blake2b_state state; 106 | }; 107 | } 108 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/Commit.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace osuCrypto { 10 | 11 | #define COMMIT_BUFF_u32_SIZE 5 12 | static_assert(RandomOracle::HashSize == sizeof(u32) * COMMIT_BUFF_u32_SIZE, "buffer need to be the same size as hash size"); 13 | 14 | 15 | class Commit 16 | { 17 | public: 18 | 19 | // Default constructor of a Commitment. The state is undefined. 20 | Commit() = default; 21 | 22 | // Compute a randomized commitment of input. 23 | Commit(const block& in, PRNG& prng) 24 | { 25 | block rand = prng.get(); 26 | hash((u8*)(&in), sizeof(block), rand); 27 | } 28 | 29 | // Compute a randomized commitment of input. 30 | Commit(const block& in, block& rand) 31 | { 32 | hash((u8*)(&in), sizeof(block), rand); 33 | } 34 | 35 | // Compute a randomized commitment of input. 36 | Commit(const span in, PRNG& prng) 37 | { 38 | block rand = prng.get(); 39 | hash(in.data(), in.size(), rand); 40 | } 41 | 42 | // Compute a randomized commitment of input. 43 | Commit(const span in, block& rand) 44 | { 45 | hash(in.data(), in.size(), rand); 46 | } 47 | 48 | 49 | 50 | // Compute a non-randomized commitment of input. 51 | // Note: insecure if input has low entropy. 52 | Commit(const block& input) { hash((u8*)(&input), sizeof(block)); } 53 | 54 | // Compute a non-randomized commitment of input. 55 | // Note: insecure if input has low entropy. 56 | Commit(const std::array& input) 57 | { 58 | hash((u8*)(&input[0]), sizeof(block)); 59 | hash((u8*)(&input[1]), sizeof(block)); 60 | hash((u8*)(&input[2]), sizeof(block)); 61 | } 62 | 63 | // Compute a non-randomized commitment of input. 64 | // Note: insecure if input has low entropy. 65 | Commit(const span in) 66 | { 67 | hash(in.data(), in.size()); 68 | } 69 | 70 | 71 | // Compute a non-randomized commitment of input. 72 | // Note: insecure if input has low entropy. 73 | Commit(u8* d, u64 s) 74 | { 75 | hash(d, s); 76 | } 77 | 78 | // Utility function to test if two commitments are equal. 79 | bool operator==(const Commit& rhs) const 80 | { 81 | for (u64 i = 0; i < COMMIT_BUFF_u32_SIZE; ++i) 82 | { 83 | if (buff[i] != rhs.buff[i]) 84 | return false; 85 | } 86 | return true; 87 | } 88 | 89 | // Utility function to test if two commitments are not equal. 90 | bool operator!=(const Commit& rhs) const 91 | { 92 | return !(*this == rhs); 93 | } 94 | 95 | // Returns a pointer to the commitment value. 96 | u8* data() const 97 | { 98 | return (u8*)buff; 99 | } 100 | 101 | // Returns the size of the commitment in bytes. 102 | static u64 size() 103 | { 104 | return RandomOracle::HashSize; 105 | } 106 | 107 | private: 108 | u32 buff[COMMIT_BUFF_u32_SIZE]; 109 | 110 | void hash(u8* data, u64 size) 111 | { 112 | RandomOracle sha; 113 | sha.Update(data, size); 114 | sha.Final((u8*)buff); 115 | } 116 | 117 | void hash(u8* data, u64 size, block& rand) 118 | { 119 | RandomOracle sha; 120 | sha.Update(data, size); 121 | sha.Update(rand); 122 | sha.Final((u8*)buff); 123 | } 124 | 125 | }; 126 | 127 | static_assert(sizeof(Commit) == RandomOracle::HashSize, "needs to be Pod type"); 128 | 129 | 130 | //std::ostream& operator<<(std::ostream& out, const Commit& comm); 131 | } 132 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/Hashable.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #include 5 | #include 6 | 7 | namespace osuCrypto { 8 | // Specializations of Hashable should inherit from std::true_type and contain: 9 | // 10 | // template 11 | // static void hash(const T& t, Hasher& mHasher); 12 | // 13 | // Hasher will contain an Update method that can be applied to byte arrays and to Hashable 14 | // types. 15 | template 16 | struct Hashable : std::false_type {}; 17 | 18 | template 19 | struct Hashable::value&& 22 | std::is_trivial::value>::type 23 | > : std::true_type 24 | { 25 | template 26 | static void hash(const T& t, Hasher& hasher) 27 | { 28 | hasher.Update((u8*) &t, sizeof(T)); 29 | } 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/PRNG.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | namespace osuCrypto { 7 | 8 | PRNG::PRNG(const block& seed, u64 bufferSize) 9 | : 10 | mBytesIdx(0), 11 | mBlockIdx(0) 12 | { 13 | SetSeed(seed, bufferSize); 14 | } 15 | 16 | PRNG::PRNG(PRNG && s) : 17 | mBuffer(std::move(s.mBuffer)), 18 | mAes(std::move(s.mAes)), 19 | mBytesIdx(s.mBytesIdx), 20 | mBlockIdx(s.mBlockIdx), 21 | mBufferByteCapacity(s.mBufferByteCapacity) 22 | { 23 | s.mBuffer.resize(0); 24 | s.mBytesIdx = 0; 25 | s.mBlockIdx = 0; 26 | s.mBufferByteCapacity = 0; 27 | } 28 | 29 | void PRNG::operator=(PRNG&&s) 30 | { 31 | mBuffer = (std::move(s.mBuffer)); 32 | mAes = (std::move(s.mAes)); 33 | mBytesIdx = (s.mBytesIdx); 34 | mBlockIdx = (s.mBlockIdx); 35 | mBufferByteCapacity = (s.mBufferByteCapacity); 36 | 37 | s.mBuffer.resize(0); 38 | s.mBytesIdx = 0; 39 | s.mBlockIdx = 0; 40 | s.mBufferByteCapacity = 0; 41 | } 42 | 43 | 44 | void PRNG::SetSeed(const block& seed, u64 bufferSize) 45 | { 46 | mAes.setKey(seed); 47 | mBlockIdx = 0; 48 | 49 | if (mBuffer.size() == 0) 50 | { 51 | mBuffer.resize(bufferSize); 52 | mBufferByteCapacity = (sizeof(block) * bufferSize); 53 | } 54 | 55 | 56 | refillBuffer(); 57 | } 58 | 59 | void PRNG::implGet(u8* destu8, u64 lengthu8) 60 | { 61 | while (lengthu8) 62 | { 63 | u64 step = std::min(lengthu8, mBufferByteCapacity - mBytesIdx); 64 | 65 | memcpy(destu8, ((u8*)mBuffer.data()) + mBytesIdx, step); 66 | 67 | destu8 += step; 68 | lengthu8 -= step; 69 | mBytesIdx += step; 70 | 71 | if (mBytesIdx == mBufferByteCapacity) 72 | { 73 | while (lengthu8 >= 8 * sizeof(block)) 74 | { 75 | oc::AlignedArray b; 76 | mAes.ecbEncCounterMode(mBlockIdx, b.size(), b.data()); 77 | memcpy(destu8, &b, sizeof(b)); 78 | mBlockIdx += b.size(); 79 | 80 | step = sizeof(b); 81 | 82 | destu8 += step; 83 | lengthu8 -= step; 84 | } 85 | 86 | refillBuffer(); 87 | } 88 | } 89 | } 90 | 91 | u8 PRNG::getBit() { return get(); } 92 | 93 | const block PRNG::getSeed() const 94 | { 95 | if(mBuffer.size()) 96 | return mAes.mRoundKey[0]; 97 | 98 | throw std::runtime_error("PRNG has not been keyed " LOCATION); 99 | } 100 | 101 | void PRNG::refillBuffer() 102 | { 103 | if (mBuffer.size() == 0) 104 | throw std::runtime_error("PRNG has not been keyed " LOCATION); 105 | 106 | mAes.ecbEncCounterMode(mBlockIdx, mBuffer.size(), mBuffer.data()); 107 | mBlockIdx += mBuffer.size(); 108 | mBytesIdx = 0; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/RandomOracle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | namespace osuCrypto 5 | { 6 | using RandomOracle = Blake2; 7 | } -------------------------------------------------------------------------------- /cryptoTools/Crypto/Rijndael256.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | 5 | namespace osuCrypto { 6 | namespace details 7 | { 8 | static const int rijndael256_rounds = 14; 9 | } 10 | 11 | struct Block256 : public std::array 12 | { 13 | private: 14 | using Base = std::array; 15 | 16 | public: 17 | Block256() = default; 18 | using Base::Base; 19 | using Base::operator=; 20 | 21 | Block256(block b0, block b1) : Base({ b0, b1 }) {} 22 | Block256(const std::uint8_t* data) : Base({ toBlock(data), toBlock(data + 16) }) {} 23 | Block256(std::uint64_t low_u64) : Base({ toBlock(low_u64), toBlock((std::uint64_t)0) }) {} 24 | 25 | const unsigned char* data() const 26 | { 27 | // Unsafe, but I don't see a better way. 28 | return (const unsigned char*)&(*this)[0]; 29 | } 30 | 31 | unsigned char* data() 32 | { 33 | return (unsigned char*)&(*this)[0]; 34 | } 35 | }; 36 | 37 | 38 | #ifdef OC_ENABLE_AESNI 39 | 40 | 41 | class Rijndael256Enc 42 | { 43 | public: 44 | using Block = Block256; 45 | static const int rounds = details::rijndael256_rounds; 46 | std::array mRoundKey; 47 | 48 | // Default constructor leaves the class in an invalid state 49 | // until setKey(...) is called. 50 | Rijndael256Enc() = default; 51 | Rijndael256Enc(const Rijndael256Enc&) = default; 52 | 53 | // Constructor to initialize the class with the given key 54 | Rijndael256Enc(const Block& userKey) 55 | { 56 | setKey(userKey); 57 | } 58 | 59 | // Set the key to be used for encryption. 60 | void setKey(const Block& userKey); 61 | 62 | void encBlock(const Block& plaintext, Block& ciphertext) const 63 | { 64 | encBlocksFixed<1>(&plaintext, &ciphertext); 65 | } 66 | 67 | Block encBlock(const Block& plaintext) const 68 | { 69 | Block ciphertext; 70 | encBlock(plaintext, ciphertext); 71 | return ciphertext; 72 | } 73 | 74 | // Instantiated only for {1, 2, 3, 4} blocks. 75 | template 76 | void encBlocksFixed(const Block* plaintext, Block* ciphertext) const; 77 | template 78 | void encBlocksFixed(const Block (&plaintext)[blocks], Block (&ciphertext)[blocks]) const 79 | { 80 | encBlocksFixed(&plaintext[0], &ciphertext[0]); 81 | } 82 | 83 | void encBlocks(const Block* plaintexts, size_t blocks, Block* ciphertext) const; 84 | 85 | static Block roundEnc(Block state, const Block& roundKey); 86 | static Block finalEnc(Block state, const Block& roundKey); 87 | }; 88 | 89 | class Rijndael256Dec 90 | { 91 | public: 92 | using Block = Block256; 93 | static const int rounds = details::rijndael256_rounds; 94 | std::array mRoundKey; 95 | 96 | Rijndael256Dec() = default; 97 | Rijndael256Dec(const Rijndael256Dec&) = default; 98 | 99 | Rijndael256Dec(const Rijndael256Enc& enc) 100 | { 101 | setKey(enc); 102 | } 103 | 104 | Rijndael256Dec(const Block& userKey) 105 | { 106 | setKey(userKey); 107 | } 108 | 109 | void setKey(const Block& userKey) 110 | { 111 | setKey(Rijndael256Enc(userKey)); 112 | } 113 | 114 | void setKey(const Rijndael256Enc& enc); 115 | 116 | void decBlock(const Block& ciphertext, Block& plaintext) const 117 | { 118 | decBlocksFixed<1>(&ciphertext, &plaintext); 119 | } 120 | 121 | Block decBlock(const Block& ciphertext) const 122 | { 123 | Block plaintext; 124 | decBlock(ciphertext, plaintext); 125 | return plaintext; 126 | } 127 | 128 | // Instantiated only for {1, 2, 3, 4} blocks. 129 | template 130 | void decBlocksFixed(const Block* ciphertext, Block* plaintext) const; 131 | template 132 | void decBlocksFixed(const Block (&ciphertext)[blocks], Block (&plaintext)[blocks]) const 133 | { 134 | decBlocksFixed(*ciphertext[0], &plaintext[0]); 135 | } 136 | 137 | void decBlocks(const Block* ciphertexts, size_t blocks, Block* plaintext) const; 138 | 139 | static Block roundDec(Block state, const Block& roundKey); 140 | static Block finalDec(Block state, const Block& roundKey); 141 | }; 142 | 143 | // TODO: encryption of N values under N different keys 144 | #endif 145 | } 146 | 147 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/SodiumCurve.cpp: -------------------------------------------------------------------------------- 1 | #include "SodiumCurve.h" 2 | 3 | #ifdef ENABLE_SODIUM 4 | 5 | namespace osuCrypto 6 | { 7 | namespace Sodium 8 | { 9 | 10 | bool Scalar25519::operator==(const Scalar25519& cmp) const 11 | { 12 | return sodium_memcmp(data, cmp.data, size) == 0; 13 | } 14 | 15 | bool Scalar25519::iszero() const 16 | { 17 | return sodium_is_zero(data, size); 18 | } 19 | 20 | Prime25519::Prime25519(const Scalar25519& a) 21 | { 22 | crypto_core_ed25519_scalar_reduce(data, a.data); 23 | } 24 | 25 | Prime25519 Prime25519::inverse() const 26 | { 27 | Prime25519 recip; 28 | crypto_core_ed25519_scalar_invert(recip.data, data); 29 | return recip; 30 | } 31 | 32 | Prime25519 operator-(const Prime25519& a) 33 | { 34 | Prime25519 neg; 35 | crypto_core_ed25519_scalar_negate(neg.data, a.data); 36 | return neg; 37 | } 38 | 39 | Prime25519 operator+(const Prime25519& a, const Prime25519& b) 40 | { 41 | Prime25519 sum; 42 | crypto_core_ed25519_scalar_add(sum.data, a.data, b.data); 43 | return sum; 44 | } 45 | 46 | Prime25519 operator-(const Prime25519& a, const Prime25519& b) 47 | { 48 | Prime25519 diff; 49 | crypto_core_ed25519_scalar_sub(diff.data, a.data, b.data); 50 | return diff; 51 | } 52 | 53 | Prime25519 operator*(const Prime25519& a, const Prime25519& b) 54 | { 55 | Prime25519 prod; 56 | crypto_core_ed25519_scalar_mul(prod.data, a.data, b.data); 57 | return prod; 58 | } 59 | 60 | bool Ed25519::operator==(const Ed25519& cmp) const 61 | { 62 | return sodium_memcmp(data, cmp.data, size) == 0; 63 | } 64 | 65 | Ed25519 Ed25519::operator+(const Ed25519& b) const 66 | { 67 | Ed25519 sum; 68 | crypto_core_ed25519_add(sum.data, data, b.data); 69 | return sum; 70 | } 71 | 72 | Ed25519 Ed25519::operator-(const Ed25519& b) const 73 | { 74 | Ed25519 diff; 75 | crypto_core_ed25519_sub(diff.data, data, b.data); 76 | return diff; 77 | } 78 | 79 | Ed25519 operator*(const Prime25519& a, const Ed25519& b) 80 | { 81 | Ed25519 prod; 82 | if (crypto_scalarmult_ed25519_noclamp(prod.data, a.data, b.data) < 0) 83 | throw std::runtime_error(LOCATION); 84 | return prod; 85 | } 86 | 87 | Ed25519 Ed25519::mulGenerator(const Prime25519& n) 88 | { 89 | Ed25519 prod; 90 | if (crypto_scalarmult_ed25519_base_noclamp(prod.data, n.data) < 0) 91 | throw std::runtime_error(LOCATION); 92 | return prod; 93 | } 94 | 95 | bool Rist25519::operator==(const Rist25519& cmp) const 96 | { 97 | return sodium_memcmp(data, cmp.data, size) == 0; 98 | } 99 | 100 | Rist25519 Rist25519::operator+(const Rist25519& b) const 101 | { 102 | Rist25519 sum; 103 | crypto_core_ristretto255_add(sum.data, data, b.data); 104 | return sum; 105 | } 106 | 107 | Rist25519 Rist25519::operator-(const Rist25519& b) const 108 | { 109 | Rist25519 diff; 110 | crypto_core_ristretto255_sub(diff.data, data, b.data); 111 | return diff; 112 | } 113 | 114 | Rist25519 operator*(const Prime25519& a, const Rist25519& b) 115 | { 116 | Rist25519 prod; 117 | if (crypto_scalarmult_ristretto255(prod.data, a.data, b.data) < 0) 118 | throw std::runtime_error(LOCATION); 119 | return prod; 120 | } 121 | 122 | Rist25519 Rist25519::mulGenerator(const Prime25519& n) 123 | { 124 | Rist25519 prod; 125 | if (crypto_scalarmult_ristretto255_base(prod.data, n.data) < 0) 126 | throw std::runtime_error(LOCATION); 127 | return prod; 128 | } 129 | 130 | Rist25519 Rist25519::fromHash(const unsigned char* d) 131 | { 132 | Rist25519 out; 133 | crypto_core_ristretto255_from_hash(out.data, d); 134 | return out; 135 | } 136 | 137 | #ifdef SODIUM_MONTGOMERY 138 | 139 | bool Monty25519::operator==(const Monty25519& cmp) const 140 | { 141 | return sodium_memcmp(data, cmp.data, size) == 0; 142 | } 143 | 144 | Monty25519 operator*(const Scalar25519& a, const Monty25519& b) 145 | { 146 | Monty25519 prod; 147 | if (crypto_scalarmult_noclamp(prod.data, a.data, b.data) < 0) 148 | throw std::runtime_error(LOCATION); 149 | return prod; 150 | } 151 | 152 | Monty25519 Monty25519::mulGenerator(const Scalar25519& n) 153 | { 154 | Monty25519 prod; 155 | if (crypto_scalarmult_base_noclamp(prod.data, n.data) < 0) 156 | throw std::runtime_error(LOCATION); 157 | return prod; 158 | } 159 | 160 | const Monty25519 Monty25519::primeSubgroupGenerator{9}; 161 | const Monty25519 Monty25519::primeTwistSubgroupGenerator{2}; 162 | const Monty25519 Monty25519::wholeGroupGenerator{6}; 163 | const Monty25519 Monty25519::wholeTwistGroupGenerator{3}; 164 | 165 | #endif 166 | 167 | } 168 | } 169 | 170 | #endif 171 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/c/blake2-impl.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - reference C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #include "cryptoTools/Common/config.h" 16 | 17 | #ifndef ENABLE_SSE_BLAKE2 18 | 19 | #ifndef BLAKE2_IMPL_H 20 | #define BLAKE2_IMPL_H 21 | 22 | #include 23 | #include 24 | 25 | #if !defined(__cplusplus) && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) 26 | #if defined(_MSC_VER) 27 | #define BLAKE2_INLINE __inline 28 | #elif defined(__GNUC__) 29 | #define BLAKE2_INLINE __inline__ 30 | #else 31 | #define BLAKE2_INLINE 32 | #endif 33 | #else 34 | #define BLAKE2_INLINE inline 35 | #endif 36 | 37 | namespace osuCrypto 38 | { 39 | 40 | static BLAKE2_INLINE uint32_t load32(const void* src) 41 | { 42 | #if defined(NATIVE_LITTLE_ENDIAN) 43 | uint32_t w; 44 | memcpy(&w, src, sizeof w); 45 | return w; 46 | #else 47 | const uint8_t* p = (const uint8_t*)src; 48 | return ((uint32_t)(p[0]) << 0) | 49 | ((uint32_t)(p[1]) << 8) | 50 | ((uint32_t)(p[2]) << 16) | 51 | ((uint32_t)(p[3]) << 24); 52 | #endif 53 | } 54 | 55 | static BLAKE2_INLINE uint64_t load64(const void* src) 56 | { 57 | #if defined(NATIVE_LITTLE_ENDIAN) 58 | uint64_t w; 59 | memcpy(&w, src, sizeof w); 60 | return w; 61 | #else 62 | const uint8_t* p = (const uint8_t*)src; 63 | return ((uint64_t)(p[0]) << 0) | 64 | ((uint64_t)(p[1]) << 8) | 65 | ((uint64_t)(p[2]) << 16) | 66 | ((uint64_t)(p[3]) << 24) | 67 | ((uint64_t)(p[4]) << 32) | 68 | ((uint64_t)(p[5]) << 40) | 69 | ((uint64_t)(p[6]) << 48) | 70 | ((uint64_t)(p[7]) << 56); 71 | #endif 72 | } 73 | 74 | static BLAKE2_INLINE uint16_t load16(const void* src) 75 | { 76 | #if defined(NATIVE_LITTLE_ENDIAN) 77 | uint16_t w; 78 | memcpy(&w, src, sizeof w); 79 | return w; 80 | #else 81 | const uint8_t* p = (const uint8_t*)src; 82 | return (uint16_t)(((uint32_t)(p[0]) << 0) | 83 | ((uint32_t)(p[1]) << 8)); 84 | #endif 85 | } 86 | 87 | static BLAKE2_INLINE void store16(void* dst, uint16_t w) 88 | { 89 | #if defined(NATIVE_LITTLE_ENDIAN) 90 | memcpy(dst, &w, sizeof w); 91 | #else 92 | uint8_t* p = (uint8_t*)dst; 93 | *p++ = (uint8_t)w; w >>= 8; 94 | *p++ = (uint8_t)w; 95 | #endif 96 | } 97 | 98 | static BLAKE2_INLINE void store32(void* dst, uint32_t w) 99 | { 100 | #if defined(NATIVE_LITTLE_ENDIAN) 101 | memcpy(dst, &w, sizeof w); 102 | #else 103 | uint8_t* p = (uint8_t*)dst; 104 | p[0] = (uint8_t)(w >> 0); 105 | p[1] = (uint8_t)(w >> 8); 106 | p[2] = (uint8_t)(w >> 16); 107 | p[3] = (uint8_t)(w >> 24); 108 | #endif 109 | } 110 | 111 | static BLAKE2_INLINE void store64(void* dst, uint64_t w) 112 | { 113 | #if defined(NATIVE_LITTLE_ENDIAN) 114 | memcpy(dst, &w, sizeof w); 115 | #else 116 | uint8_t* p = (uint8_t*)dst; 117 | p[0] = (uint8_t)(w >> 0); 118 | p[1] = (uint8_t)(w >> 8); 119 | p[2] = (uint8_t)(w >> 16); 120 | p[3] = (uint8_t)(w >> 24); 121 | p[4] = (uint8_t)(w >> 32); 122 | p[5] = (uint8_t)(w >> 40); 123 | p[6] = (uint8_t)(w >> 48); 124 | p[7] = (uint8_t)(w >> 56); 125 | #endif 126 | } 127 | 128 | static BLAKE2_INLINE uint64_t load48(const void* src) 129 | { 130 | const uint8_t* p = (const uint8_t*)src; 131 | return ((uint64_t)(p[0]) << 0) | 132 | ((uint64_t)(p[1]) << 8) | 133 | ((uint64_t)(p[2]) << 16) | 134 | ((uint64_t)(p[3]) << 24) | 135 | ((uint64_t)(p[4]) << 32) | 136 | ((uint64_t)(p[5]) << 40); 137 | } 138 | 139 | static BLAKE2_INLINE void store48(void* dst, uint64_t w) 140 | { 141 | uint8_t* p = (uint8_t*)dst; 142 | p[0] = (uint8_t)(w >> 0); 143 | p[1] = (uint8_t)(w >> 8); 144 | p[2] = (uint8_t)(w >> 16); 145 | p[3] = (uint8_t)(w >> 24); 146 | p[4] = (uint8_t)(w >> 32); 147 | p[5] = (uint8_t)(w >> 40); 148 | } 149 | 150 | static BLAKE2_INLINE uint32_t rotr32(const uint32_t w, const unsigned c) 151 | { 152 | return (w >> c) | (w << (32 - c)); 153 | } 154 | 155 | static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) 156 | { 157 | return (w >> c) | (w << (64 - c)); 158 | } 159 | 160 | /* prevents compiler optimizing out memset() */ 161 | static BLAKE2_INLINE void secure_zero_memory(void* v, size_t n) 162 | { 163 | static void* (* const volatile memset_v)(void*, int, size_t) = &memset; 164 | memset_v(v, 0, n); 165 | } 166 | } 167 | 168 | #endif 169 | #endif 170 | 171 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/sse/blake2-config.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - optimized C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #include "cryptoTools/Common/config.h" 16 | #ifdef ENABLE_SSE_BLAKE2 17 | 18 | #ifndef BLAKE2_CONFIG_H 19 | #define BLAKE2_CONFIG_H 20 | 21 | 22 | /* These don't work everywhere */ 23 | #define HAVE_SSE2 24 | 25 | #ifdef ENABLE_AVX 26 | #define HAVE_SSSE3 27 | #define HAVE_SSE41 28 | #define HAVE_AVX 29 | #endif 30 | 31 | 32 | #ifdef HAVE_AVX2 33 | #ifndef HAVE_AVX 34 | #define HAVE_AVX 35 | #endif 36 | #endif 37 | 38 | #ifdef HAVE_XOP 39 | #ifndef HAVE_AVX 40 | #define HAVE_AVX 41 | #endif 42 | #endif 43 | 44 | #ifdef HAVE_AVX 45 | #ifndef HAVE_SSE41 46 | #define HAVE_SSE41 47 | #endif 48 | #endif 49 | 50 | #ifdef HAVE_SSE41 51 | #ifndef HAVE_SSSE3 52 | #define HAVE_SSSE3 53 | #endif 54 | #endif 55 | 56 | #ifdef HAVE_SSSE3 57 | #define HAVE_SSE2 58 | #endif 59 | 60 | #if !defined(HAVE_SSE2) 61 | #error "This code requires at least SSE2." 62 | #endif 63 | 64 | #endif 65 | #endif 66 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/sse/blake2-impl.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - reference C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #ifndef BLAKE2_IMPL_H 16 | #define BLAKE2_IMPL_H 17 | 18 | #include "cryptoTools/Common/config.h" 19 | #ifdef ENABLE_SSE_BLAKE2 20 | 21 | 22 | #include 23 | #include 24 | 25 | #if !defined(__cplusplus) && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) 26 | #if defined(_MSC_VER) 27 | #define BLAKE2_INLINE __inline 28 | #elif defined(__GNUC__) 29 | #define BLAKE2_INLINE __inline__ 30 | #else 31 | #define BLAKE2_INLINE 32 | #endif 33 | #else 34 | #define BLAKE2_INLINE inline 35 | #endif 36 | 37 | namespace osuCrypto 38 | { 39 | 40 | 41 | static BLAKE2_INLINE uint32_t load32(const void* src) 42 | { 43 | #if defined(NATIVE_LITTLE_ENDIAN) 44 | uint32_t w; 45 | memcpy(&w, src, sizeof w); 46 | return w; 47 | #else 48 | const uint8_t* p = (const uint8_t*)src; 49 | return ((uint32_t)(p[0]) << 0) | 50 | ((uint32_t)(p[1]) << 8) | 51 | ((uint32_t)(p[2]) << 16) | 52 | ((uint32_t)(p[3]) << 24); 53 | #endif 54 | } 55 | 56 | static BLAKE2_INLINE uint64_t load64(const void* src) 57 | { 58 | #if defined(NATIVE_LITTLE_ENDIAN) 59 | uint64_t w; 60 | memcpy(&w, src, sizeof w); 61 | return w; 62 | #else 63 | const uint8_t* p = (const uint8_t*)src; 64 | return ((uint64_t)(p[0]) << 0) | 65 | ((uint64_t)(p[1]) << 8) | 66 | ((uint64_t)(p[2]) << 16) | 67 | ((uint64_t)(p[3]) << 24) | 68 | ((uint64_t)(p[4]) << 32) | 69 | ((uint64_t)(p[5]) << 40) | 70 | ((uint64_t)(p[6]) << 48) | 71 | ((uint64_t)(p[7]) << 56); 72 | #endif 73 | } 74 | 75 | static BLAKE2_INLINE uint16_t load16(const void* src) 76 | { 77 | #if defined(NATIVE_LITTLE_ENDIAN) 78 | uint16_t w; 79 | memcpy(&w, src, sizeof w); 80 | return w; 81 | #else 82 | const uint8_t* p = (const uint8_t*)src; 83 | return ((uint16_t)(p[0]) << 0) | 84 | ((uint16_t)(p[1]) << 8); 85 | #endif 86 | } 87 | 88 | static BLAKE2_INLINE void store16(void* dst, uint16_t w) 89 | { 90 | #if defined(NATIVE_LITTLE_ENDIAN) 91 | memcpy(dst, &w, sizeof w); 92 | #else 93 | uint8_t* p = (uint8_t*)dst; 94 | *p++ = (uint8_t)w; w >>= 8; 95 | *p++ = (uint8_t)w; 96 | #endif 97 | } 98 | 99 | static BLAKE2_INLINE void store32(void* dst, uint32_t w) 100 | { 101 | #if defined(NATIVE_LITTLE_ENDIAN) 102 | memcpy(dst, &w, sizeof w); 103 | #else 104 | uint8_t* p = (uint8_t*)dst; 105 | p[0] = (uint8_t)(w >> 0); 106 | p[1] = (uint8_t)(w >> 8); 107 | p[2] = (uint8_t)(w >> 16); 108 | p[3] = (uint8_t)(w >> 24); 109 | #endif 110 | } 111 | 112 | static BLAKE2_INLINE void store64(void* dst, uint64_t w) 113 | { 114 | #if defined(NATIVE_LITTLE_ENDIAN) 115 | memcpy(dst, &w, sizeof w); 116 | #else 117 | uint8_t* p = (uint8_t*)dst; 118 | p[0] = (uint8_t)(w >> 0); 119 | p[1] = (uint8_t)(w >> 8); 120 | p[2] = (uint8_t)(w >> 16); 121 | p[3] = (uint8_t)(w >> 24); 122 | p[4] = (uint8_t)(w >> 32); 123 | p[5] = (uint8_t)(w >> 40); 124 | p[6] = (uint8_t)(w >> 48); 125 | p[7] = (uint8_t)(w >> 56); 126 | #endif 127 | } 128 | 129 | static BLAKE2_INLINE uint64_t load48(const void* src) 130 | { 131 | const uint8_t* p = (const uint8_t*)src; 132 | return ((uint64_t)(p[0]) << 0) | 133 | ((uint64_t)(p[1]) << 8) | 134 | ((uint64_t)(p[2]) << 16) | 135 | ((uint64_t)(p[3]) << 24) | 136 | ((uint64_t)(p[4]) << 32) | 137 | ((uint64_t)(p[5]) << 40); 138 | } 139 | 140 | static BLAKE2_INLINE void store48(void* dst, uint64_t w) 141 | { 142 | uint8_t* p = (uint8_t*)dst; 143 | p[0] = (uint8_t)(w >> 0); 144 | p[1] = (uint8_t)(w >> 8); 145 | p[2] = (uint8_t)(w >> 16); 146 | p[3] = (uint8_t)(w >> 24); 147 | p[4] = (uint8_t)(w >> 32); 148 | p[5] = (uint8_t)(w >> 40); 149 | } 150 | 151 | static BLAKE2_INLINE uint32_t rotr32(const uint32_t w, const unsigned c) 152 | { 153 | return (w >> c) | (w << (32 - c)); 154 | } 155 | 156 | static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) 157 | { 158 | return (w >> c) | (w << (64 - c)); 159 | } 160 | 161 | /* prevents compiler optimizing out memset() */ 162 | static BLAKE2_INLINE void secure_zero_memory(void* v, size_t n) 163 | { 164 | static void* (* const volatile memset_v)(void*, int, size_t) = &memset; 165 | memset_v(v, 0, n); 166 | } 167 | 168 | } 169 | #endif 170 | #endif 171 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/sse/blake2.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - reference C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #include "cryptoTools/Common/config.h" 16 | #ifdef ENABLE_SSE_BLAKE2 17 | 18 | #ifndef BLAKE2_H 19 | #define BLAKE2_H 20 | 21 | #include 22 | #include 23 | 24 | #if defined(_MSC_VER) 25 | #define BLAKE2_PACKED(x) __pragma(pack(push, 1)) x __pragma(pack(pop)) 26 | #else 27 | #define BLAKE2_PACKED(x) x __attribute__((packed)) 28 | #endif 29 | 30 | namespace osuCrypto 31 | { 32 | enum blake2s_constant 33 | { 34 | BLAKE2S_BLOCKBYTES = 64, 35 | BLAKE2S_OUTBYTES = 32, 36 | BLAKE2S_KEYBYTES = 32, 37 | BLAKE2S_SALTBYTES = 8, 38 | BLAKE2S_PERSONALBYTES = 8 39 | }; 40 | 41 | enum blake2b_constant 42 | { 43 | BLAKE2B_BLOCKBYTES = 128, 44 | BLAKE2B_OUTBYTES = 64, 45 | BLAKE2B_KEYBYTES = 64, 46 | BLAKE2B_SALTBYTES = 16, 47 | BLAKE2B_PERSONALBYTES = 16 48 | }; 49 | 50 | typedef struct blake2s_state__ 51 | { 52 | uint32_t h[8]; 53 | uint32_t t[2]; 54 | uint32_t f[2]; 55 | uint8_t buf[BLAKE2S_BLOCKBYTES]; 56 | size_t buflen; 57 | size_t outlen; 58 | uint8_t last_node; 59 | } blake2s_state; 60 | 61 | typedef struct blake2b_state__ 62 | { 63 | uint64_t h[8]; 64 | uint64_t t[2]; 65 | uint64_t f[2]; 66 | uint8_t buf[BLAKE2B_BLOCKBYTES]; 67 | size_t buflen; 68 | size_t outlen; 69 | uint8_t last_node; 70 | } blake2b_state; 71 | 72 | typedef struct blake2sp_state__ 73 | { 74 | blake2s_state S[8][1]; 75 | blake2s_state R[1]; 76 | uint8_t buf[8 * BLAKE2S_BLOCKBYTES]; 77 | size_t buflen; 78 | size_t outlen; 79 | } blake2sp_state; 80 | 81 | typedef struct blake2bp_state__ 82 | { 83 | blake2b_state S[4][1]; 84 | blake2b_state R[1]; 85 | uint8_t buf[4 * BLAKE2B_BLOCKBYTES]; 86 | size_t buflen; 87 | size_t outlen; 88 | } blake2bp_state; 89 | 90 | 91 | BLAKE2_PACKED(struct blake2s_param__ 92 | { 93 | uint8_t digest_length; /* 1 */ 94 | uint8_t key_length; /* 2 */ 95 | uint8_t fanout; /* 3 */ 96 | uint8_t depth; /* 4 */ 97 | uint32_t leaf_length; /* 8 */ 98 | uint32_t node_offset; /* 12 */ 99 | uint16_t xof_length; /* 14 */ 100 | uint8_t node_depth; /* 15 */ 101 | uint8_t inner_length; /* 16 */ 102 | /* uint8_t reserved[0]; */ 103 | uint8_t salt[BLAKE2S_SALTBYTES]; /* 24 */ 104 | uint8_t personal[BLAKE2S_PERSONALBYTES]; /* 32 */ 105 | }); 106 | 107 | typedef struct blake2s_param__ blake2s_param; 108 | 109 | BLAKE2_PACKED(struct blake2b_param__ 110 | { 111 | uint8_t digest_length; /* 1 */ 112 | uint8_t key_length; /* 2 */ 113 | uint8_t fanout; /* 3 */ 114 | uint8_t depth; /* 4 */ 115 | uint32_t leaf_length; /* 8 */ 116 | uint32_t node_offset; /* 12 */ 117 | uint32_t xof_length; /* 16 */ 118 | uint8_t node_depth; /* 17 */ 119 | uint8_t inner_length; /* 18 */ 120 | uint8_t reserved[14]; /* 32 */ 121 | uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */ 122 | uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */ 123 | }); 124 | 125 | typedef struct blake2b_param__ blake2b_param; 126 | 127 | typedef struct blake2xs_state__ 128 | { 129 | blake2s_state S[1]; 130 | blake2s_param P[1]; 131 | } blake2xs_state; 132 | 133 | typedef struct blake2xb_state__ 134 | { 135 | blake2b_state S[1]; 136 | blake2b_param P[1]; 137 | } blake2xb_state; 138 | 139 | /* Padded structs result in a compile-time error */ 140 | enum { 141 | BLAKE2_DUMMY_1 = 1 / ((int)(sizeof(blake2s_param) == BLAKE2S_OUTBYTES) & 1), 142 | BLAKE2_DUMMY_2 = 1 / ((int)(sizeof(blake2b_param) == BLAKE2B_OUTBYTES) & 1) 143 | }; 144 | 145 | /* Streaming API */ 146 | int blake2b_init(blake2b_state* S, size_t outlen); 147 | int blake2b_init_key(blake2b_state* S, size_t outlen, const void* key, size_t keylen); 148 | int blake2b_init_param(blake2b_state* S, const blake2b_param* P); 149 | int blake2b_update(blake2b_state* S, const void* in, size_t inlen); 150 | int blake2b_final(blake2b_state* S, void* out, size_t outlen); 151 | 152 | int blake2bp_init(blake2bp_state* S, size_t outlen); 153 | int blake2bp_init_key(blake2bp_state* S, size_t outlen, const void* key, size_t keylen); 154 | int blake2bp_update(blake2bp_state* S, const void* in, size_t inlen); 155 | int blake2bp_final(blake2bp_state* S, void* out, size_t outlen); 156 | 157 | /* Variable output length API */ 158 | 159 | int blake2xb_init(blake2xb_state* S, const size_t outlen); 160 | int blake2xb_init_key(blake2xb_state* S, const size_t outlen, const void* key, size_t keylen); 161 | int blake2xb_update(blake2xb_state* S, const void* in, size_t inlen); 162 | int blake2xb_final(blake2xb_state* S, void* out, size_t outlen); 163 | 164 | /* Simple API */ 165 | int blake2b(void* out, size_t outlen, const void* in, size_t inlen, const void* key, size_t keylen); 166 | 167 | int blake2bp(void* out, size_t outlen, const void* in, size_t inlen, const void* key, size_t keylen); 168 | 169 | int blake2xb(void* out, size_t outlen, const void* in, size_t inlen, const void* key, size_t keylen); 170 | 171 | /* This is simply an alias for blake2b */ 172 | int blake2(void* out, size_t outlen, const void* in, size_t inlen, const void* key, size_t keylen); 173 | 174 | } 175 | #endif 176 | #endif 177 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/sse/blake2b-load-sse2.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - optimized C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #include "cryptoTools/Common/config.h" 16 | #ifdef ENABLE_SSE_BLAKE2 17 | 18 | 19 | #ifndef BLAKE2B_LOAD_SSE2_H 20 | #define BLAKE2B_LOAD_SSE2_H 21 | 22 | #define LOAD_MSG_0_1(b0, b1) b0 = _mm_set_epi64x(m2, m0); b1 = _mm_set_epi64x(m6, m4) 23 | #define LOAD_MSG_0_2(b0, b1) b0 = _mm_set_epi64x(m3, m1); b1 = _mm_set_epi64x(m7, m5) 24 | #define LOAD_MSG_0_3(b0, b1) b0 = _mm_set_epi64x(m10, m8); b1 = _mm_set_epi64x(m14, m12) 25 | #define LOAD_MSG_0_4(b0, b1) b0 = _mm_set_epi64x(m11, m9); b1 = _mm_set_epi64x(m15, m13) 26 | #define LOAD_MSG_1_1(b0, b1) b0 = _mm_set_epi64x(m4, m14); b1 = _mm_set_epi64x(m13, m9) 27 | #define LOAD_MSG_1_2(b0, b1) b0 = _mm_set_epi64x(m8, m10); b1 = _mm_set_epi64x(m6, m15) 28 | #define LOAD_MSG_1_3(b0, b1) b0 = _mm_set_epi64x(m0, m1); b1 = _mm_set_epi64x(m5, m11) 29 | #define LOAD_MSG_1_4(b0, b1) b0 = _mm_set_epi64x(m2, m12); b1 = _mm_set_epi64x(m3, m7) 30 | #define LOAD_MSG_2_1(b0, b1) b0 = _mm_set_epi64x(m12, m11); b1 = _mm_set_epi64x(m15, m5) 31 | #define LOAD_MSG_2_2(b0, b1) b0 = _mm_set_epi64x(m0, m8); b1 = _mm_set_epi64x(m13, m2) 32 | #define LOAD_MSG_2_3(b0, b1) b0 = _mm_set_epi64x(m3, m10); b1 = _mm_set_epi64x(m9, m7) 33 | #define LOAD_MSG_2_4(b0, b1) b0 = _mm_set_epi64x(m6, m14); b1 = _mm_set_epi64x(m4, m1) 34 | #define LOAD_MSG_3_1(b0, b1) b0 = _mm_set_epi64x(m3, m7); b1 = _mm_set_epi64x(m11, m13) 35 | #define LOAD_MSG_3_2(b0, b1) b0 = _mm_set_epi64x(m1, m9); b1 = _mm_set_epi64x(m14, m12) 36 | #define LOAD_MSG_3_3(b0, b1) b0 = _mm_set_epi64x(m5, m2); b1 = _mm_set_epi64x(m15, m4) 37 | #define LOAD_MSG_3_4(b0, b1) b0 = _mm_set_epi64x(m10, m6); b1 = _mm_set_epi64x(m8, m0) 38 | #define LOAD_MSG_4_1(b0, b1) b0 = _mm_set_epi64x(m5, m9); b1 = _mm_set_epi64x(m10, m2) 39 | #define LOAD_MSG_4_2(b0, b1) b0 = _mm_set_epi64x(m7, m0); b1 = _mm_set_epi64x(m15, m4) 40 | #define LOAD_MSG_4_3(b0, b1) b0 = _mm_set_epi64x(m11, m14); b1 = _mm_set_epi64x(m3, m6) 41 | #define LOAD_MSG_4_4(b0, b1) b0 = _mm_set_epi64x(m12, m1); b1 = _mm_set_epi64x(m13, m8) 42 | #define LOAD_MSG_5_1(b0, b1) b0 = _mm_set_epi64x(m6, m2); b1 = _mm_set_epi64x(m8, m0) 43 | #define LOAD_MSG_5_2(b0, b1) b0 = _mm_set_epi64x(m10, m12); b1 = _mm_set_epi64x(m3, m11) 44 | #define LOAD_MSG_5_3(b0, b1) b0 = _mm_set_epi64x(m7, m4); b1 = _mm_set_epi64x(m1, m15) 45 | #define LOAD_MSG_5_4(b0, b1) b0 = _mm_set_epi64x(m5, m13); b1 = _mm_set_epi64x(m9, m14) 46 | #define LOAD_MSG_6_1(b0, b1) b0 = _mm_set_epi64x(m1, m12); b1 = _mm_set_epi64x(m4, m14) 47 | #define LOAD_MSG_6_2(b0, b1) b0 = _mm_set_epi64x(m15, m5); b1 = _mm_set_epi64x(m10, m13) 48 | #define LOAD_MSG_6_3(b0, b1) b0 = _mm_set_epi64x(m6, m0); b1 = _mm_set_epi64x(m8, m9) 49 | #define LOAD_MSG_6_4(b0, b1) b0 = _mm_set_epi64x(m3, m7); b1 = _mm_set_epi64x(m11, m2) 50 | #define LOAD_MSG_7_1(b0, b1) b0 = _mm_set_epi64x(m7, m13); b1 = _mm_set_epi64x(m3, m12) 51 | #define LOAD_MSG_7_2(b0, b1) b0 = _mm_set_epi64x(m14, m11); b1 = _mm_set_epi64x(m9, m1) 52 | #define LOAD_MSG_7_3(b0, b1) b0 = _mm_set_epi64x(m15, m5); b1 = _mm_set_epi64x(m2, m8) 53 | #define LOAD_MSG_7_4(b0, b1) b0 = _mm_set_epi64x(m4, m0); b1 = _mm_set_epi64x(m10, m6) 54 | #define LOAD_MSG_8_1(b0, b1) b0 = _mm_set_epi64x(m14, m6); b1 = _mm_set_epi64x(m0, m11) 55 | #define LOAD_MSG_8_2(b0, b1) b0 = _mm_set_epi64x(m9, m15); b1 = _mm_set_epi64x(m8, m3) 56 | #define LOAD_MSG_8_3(b0, b1) b0 = _mm_set_epi64x(m13, m12); b1 = _mm_set_epi64x(m10, m1) 57 | #define LOAD_MSG_8_4(b0, b1) b0 = _mm_set_epi64x(m7, m2); b1 = _mm_set_epi64x(m5, m4) 58 | #define LOAD_MSG_9_1(b0, b1) b0 = _mm_set_epi64x(m8, m10); b1 = _mm_set_epi64x(m1, m7) 59 | #define LOAD_MSG_9_2(b0, b1) b0 = _mm_set_epi64x(m4, m2); b1 = _mm_set_epi64x(m5, m6) 60 | #define LOAD_MSG_9_3(b0, b1) b0 = _mm_set_epi64x(m9, m15); b1 = _mm_set_epi64x(m13, m3) 61 | #define LOAD_MSG_9_4(b0, b1) b0 = _mm_set_epi64x(m14, m11); b1 = _mm_set_epi64x(m0, m12) 62 | #define LOAD_MSG_10_1(b0, b1) b0 = _mm_set_epi64x(m2, m0); b1 = _mm_set_epi64x(m6, m4) 63 | #define LOAD_MSG_10_2(b0, b1) b0 = _mm_set_epi64x(m3, m1); b1 = _mm_set_epi64x(m7, m5) 64 | #define LOAD_MSG_10_3(b0, b1) b0 = _mm_set_epi64x(m10, m8); b1 = _mm_set_epi64x(m14, m12) 65 | #define LOAD_MSG_10_4(b0, b1) b0 = _mm_set_epi64x(m11, m9); b1 = _mm_set_epi64x(m15, m13) 66 | #define LOAD_MSG_11_1(b0, b1) b0 = _mm_set_epi64x(m4, m14); b1 = _mm_set_epi64x(m13, m9) 67 | #define LOAD_MSG_11_2(b0, b1) b0 = _mm_set_epi64x(m8, m10); b1 = _mm_set_epi64x(m6, m15) 68 | #define LOAD_MSG_11_3(b0, b1) b0 = _mm_set_epi64x(m0, m1); b1 = _mm_set_epi64x(m5, m11) 69 | #define LOAD_MSG_11_4(b0, b1) b0 = _mm_set_epi64x(m2, m12); b1 = _mm_set_epi64x(m3, m7) 70 | 71 | 72 | #endif 73 | #endif 74 | -------------------------------------------------------------------------------- /cryptoTools/Crypto/blake2/sse/blake2b-round.h: -------------------------------------------------------------------------------- 1 | /* 2 | BLAKE2 reference source code package - optimized C implementations 3 | 4 | Copyright 2012, Samuel Neves . You may use this under the 5 | terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at 6 | your option. The terms of these licenses can be found at: 7 | 8 | - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 9 | - OpenSSL license : https://www.openssl.org/source/license.html 10 | - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | More information about the BLAKE2 hash function can be found at 13 | https://blake2.net. 14 | */ 15 | #include "cryptoTools/Common/config.h" 16 | #ifdef ENABLE_SSE_BLAKE2 17 | 18 | #ifndef BLAKE2B_ROUND_H 19 | #define BLAKE2B_ROUND_H 20 | 21 | #define LOADU(p) _mm_loadu_si128( (const __m128i *)(p) ) 22 | #define STOREU(p,r) _mm_storeu_si128((__m128i *)(p), r) 23 | 24 | #define TOF(reg) _mm_castsi128_ps((reg)) 25 | #define TOI(reg) _mm_castps_si128((reg)) 26 | 27 | #define LIKELY(x) __builtin_expect((x),1) 28 | 29 | 30 | /* Microarchitecture-specific macros */ 31 | #ifndef HAVE_XOP 32 | #ifdef HAVE_SSSE3 33 | #define _mm_roti_epi64(x, c) \ 34 | (-(c) == 32) ? _mm_shuffle_epi32((x), _MM_SHUFFLE(2,3,0,1)) \ 35 | : (-(c) == 24) ? _mm_shuffle_epi8((x), r24) \ 36 | : (-(c) == 16) ? _mm_shuffle_epi8((x), r16) \ 37 | : (-(c) == 63) ? _mm_xor_si128(_mm_srli_epi64((x), -(c)), _mm_add_epi64((x), (x))) \ 38 | : _mm_xor_si128(_mm_srli_epi64((x), -(c)), _mm_slli_epi64((x), 64-(-(c)))) 39 | #else 40 | #define _mm_roti_epi64(r, c) _mm_xor_si128(_mm_srli_epi64( (r), -(c) ),_mm_slli_epi64( (r), 64-(-(c)) )) 41 | #endif 42 | #else 43 | /* ... */ 44 | #endif 45 | 46 | 47 | 48 | #define G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1) \ 49 | row1l = _mm_add_epi64(_mm_add_epi64(row1l, b0), row2l); \ 50 | row1h = _mm_add_epi64(_mm_add_epi64(row1h, b1), row2h); \ 51 | \ 52 | row4l = _mm_xor_si128(row4l, row1l); \ 53 | row4h = _mm_xor_si128(row4h, row1h); \ 54 | \ 55 | row4l = _mm_roti_epi64(row4l, -32); \ 56 | row4h = _mm_roti_epi64(row4h, -32); \ 57 | \ 58 | row3l = _mm_add_epi64(row3l, row4l); \ 59 | row3h = _mm_add_epi64(row3h, row4h); \ 60 | \ 61 | row2l = _mm_xor_si128(row2l, row3l); \ 62 | row2h = _mm_xor_si128(row2h, row3h); \ 63 | \ 64 | row2l = _mm_roti_epi64(row2l, -24); \ 65 | row2h = _mm_roti_epi64(row2h, -24); \ 66 | 67 | #define G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1) \ 68 | row1l = _mm_add_epi64(_mm_add_epi64(row1l, b0), row2l); \ 69 | row1h = _mm_add_epi64(_mm_add_epi64(row1h, b1), row2h); \ 70 | \ 71 | row4l = _mm_xor_si128(row4l, row1l); \ 72 | row4h = _mm_xor_si128(row4h, row1h); \ 73 | \ 74 | row4l = _mm_roti_epi64(row4l, -16); \ 75 | row4h = _mm_roti_epi64(row4h, -16); \ 76 | \ 77 | row3l = _mm_add_epi64(row3l, row4l); \ 78 | row3h = _mm_add_epi64(row3h, row4h); \ 79 | \ 80 | row2l = _mm_xor_si128(row2l, row3l); \ 81 | row2h = _mm_xor_si128(row2h, row3h); \ 82 | \ 83 | row2l = _mm_roti_epi64(row2l, -63); \ 84 | row2h = _mm_roti_epi64(row2h, -63); \ 85 | 86 | #if defined(HAVE_SSSE3) 87 | #define DIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \ 88 | t0 = _mm_alignr_epi8(row2h, row2l, 8); \ 89 | t1 = _mm_alignr_epi8(row2l, row2h, 8); \ 90 | row2l = t0; \ 91 | row2h = t1; \ 92 | \ 93 | t0 = row3l; \ 94 | row3l = row3h; \ 95 | row3h = t0; \ 96 | \ 97 | t0 = _mm_alignr_epi8(row4h, row4l, 8); \ 98 | t1 = _mm_alignr_epi8(row4l, row4h, 8); \ 99 | row4l = t1; \ 100 | row4h = t0; 101 | 102 | #define UNDIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \ 103 | t0 = _mm_alignr_epi8(row2l, row2h, 8); \ 104 | t1 = _mm_alignr_epi8(row2h, row2l, 8); \ 105 | row2l = t0; \ 106 | row2h = t1; \ 107 | \ 108 | t0 = row3l; \ 109 | row3l = row3h; \ 110 | row3h = t0; \ 111 | \ 112 | t0 = _mm_alignr_epi8(row4l, row4h, 8); \ 113 | t1 = _mm_alignr_epi8(row4h, row4l, 8); \ 114 | row4l = t1; \ 115 | row4h = t0; 116 | #else 117 | 118 | #define DIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \ 119 | t0 = row4l;\ 120 | t1 = row2l;\ 121 | row4l = row3l;\ 122 | row3l = row3h;\ 123 | row3h = row4l;\ 124 | row4l = _mm_unpackhi_epi64(row4h, _mm_unpacklo_epi64(t0, t0)); \ 125 | row4h = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(row4h, row4h)); \ 126 | row2l = _mm_unpackhi_epi64(row2l, _mm_unpacklo_epi64(row2h, row2h)); \ 127 | row2h = _mm_unpackhi_epi64(row2h, _mm_unpacklo_epi64(t1, t1)) 128 | 129 | #define UNDIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \ 130 | t0 = row3l;\ 131 | row3l = row3h;\ 132 | row3h = t0;\ 133 | t0 = row2l;\ 134 | t1 = row4l;\ 135 | row2l = _mm_unpackhi_epi64(row2h, _mm_unpacklo_epi64(row2l, row2l)); \ 136 | row2h = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(row2h, row2h)); \ 137 | row4l = _mm_unpackhi_epi64(row4l, _mm_unpacklo_epi64(row4h, row4h)); \ 138 | row4h = _mm_unpackhi_epi64(row4h, _mm_unpacklo_epi64(t1, t1)) 139 | 140 | #endif 141 | 142 | #if defined(HAVE_SSE41) 143 | #include "blake2b-load-sse41.h" 144 | #else 145 | #include "blake2b-load-sse2.h" 146 | #endif 147 | 148 | #define ROUND(r) \ 149 | LOAD_MSG_ ##r ##_1(b0, b1); \ 150 | G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1); \ 151 | LOAD_MSG_ ##r ##_2(b0, b1); \ 152 | G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1); \ 153 | DIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \ 154 | LOAD_MSG_ ##r ##_3(b0, b1); \ 155 | G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1); \ 156 | LOAD_MSG_ ##r ##_4(b0, b1); \ 157 | G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h,b0,b1); \ 158 | UNDIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); 159 | 160 | #endif 161 | #endif 162 | -------------------------------------------------------------------------------- /cryptoTools/Network/Endpoint.h: -------------------------------------------------------------------------------- 1 | #include "Session.h" -------------------------------------------------------------------------------- /cryptoTools/Network/IoBuffer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #ifdef ENABLE_BOOST 3 | 4 | #include "IoBuffer.h" 5 | #include "Channel.h" 6 | #include "IOService.h" 7 | #include 8 | #include 9 | 10 | namespace osuCrypto 11 | { 12 | namespace details 13 | { 14 | //operation_canceled opCancel; 15 | 16 | void FixedSendBuff::asyncPerform(ChannelBase * base, io_completion_handle&& completionHandle) 17 | { 18 | //if (base->mHandle == nullptr) 19 | //{ 20 | // lout << "null handle" << std::endl; 21 | 22 | // lout << base->mLog << std::endl; 23 | //} 24 | 25 | base->mSendBuffers = getSendBuffer(); 26 | base->mHandle->async_send(base->mSendBuffers, 27 | std::forward(completionHandle)); 28 | } 29 | 30 | void FixedRecvBuff::asyncPerform(ChannelBase * base, io_completion_handle&& completionHandle) 31 | { 32 | 33 | mComHandle = std::move(completionHandle); 34 | mBase = base; 35 | 36 | if (!mComHandle) 37 | throw std::runtime_error(LOCATION); 38 | 39 | // first we have to receive the header which tells us how much. 40 | base->mRecvBuffer = getRecvHeaderBuffer(); 41 | base->mHandle->async_recv({&base->mRecvBuffer, 1}, [this](const error_code& ec, u64 bt1) { 42 | 43 | if (!ec) 44 | { 45 | // check that the buffer has enough space. Resize if not. 46 | if (getHeaderSize() != getBufferSize()) 47 | { 48 | resizeBuffer(getHeaderSize()); 49 | 50 | // check that the resize was successful. 51 | if (getHeaderSize() != getBufferSize()) 52 | { 53 | std::stringstream ss; 54 | ss << "Bad receive buffer size.\n" 55 | << " Size transmitted: " << getHeaderSize() 56 | << " bytes\n Size of buffer: " << getBufferSize() << " bytes\n"; 57 | 58 | // make the channel to know that a receive has a partial failure. 59 | // The partial error can be cleared if the following lambda is 60 | // called by the user. This will complete the receive operation. 61 | //mBase->setBadRecvErrorState(ss.str()); 62 | 63 | // give the user a chance to give us another location 64 | // by passing out an exception which they can call. 65 | mPromise.set_exception(std::make_exception_ptr( 66 | BadReceiveBufferSize(ss.str(), getHeaderSize()))); 67 | 68 | auto ec = boost::system::errc::make_error_code(boost::system::errc::no_buffer_space); 69 | mComHandle(ec, sizeof(u32)); 70 | return; 71 | } 72 | } 73 | 74 | // the normal case that the buffer is the right size or was correctly resized. 75 | mBase->mRecvBuffer = getRecvBuffer(); 76 | mBase->mHandle->async_recv({ &mBase->mRecvBuffer , 1 }, [this, bt1](const error_code& ec, u64 bt2) 77 | { 78 | 79 | if (!ec) mPromise.set_value(); 80 | else mPromise.set_exception(std::make_exception_ptr(std::runtime_error(ec.message()))); 81 | 82 | if (!mComHandle) 83 | throw std::runtime_error(LOCATION); 84 | 85 | #ifdef ENABLE_NET_LOG 86 | if(ec) 87 | log("FixedRecvBuff error " + std::to_string(mIdx) + " " + LOCATION); 88 | else 89 | log("FixedRecvBuff success " + std::to_string(mIdx) + " " + LOCATION); 90 | 91 | #endif 92 | mComHandle(ec, bt1 + bt2); 93 | }); 94 | } 95 | else 96 | { 97 | #ifdef ENABLE_NET_LOG 98 | log("FixedRecvBuff error " + std::to_string(mIdx) + " " + ec.message() +" " + LOCATION); 99 | #endif 100 | mPromise.set_exception(std::make_exception_ptr(std::runtime_error(ec.message()))); 101 | mComHandle(ec, bt1); 102 | } 103 | }); 104 | 105 | } 106 | 107 | 108 | std::string FixedSendBuff::toString() const 109 | { 110 | return std::string("FixedSendBuff #") 111 | #ifdef ENABLE_NET_LOG 112 | + std::to_string(mIdx) 113 | #endif 114 | + " ~ " + std::to_string(getBufferSize()) + " bytes"; 115 | } 116 | 117 | std::string FixedRecvBuff::toString() const 118 | { 119 | return std::string("FixedRecvBuff #") 120 | #ifdef ENABLE_NET_LOG 121 | + std::to_string(mIdx) 122 | #endif 123 | + " ~ " + std::to_string(getBufferSize()) + " bytes"; 124 | } 125 | 126 | 127 | //void Callback::asyncPerform(ChannelBase* base, io_completion_handle&& completionHandle) 128 | //{ 129 | // auto ec = boost::system::errc::make_error_code(boost::system::errc::success); 130 | // boost::asio::post(base->mIos.mIoService.get_executor(), [c = std::move(mComm), ec](){ 131 | // c(ec); 132 | // }); 133 | // completionHandle(ec, 0); 134 | //} 135 | 136 | boost::asio::io_context& getIOService(ChannelBase* base) 137 | { 138 | return base->mIos.mIoService; 139 | } 140 | 141 | } 142 | } 143 | #endif -------------------------------------------------------------------------------- /cryptoTools/Network/Session.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | #ifdef ENABLE_BOOST 5 | 6 | #include "cryptoTools/Common/Defines.h" 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "TLS.h" 14 | #include "util.h" 15 | 16 | namespace osuCrypto { 17 | 18 | class IOService; 19 | class Acceptor; 20 | namespace details { struct SessionGroup; } 21 | class ChannelBase; 22 | struct SessionBase; 23 | 24 | typedef SessionMode EpMode; 25 | 26 | class Session 27 | { 28 | public: 29 | 30 | // Start a session for the given IP and port in either Client or Server mode. 31 | // The server should use their local address on which the socket should bind. 32 | // The client should use the address of the server. 33 | // The same name should be used by both sessions. Multiple Sessions can be bound to the same 34 | // address if the same IOService is used but with different name. 35 | void start(IOService& ioService, std::string remoteIp, u32 port, SessionMode type, std::string name = ""); 36 | 37 | // Start a session for the given address in either Client or Server mode. 38 | // The server should use their local address on which the socket should bind. 39 | // The client should use the address of the server. 40 | // The same name should be used by both sessions. Multiple Sessions can be bound to the same 41 | // address if the same IOService is used but with different name. 42 | void start(IOService& ioService, std::string address, SessionMode type, std::string name = ""); 43 | 44 | void start(IOService& ioService, std::string ip, u64 port, SessionMode type, TLSContext& tls, std::string name = ""); 45 | 46 | 47 | // See start(...) 48 | Session(IOService & ioService, std::string address, SessionMode type, std::string name = ""); 49 | 50 | // See start(...) 51 | Session(IOService& ioService, std::string remoteIP, u32 port, SessionMode type, std::string name = ""); 52 | 53 | Session(IOService & ioService, std::string remoteIP, u32 port, SessionMode type, TLSContext& tls, std::string name = ""); 54 | 55 | // Default constructor 56 | Session(); 57 | 58 | Session(const Session&); 59 | Session(Session&&) = default; 60 | 61 | Session(const std::shared_ptr& c); 62 | 63 | ~Session(); 64 | 65 | std::string getName() const; 66 | 67 | u64 getSessionID() const; 68 | 69 | IOService& getIOService(); 70 | 71 | // Adds a new channel (data pipe) between this endpoint and the remote. The channel is named at each end. 72 | Channel addChannel(std::string localName = "", std::string remoteName = ""); 73 | 74 | // Stops this Session. 75 | void stop(/*const std::optional& waitTime = {}*/); 76 | 77 | // returns whether the endpoint has been stopped (or never isConnected). 78 | bool stopped() const; 79 | 80 | u32 port() const; 81 | 82 | std::string IP() const; 83 | 84 | bool isHost() const; 85 | 86 | std::shared_ptr mBase; 87 | }; 88 | 89 | typedef Session Endpoint; 90 | class IOService; 91 | 92 | struct SessionBase 93 | { 94 | SessionBase(IOService& ios); 95 | ~SessionBase(); 96 | 97 | void stop(); 98 | // Removes the channel with chlName. 99 | //void removeChannel(ChannelBase* chl); 100 | 101 | // if this channnel is waiting on a socket, cancel that 102 | // operation and set the future to contain an exception 103 | //void cancelPendingConnection(ChannelBase* chl); 104 | 105 | std::string mIP; 106 | u32 mPort = 0, mAnonymousChannelIdx = 0; 107 | SessionMode mMode = SessionMode::Client; 108 | bool mStopped = true; 109 | IOService* mIOService = nullptr; 110 | Acceptor* mAcceptor = nullptr; 111 | 112 | 113 | std::atomic mRealRefCount; 114 | 115 | Work mWorker; 116 | 117 | //bool mHasGroup = false; 118 | std::shared_ptr mGroup; 119 | 120 | TLSContext mTLSContext; 121 | 122 | std::mutex mAddChannelMtx; 123 | std::string mName; 124 | 125 | u64 mSessionID = 0; 126 | 127 | #ifdef ENABLE_WOLFSSL 128 | std::mutex mTLSSessionIDMtx; 129 | bool mTLSSessionIDIsSet = false; 130 | block mTLSSessionID; 131 | #endif 132 | 133 | boost::asio::ip::tcp::endpoint mRemoteAddr; 134 | }; 135 | 136 | 137 | } 138 | #endif -------------------------------------------------------------------------------- /cryptoTools/Network/SocketAdapter.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "SocketAdapter.h" 3 | 4 | namespace osuCrypto 5 | { 6 | 7 | 8 | } -------------------------------------------------------------------------------- /frontend_cryptoTools/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | file(GLOB_RECURSE SRCS *.cpp) 4 | 5 | include_directories(${CMAKE_SOURCE_DIR}) 6 | 7 | add_executable(frontend_cryptoTools ${SRCS}) 8 | target_link_libraries(frontend_cryptoTools cryptoTools tests_cryptoTools) 9 | 10 | 11 | 12 | 13 | if(MSVC) 14 | target_compile_options(frontend_cryptoTools PRIVATE $<$:/std:c++${CRYPTO_TOOLS_STD_VER}>) 15 | 16 | else() 17 | target_compile_options(frontend_cryptoTools PRIVATE $<$:-std=c++${CRYPTO_TOOLS_STD_VER}>) 18 | endif() -------------------------------------------------------------------------------- /frontend_cryptoTools/certs/ca-cert.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ladnir/cryptoTools/c2735302694ff4c0c44dff3732deb4d7e2fd304e/frontend_cryptoTools/certs/ca-cert.der -------------------------------------------------------------------------------- /frontend_cryptoTools/certs/ca-cert.pem: -------------------------------------------------------------------------------- 1 | Certificate: 2 | Data: 3 | Version: 3 (0x2) 4 | Serial Number: 9727763710660753659 (0x86fff58e10deb8fb) 5 | Signature Algorithm: sha256WithRSAEncryption 6 | Issuer: C=US, ST=Montana, L=Bozeman, O=Sawtooth, OU=Consulting, CN=www.wolfssl.com/emailAddress=info@wolfssl.com 7 | Validity 8 | Not Before: Apr 13 15:23:09 2018 GMT 9 | Not After : Jan 7 15:23:09 2021 GMT 10 | Subject: C=US, ST=Montana, L=Bozeman, O=Sawtooth, OU=Consulting, CN=www.wolfssl.com/emailAddress=info@wolfssl.com 11 | Subject Public Key Info: 12 | Public Key Algorithm: rsaEncryption 13 | Public-Key: (2048 bit) 14 | Modulus: 15 | 00:bf:0c:ca:2d:14:b2:1e:84:42:5b:cd:38:1f:4a: 16 | f2:4d:75:10:f1:b6:35:9f:df:ca:7d:03:98:d3:ac: 17 | de:03:66:ee:2a:f1:d8:b0:7d:6e:07:54:0b:10:98: 18 | 21:4d:80:cb:12:20:e7:cc:4f:de:45:7d:c9:72:77: 19 | 32:ea:ca:90:bb:69:52:10:03:2f:a8:f3:95:c5:f1: 20 | 8b:62:56:1b:ef:67:6f:a4:10:41:95:ad:0a:9b:e3: 21 | a5:c0:b0:d2:70:76:50:30:5b:a8:e8:08:2c:7c:ed: 22 | a7:a2:7a:8d:38:29:1c:ac:c7:ed:f2:7c:95:b0:95: 23 | 82:7d:49:5c:38:cd:77:25:ef:bd:80:75:53:94:3c: 24 | 3d:ca:63:5b:9f:15:b5:d3:1d:13:2f:19:d1:3c:db: 25 | 76:3a:cc:b8:7d:c9:e5:c2:d7:da:40:6f:d8:21:dc: 26 | 73:1b:42:2d:53:9c:fe:1a:fc:7d:ab:7a:36:3f:98: 27 | de:84:7c:05:67:ce:6a:14:38:87:a9:f1:8c:b5:68: 28 | cb:68:7f:71:20:2b:f5:a0:63:f5:56:2f:a3:26:d2: 29 | b7:6f:b1:5a:17:d7:38:99:08:fe:93:58:6f:fe:c3: 30 | 13:49:08:16:0b:a7:4d:67:00:52:31:67:23:4e:98: 31 | ed:51:45:1d:b9:04:d9:0b:ec:d8:28:b3:4b:bd:ed: 32 | 36:79 33 | Exponent: 65537 (0x10001) 34 | X509v3 extensions: 35 | X509v3 Subject Key Identifier: 36 | 27:8E:67:11:74:C3:26:1D:3F:ED:33:63:B3:A4:D8:1D:30:E5:E8:D5 37 | X509v3 Authority Key Identifier: 38 | keyid:27:8E:67:11:74:C3:26:1D:3F:ED:33:63:B3:A4:D8:1D:30:E5:E8:D5 39 | DirName:/C=US/ST=Montana/L=Bozeman/O=Sawtooth/OU=Consulting/CN=www.wolfssl.com/emailAddress=info@wolfssl.com 40 | serial:86:FF:F5:8E:10:DE:B8:FB 41 | 42 | X509v3 Basic Constraints: 43 | CA:TRUE 44 | Signature Algorithm: sha256WithRSAEncryption 45 | 9e:28:88:72:00:ca:e6:e7:97:ca:c1:f1:1f:9e:12:b2:b8:c7: 46 | 51:ea:28:e1:36:b5:2d:e6:2f:08:23:cb:a9:4a:87:25:c6:5d: 47 | 89:45:ea:f5:00:98:ac:76:fb:1b:af:f0:ce:64:9e:da:08:bf: 48 | b6:eb:b4:b5:0c:a0:e7:f6:47:59:1c:61:cf:2e:0e:58:a4:82: 49 | ac:0f:3f:ec:c4:ae:80:f7:b0:8a:1e:85:41:e8:ff:fe:fe:4f: 50 | 1a:24:d5:49:fa:fb:fe:5e:e5:d3:91:0e:4f:4e:0c:21:51:71: 51 | 83:04:6b:62:7b:4f:59:76:48:81:1e:b4:f7:04:47:8a:91:57: 52 | a3:11:a9:f2:20:b4:78:33:62:3d:b0:5e:0d:f9:86:38:82:da: 53 | a1:98:8d:19:06:87:21:39:b7:02:f7:da:7d:58:ba:52:15:d8: 54 | 3b:c9:7b:58:34:a0:c7:e2:7c:a9:83:13:e1:b6:ec:01:bf:52: 55 | 33:0b:c4:fe:43:d3:c6:a4:8e:2f:87:7f:7a:44:ea:ca:53:6c: 56 | 85:ed:65:76:73:31:03:4e:ea:bd:35:54:13:f3:64:87:6b:df: 57 | 34:dd:34:a1:88:3b:db:4d:af:1b:64:90:92:71:30:8e:c8:cc: 58 | e5:60:24:af:31:16:39:33:91:50:f9:ab:68:42:74:7a:35:d9: 59 | dd:c8:c4:52 60 | -----BEGIN CERTIFICATE----- 61 | MIIEqjCCA5KgAwIBAgIJAIb/9Y4Q3rj7MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYD 62 | VQQGEwJVUzEQMA4GA1UECAwHTW9udGFuYTEQMA4GA1UEBwwHQm96ZW1hbjERMA8G 63 | A1UECgwIU2F3dG9vdGgxEzARBgNVBAsMCkNvbnN1bHRpbmcxGDAWBgNVBAMMD3d3 64 | dy53b2xmc3NsLmNvbTEfMB0GCSqGSIb3DQEJARYQaW5mb0B3b2xmc3NsLmNvbTAe 65 | Fw0xODA0MTMxNTIzMDlaFw0yMTAxMDcxNTIzMDlaMIGUMQswCQYDVQQGEwJVUzEQ 66 | MA4GA1UECAwHTW9udGFuYTEQMA4GA1UEBwwHQm96ZW1hbjERMA8GA1UECgwIU2F3 67 | dG9vdGgxEzARBgNVBAsMCkNvbnN1bHRpbmcxGDAWBgNVBAMMD3d3dy53b2xmc3Ns 68 | LmNvbTEfMB0GCSqGSIb3DQEJARYQaW5mb0B3b2xmc3NsLmNvbTCCASIwDQYJKoZI 69 | hvcNAQEBBQADggEPADCCAQoCggEBAL8Myi0Ush6EQlvNOB9K8k11EPG2NZ/fyn0D 70 | mNOs3gNm7irx2LB9bgdUCxCYIU2AyxIg58xP3kV9yXJ3MurKkLtpUhADL6jzlcXx 71 | i2JWG+9nb6QQQZWtCpvjpcCw0nB2UDBbqOgILHztp6J6jTgpHKzH7fJ8lbCVgn1J 72 | XDjNdyXvvYB1U5Q8PcpjW58VtdMdEy8Z0TzbdjrMuH3J5cLX2kBv2CHccxtCLVOc 73 | /hr8fat6Nj+Y3oR8BWfOahQ4h6nxjLVoy2h/cSAr9aBj9VYvoybSt2+xWhfXOJkI 74 | /pNYb/7DE0kIFgunTWcAUjFnI06Y7VFFHbkE2Qvs2CizS73tNnkCAwEAAaOB/DCB 75 | +TAdBgNVHQ4EFgQUJ45nEXTDJh0/7TNjs6TYHTDl6NUwgckGA1UdIwSBwTCBvoAU 76 | J45nEXTDJh0/7TNjs6TYHTDl6NWhgZqkgZcwgZQxCzAJBgNVBAYTAlVTMRAwDgYD 77 | VQQIDAdNb250YW5hMRAwDgYDVQQHDAdCb3plbWFuMREwDwYDVQQKDAhTYXd0b290 78 | aDETMBEGA1UECwwKQ29uc3VsdGluZzEYMBYGA1UEAwwPd3d3LndvbGZzc2wuY29t 79 | MR8wHQYJKoZIhvcNAQkBFhBpbmZvQHdvbGZzc2wuY29tggkAhv/1jhDeuPswDAYD 80 | VR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAniiIcgDK5ueXysHxH54SsrjH 81 | Ueoo4Ta1LeYvCCPLqUqHJcZdiUXq9QCYrHb7G6/wzmSe2gi/tuu0tQyg5/ZHWRxh 82 | zy4OWKSCrA8/7MSugPewih6FQej//v5PGiTVSfr7/l7l05EOT04MIVFxgwRrYntP 83 | WXZIgR609wRHipFXoxGp8iC0eDNiPbBeDfmGOILaoZiNGQaHITm3AvfafVi6UhXY 84 | O8l7WDSgx+J8qYMT4bbsAb9SMwvE/kPTxqSOL4d/ekTqylNshe1ldnMxA07qvTVU 85 | E/Nkh2vfNN00oYg7202vG2SQknEwjsjM5WAkrzEWOTORUPmraEJ0ejXZ3cjEUg== 86 | -----END CERTIFICATE----- 87 | -------------------------------------------------------------------------------- /frontend_cryptoTools/certs/dh2048.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ladnir/cryptoTools/c2735302694ff4c0c44dff3732deb4d7e2fd304e/frontend_cryptoTools/certs/dh2048.der -------------------------------------------------------------------------------- /frontend_cryptoTools/certs/dh2048.pem: -------------------------------------------------------------------------------- 1 | Diffie-Hellman-Parameters: (2048 bit) 2 | prime: 3 | 00:b0:a1:08:06:9c:08:13:ba:59:06:3c:bc:30:d5: 4 | f5:00:c1:4f:44:a7:d6:ef:4a:c6:25:27:1c:e8:d2: 5 | 96:53:0a:5c:91:dd:a2:c2:94:84:bf:7d:b2:44:9f: 6 | 9b:d2:c1:8a:c5:be:72:5c:a7:e7:91:e6:d4:9f:73: 7 | 07:85:5b:66:48:c7:70:fa:b4:ee:02:c9:3d:9a:4a: 8 | da:3d:c1:46:3e:19:69:d1:17:46:07:a3:4d:9f:2b: 9 | 96:17:39:6d:30:8d:2a:f3:94:d3:75:cf:a0:75:e6: 10 | f2:92:1f:1a:70:05:aa:04:83:57:30:fb:da:76:93: 11 | 38:50:e8:27:fd:63:ee:3c:e5:b7:c8:09:ae:6f:50: 12 | 35:8e:84:ce:4a:00:e9:12:7e:5a:31:d7:33:fc:21: 13 | 13:76:cc:16:30:db:0c:fc:c5:62:a7:35:b8:ef:b7: 14 | b0:ac:c0:36:f6:d9:c9:46:48:f9:40:90:00:2b:1b: 15 | aa:6c:e3:1a:c3:0b:03:9e:1b:c2:46:e4:48:4e:22: 16 | 73:6f:c3:5f:d4:9a:d6:30:07:48:d6:8c:90:ab:d4: 17 | f6:f1:e3:48:d3:58:4b:a6:b9:cd:29:bf:68:1f:08: 18 | 4b:63:86:2f:5c:6b:d6:b6:06:65:f7:a6:dc:00:67: 19 | 6b:bb:c3:a9:41:83:fb:c7:fa:c8:e2:1e:7e:af:00: 20 | 3f:93 21 | generator: 2 (0x2) 22 | -----BEGIN DH PARAMETERS----- 23 | MIIBCAKCAQEAsKEIBpwIE7pZBjy8MNX1AMFPRKfW70rGJScc6NKWUwpckd2iwpSE 24 | v32yRJ+b0sGKxb5yXKfnkebUn3MHhVtmSMdw+rTuAsk9mkraPcFGPhlp0RdGB6NN 25 | nyuWFzltMI0q85TTdc+gdebykh8acAWqBINXMPvadpM4UOgn/WPuPOW3yAmub1A1 26 | joTOSgDpEn5aMdcz/CETdswWMNsM/MVipzW477ewrMA29tnJRkj5QJAAKxuqbOMa 27 | wwsDnhvCRuRITiJzb8Nf1JrWMAdI1oyQq9T28eNI01hLprnNKb9oHwhLY4YvXGvW 28 | tgZl96bcAGdru8OpQYP7x/rI4h5+rwA/kwIBAg== 29 | -----END DH PARAMETERS----- 30 | -------------------------------------------------------------------------------- /frontend_cryptoTools/frontend_cryptoTools.args.json: -------------------------------------------------------------------------------- 1 | { 2 | "FileVersion": 2, 3 | "Id": "9816c48c-6316-40c7-929c-4b29505c7e0a", 4 | "Items": [ 5 | { 6 | "Id": "4a869124-31d1-4c30-bd70-53cd0935616a", 7 | "Command": "-u" 8 | } 9 | ] 10 | } -------------------------------------------------------------------------------- /frontend_cryptoTools/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "../tests_cryptoTools/UnitTests.h" 3 | #include "Tutorials/Network.h" 4 | #include "cryptoTools/Network/Channel.h" 5 | #include "cryptoTools/Network/IOService.h" 6 | #include 7 | #include "cryptoTools/Common/CuckooIndex.h" 8 | #include "cryptoTools/Common/CLP.h" 9 | using namespace osuCrypto; 10 | #include 11 | #include 12 | 13 | #ifdef ENABLE_CIRCUITS 14 | #include 15 | 16 | void print_aes_bristol() 17 | { 18 | 19 | //{ 20 | // auto name = "./AES-expanded.txt"; 21 | 22 | // std::ifstream file(name); 23 | 24 | // BetaCircuit cir2; 25 | // cir2.readBristol(file); 26 | // std::cout << "and " << cir2.mNonlinearGateCount << std::endl; 27 | //} 28 | for (auto rounds : { 10, /*12, */14 })// 29 | { 30 | BetaLibrary lib; 31 | BetaCircuit cir; 32 | 33 | 34 | BetaBundle input1(256); 35 | BetaBundle k(128 * rounds + 128); 36 | BetaBundle c(128); 37 | 38 | 39 | cir.addInputBundle(k); 40 | cir.addInputBundle(input1); 41 | cir.addOutputBundle(c); 42 | 43 | 44 | // m is the fist 128 bits and cMask is the second of input1. 45 | BetaBundle m, cMask; 46 | m.mWires.insert( 47 | m.mWires.end(), 48 | input1.mWires.begin(), 49 | input1.mWires.begin() + 128); 50 | cMask.mWires.insert( 51 | cMask.mWires.end(), 52 | input1.mWires.begin() + 128, 53 | input1.mWires.begin() + 256); 54 | 55 | 56 | // c = AES_k(m) 57 | lib.aes_exapnded_build(cir, m, k, c); 58 | 59 | // c = c ^ cMask 60 | lib.bitwiseXor_build(cir, c, cMask, c); 61 | 62 | auto name = "./aes_r_" + std::to_string(rounds) + ".txt"; 63 | 64 | { 65 | std::ofstream ofile(name); 66 | cir.writeBristol(ofile); 67 | } 68 | 69 | 70 | std::ifstream file(name); 71 | 72 | BetaCircuit cir2; 73 | cir2.readBristol(file); 74 | 75 | std::vector in(2), out1(1), out2(1); 76 | in[0].resize(k.size()); 77 | in[1].resize(input1.size()); 78 | out1[0].resize(128); 79 | out2[0].resize(128); 80 | 81 | PRNG prng(ZeroBlock); 82 | AES aes(prng.get()); 83 | 84 | for (u64 i = 0; i < 3; ++i) 85 | { 86 | 87 | in[1].randomize(prng); 88 | if (rounds == 10) 89 | { 90 | memcpy(in[0].data(), aes.mRoundKey.data(), 11 * 16); 91 | } 92 | else 93 | { 94 | in[0].randomize(prng); 95 | } 96 | 97 | 98 | cir.evaluate(in, out1); 99 | cir2.evaluate(in, out2); 100 | 101 | if (out1[0] != out2[0]) 102 | { 103 | std::cout << "failed \n"; 104 | std::cout << out1[0] << std::endl; 105 | std::cout << out2[0] << std::endl; 106 | } 107 | else 108 | { 109 | if (rounds == 10) 110 | { 111 | block message = in[1].getSpan()[0]; 112 | block mask = in[1].getSpan()[1]; 113 | block ctxt = aes.ecbEncBlock(message) ^ mask; 114 | 115 | if (neq(ctxt, out1[0].getSpan()[0])) 116 | { 117 | std::cout << "failed bad val" << std::endl; 118 | } 119 | else 120 | { 121 | std::cout << "passed! " << cir.mNonlinearGateCount << std::endl; 122 | } 123 | } 124 | else 125 | { 126 | std::cout << "passed " << std::endl; 127 | } 128 | } 129 | 130 | std::cout 131 | << "k " << in[0] << "\n" 132 | << "m " << in[1] << "\n" 133 | << "c " << out1[0] << std::endl; 134 | } 135 | 136 | } 137 | } 138 | #endif 139 | 140 | int main(int argc, char** argv) 141 | { 142 | 143 | CLP cmd(argc, argv); 144 | 145 | if (cmd.isSet("tut")) 146 | { 147 | networkTutorial(); 148 | } 149 | else if(cmd.isSet("u")) 150 | { 151 | tests_cryptoTools::Tests.runIf(cmd); 152 | } 153 | else 154 | { 155 | std::cout << "Run the unit tests with:\n\n\t" 156 | << Color::Green << cmd.mProgramName << " -u\n\n" << Color::Default 157 | << "Run the network tutorial with:\n\n\t" 158 | << Color::Green << cmd.mProgramName << " -tut" << Color::Default 159 | << std::endl; 160 | } 161 | } -------------------------------------------------------------------------------- /frontend_cryptoTools/signalHandle.cpp: -------------------------------------------------------------------------------- 1 | 2 | #if !defined _MSC_VER & 0 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | char* exe = 0; 13 | 14 | int initialiseExecutableName() 15 | { 16 | char link[1024]; 17 | exe = new char[1024]; 18 | snprintf(link, sizeof link, "/proc/%d/exe", getpid()); 19 | if (readlink(link, exe, sizeof link) == -1) { 20 | fprintf(stderr, "ERRORRRRR\n"); 21 | exit(1); 22 | } 23 | printf("Executable name initialised: %s\n", exe); 24 | } 25 | 26 | const char* getExecutableName() 27 | { 28 | if (exe == 0) 29 | initialiseExecutableName(); 30 | return exe; 31 | } 32 | 33 | /* get REG_EIP from ucontext.h */ 34 | #define __USE_GNU 35 | #include 36 | #ifdef __x86_64__ 37 | #define REG_EIP REG_RIP 38 | #endif 39 | 40 | void bt_sighandler(int sig, siginfo_t *info, 41 | void *secret) { 42 | 43 | void *trace[16]; 44 | char **messages = (char **)NULL; 45 | int i, trace_size = 0; 46 | ucontext_t *uc = (ucontext_t *)secret; 47 | 48 | /* Do something useful with siginfo_t */ 49 | if (sig == SIGSEGV) 50 | printf("Got signal %d, faulty address is %p, " 51 | "from %p\n", sig, info->si_addr, 52 | uc->uc_mcontext.gregs[REG_EIP]); 53 | else 54 | printf("Got signal %d#92;\n", sig); 55 | 56 | trace_size = backtrace(trace, 16); 57 | /* overwrite sigaction with caller's address */ 58 | trace[1] = (void *)uc->uc_mcontext.gregs[REG_EIP]; 59 | 60 | messages = backtrace_symbols(trace, trace_size); 61 | /* skip first stack frame (points here) */ 62 | printf("[bt] Execution path:#92;\n"); 63 | for (i = 1; i 4 | #include 5 | #include 6 | 7 | #include "Common.h" 8 | #include 9 | #include 10 | #include 11 | 12 | namespace osuCrypto 13 | { 14 | void aesCheck(); 15 | } 16 | using namespace osuCrypto; 17 | //namespace tests_cryptoTools 18 | //{ 19 | #include 20 | namespace tests_cryptoTools 21 | { 22 | block byteReverse(block b) 23 | { 24 | block r; 25 | auto bb = b.data(); 26 | auto rr = r.data(); 27 | for (u64 i = 0; i < 16; ++i) 28 | rr[i] = bb[15 - i]; 29 | return r; 30 | } 31 | 32 | template 33 | void test() 34 | { 35 | 36 | block userKey = byteReverse(toBlock( 37 | 0x0001020304050607, 38 | 0x08090a0b0c0d0e0f)); 39 | block ptxt = byteReverse(toBlock( 40 | 0x0011223344556677, 41 | 0x8899aabbccddeeff)); 42 | block exp = byteReverse(toBlock( 43 | 0x69c4e0d86a7b0430, 44 | 0xd8cdb78070b4c55a)); 45 | 46 | details::AES encKey(userKey); 47 | //details::AES encKey2(userKey); 48 | 49 | auto ctxt = encKey.ecbEncBlock(ptxt); 50 | if (neq(ctxt, exp)) 51 | throw UnitTestFail(); 52 | 53 | details::AESDec decKey(userKey); 54 | 55 | auto ptxt2 = decKey.ecbDecBlock(ctxt); 56 | if (neq(ptxt2, ptxt)) 57 | throw UnitTestFail(); 58 | 59 | for (u64 tt = 0; tt < 0; ++tt) 60 | { 61 | u64 length = (1ull << 6) + tt; 62 | 63 | std::vector data(length); 64 | std::vector cyphertext1(length); 65 | std::vector cyphertext2(length); 66 | 67 | for (u64 i = 0; i < length; ++i) 68 | { 69 | data[i] = toBlock(i); 70 | encKey.ecbEncBlock(data[i], cyphertext1[i]); 71 | decKey.ecbDecBlock(cyphertext1[i], ptxt); 72 | if (neq(data[i], ptxt)) 73 | throw UnitTestFail(); 74 | } 75 | 76 | encKey.ecbEncBlocks(data.data(), data.size(), cyphertext2.data()); 77 | for (u64 i = 0; i < length; ++i) 78 | { 79 | if (neq(cyphertext1[i], cyphertext2[i])) 80 | throw UnitTestFail(); 81 | } 82 | 83 | encKey.ecbEncCounterMode(1423234, data.size(), cyphertext2.data()); 84 | for (u64 i = 0; i < length; ++i) 85 | { 86 | if (neq(encKey.ecbEncBlock(block(1423234 + i)), cyphertext2[i])) 87 | throw UnitTestFail(); 88 | } 89 | 90 | u64 step = 3; 91 | std::vector data2(length * step); 92 | for (u64 i = 0; i < length; ++i) 93 | { 94 | for (u64 j = 0; j < step; ++j) 95 | { 96 | data2[i * step + j] = block(45233453 * i, 234235543 * j); 97 | } 98 | 99 | data[i] = data2[i * step + (i % step)]; 100 | } 101 | 102 | encKey.TmmoHashBlocks(data, cyphertext1, [t = 0]() mutable {return block(t++); }); 103 | encKey.TmmoHashBlocks(data, cyphertext2, [t = 0]() mutable {return block(t++); }); 104 | 105 | for (u64 i = 0; i < length; ++i) 106 | { 107 | 108 | if (cyphertext1[i] != cyphertext2[i]) 109 | { 110 | throw RTE_LOC; 111 | } 112 | 113 | // y_i = AES(AES(x_i) ^ tweak_i) + AES(x_i). 114 | if (cyphertext1[i] != (encKey.ecbEncBlock(encKey.ecbEncBlock(data[i]) ^ block(i)) ^ encKey.ecbEncBlock(data[i]))) 115 | throw RTE_LOC; 116 | 117 | if (cyphertext1[i] != encKey.TmmoHashBlock(data[i], block(i))) 118 | throw RTE_LOC; 119 | } 120 | 121 | cyphertext2.resize(data2.size()); 122 | encKey.TmmoHashBlocks(data2, cyphertext2, [t = 0, step]() mutable {return block(t++ / step); }); 123 | 124 | for (u64 i = 0; i < length; ++i) 125 | { 126 | if (cyphertext1[i] != cyphertext2[i * step + (i % step)]) 127 | { 128 | throw RTE_LOC; 129 | } 130 | } 131 | } 132 | 133 | { 134 | block state(241453245234532ull, 2345123451235123ull); 135 | block t = details::AES::roundEnc(state, state); 136 | //std::cout << t.get(1) << std::endl; 137 | //std::cout << t.get(0) << std::endl; 138 | block exp(7833415616886348363ull, 14916852119338822067ull); 139 | if (t != exp) 140 | throw RTE_LOC; 141 | } 142 | } 143 | 144 | 145 | 146 | template 147 | void compare() 148 | { 149 | block userKey(2342134234, 213421341234); 150 | details::AES enc0(userKey); 151 | details::AES enc1(userKey); 152 | 153 | 154 | for (u64 i = 0; i < 40; ++i) 155 | { 156 | auto b0 = enc0.ecbEncBlock(block(324223, i)); 157 | auto b1 = enc1.ecbEncBlock(block(324223, i)); 158 | 159 | if (b0 != b1) 160 | throw RTE_LOC; 161 | } 162 | } 163 | 164 | void AES_EncDec_Test() 165 | { 166 | 167 | #ifdef OC_ENABLE_PORTABLE_AES 168 | test(); 169 | #endif // ENABLE_PORTABLE_AES 170 | #ifdef OC_ENABLE_AESNI 171 | test(); 172 | #endif // ENABLE_SSE 173 | #ifdef ENABLE_ARM_AES 174 | test(); 175 | #endif // ENABLE_ARM_AES 176 | 177 | #if defined(OC_ENABLE_AESNI) && defined(OC_ENABLE_PORTABLE_AES) 178 | compare(); 179 | #endif 180 | 181 | #if defined(ENABLE_ARM_AES) && defined(OC_ENABLE_PORTABLE_AES) 182 | compare(); 183 | #endif 184 | 185 | } 186 | 187 | } 188 | -------------------------------------------------------------------------------- /tests_cryptoTools/AES_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | 4 | namespace tests_cryptoTools 5 | { 6 | 7 | void AES_EncDec_Test(); 8 | } -------------------------------------------------------------------------------- /tests_cryptoTools/BtChannel_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | 8 | namespace tests_cryptoTools 9 | { 10 | 11 | #ifdef ENABLE_BOOST 12 | 13 | void BtNetwork_Connect1_Test(const osuCrypto::CLP& cmd); 14 | void BtNetwork_BadConnect_Test(const osuCrypto::CLP& cmd); 15 | void BtNetwork_PartialConnect_Test(const osuCrypto::CLP& cmd); 16 | 17 | void BtNetwork_shutdown_test(const osuCrypto::CLP& cmd); 18 | 19 | 20 | void BtNetwork_RapidConnect_Test(const osuCrypto::CLP& cmd); 21 | void BtNetwork_OneMegabyteSend_Test(const osuCrypto::CLP& cmd); 22 | void BtNetwork_ConnectMany_Test(const osuCrypto::CLP& cmd); 23 | void BtNetwork_CrossConnect_Test(const osuCrypto::CLP& cmd); 24 | void BtNetwork_ManySessions_Test(const osuCrypto::CLP& cmd); 25 | 26 | 27 | void BtNetwork_AsyncConnect_Test(const osuCrypto::CLP& cmd); 28 | void BtNetwork_std_Containers_Test(const osuCrypto::CLP& cmd); 29 | void BtNetwork_bitVector_Test(const osuCrypto::CLP& cmd); 30 | 31 | 32 | void BtNetwork_recvErrorHandler_Test(const osuCrypto::CLP& cmd); 33 | void BtNetwork_closeOnError_Test(const osuCrypto::CLP& cmd); 34 | void BtNetwork_clientClose_Test(const osuCrypto::CLP& cmd); 35 | 36 | 37 | void BtNetwork_SocketInterface_Test(const osuCrypto::CLP& cmd); 38 | 39 | void BtNetwork_AnonymousMode_Test(const osuCrypto::CLP& cmd); 40 | void BtNetwork_ServerMode_Test(const osuCrypto::CLP& cmd); 41 | void BtNetwork_CancelChannel_Test(const osuCrypto::CLP& cmd); 42 | 43 | 44 | void BtNetwork_oneWorker_Test(const osuCrypto::CLP& cmd); 45 | void BtNetwork_useAfterCancel_test(const osuCrypto::CLP& cmd); 46 | void BtNetwork_fastCancel(const osuCrypto::CLP& cmd); 47 | 48 | void BtNetwork_socketAdapter_test(const osuCrypto::CLP& cmd); 49 | void BtNetwork_BasicSocket_test(const osuCrypto::CLP&cmd); 50 | 51 | void SBO_ptr_test(); 52 | void BtNetwork_queue_Test(const osuCrypto::CLP& cmd); 53 | #else 54 | inline void np() { throw oc::UnitTestSkipped("ENABLE_BOOST not defined."); } 55 | inline void BtNetwork_Connect1_Test(const osuCrypto::CLP& cmd) { np(); } 56 | inline void BtNetwork_BadConnect_Test(const osuCrypto::CLP& cmd) { np(); } 57 | inline void BtNetwork_PartialConnect_Test(const osuCrypto::CLP& cmd) { np(); } 58 | inline void BtNetwork_shutdown_test(const osuCrypto::CLP& cmd) { np(); } 59 | inline void BtNetwork_RapidConnect_Test(const osuCrypto::CLP& cmd) { np(); } 60 | inline void BtNetwork_OneMegabyteSend_Test(const osuCrypto::CLP& cmd) { np(); } 61 | inline void BtNetwork_ConnectMany_Test(const osuCrypto::CLP& cmd) { np(); } 62 | inline void BtNetwork_CrossConnect_Test(const osuCrypto::CLP& cmd) { np(); } 63 | inline void BtNetwork_ManySessions_Test(const osuCrypto::CLP& cmd) { np(); } 64 | inline void BtNetwork_AsyncConnect_Test(const osuCrypto::CLP& cmd) { np(); } 65 | inline void BtNetwork_std_Containers_Test(const osuCrypto::CLP& cmd) { np(); } 66 | inline void BtNetwork_bitVector_Test(const osuCrypto::CLP& cmd) { np(); } 67 | inline void BtNetwork_recvErrorHandler_Test(const osuCrypto::CLP& cmd) { np(); } 68 | inline void BtNetwork_closeOnError_Test(const osuCrypto::CLP& cmd) { np(); } 69 | inline void BtNetwork_clientClose_Test(const osuCrypto::CLP& cmd) { np(); } 70 | inline void BtNetwork_SocketInterface_Test(const osuCrypto::CLP& cmd) { np(); } 71 | inline void BtNetwork_AnonymousMode_Test(const osuCrypto::CLP& cmd) { np(); } 72 | inline void BtNetwork_ServerMode_Test(const osuCrypto::CLP& cmd) { np(); } 73 | inline void BtNetwork_CancelChannel_Test(const osuCrypto::CLP& cmd) { np(); } 74 | inline void BtNetwork_oneWorker_Test(const osuCrypto::CLP& cmd) { np(); } 75 | inline void BtNetwork_useAfterCancel_test(const osuCrypto::CLP& cmd) { np(); } 76 | inline void BtNetwork_fastCancel(const osuCrypto::CLP& cmd) { np(); } 77 | inline void SBO_ptr_test() { np(); } 78 | inline void BtNetwork_queue_Test(const osuCrypto::CLP& cmd) { np(); } 79 | inline void BtNetwork_socketAdapter_test(const osuCrypto::CLP& cmd) { np(); } 80 | inline void BtNetwork_BasicSocket_test(const osuCrypto::CLP& cmd) { np(); }; 81 | 82 | #endif 83 | } -------------------------------------------------------------------------------- /tests_cryptoTools/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | file(GLOB_RECURSE SRCS *.cpp) 4 | include_directories(${CMAKE_SOURCE_DIR}) 5 | add_library(tests_cryptoTools STATIC ${SRCS}) 6 | 7 | # make projects that include cryptoTools use this as an include folder 8 | target_include_directories(tests_cryptoTools PUBLIC 9 | $ 10 | $) 11 | target_include_directories(tests_cryptoTools PUBLIC 12 | $ 13 | $) 14 | target_link_libraries(tests_cryptoTools cryptoTools) 15 | 16 | 17 | 18 | 19 | if(MSVC) 20 | target_compile_options(tests_cryptoTools PRIVATE $<$:/std:c++${CRYPTO_TOOLS_STD_VER}>) 21 | 22 | else() 23 | target_compile_options(tests_cryptoTools PRIVATE $<$:-std=c++${CRYPTO_TOOLS_STD_VER}>) 24 | endif() 25 | 26 | ############################################# 27 | # Install # 28 | ############################################# 29 | 30 | -------------------------------------------------------------------------------- /tests_cryptoTools/Circuit_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "cryptoTools/Common/CLP.h" 3 | 4 | 5 | void BetaCircuit_SequentialOp_Test(); 6 | void BetaCircuit_int_Adder_Test(); 7 | void BetaCircuit_int_Adder_const_Test(); 8 | void BetaCircuit_int_Subtractor_Test(); 9 | void BetaCircuit_int_Subtractor_const_Test(); 10 | void BetaCircuit_int_Multiply_Test(); 11 | void BetaCircuit_int_Divide_Test(); 12 | void BetaCircuit_int_LessThan_Test(); 13 | void BetaCircuit_int_GreaterThanEq_Test(); 14 | 15 | void BetaCircuit_negate_Test(); 16 | void BetaCircuit_bitInvert_Test(); 17 | void BetaCircuit_removeSign_Test(); 18 | void BetaCircuit_addSign_Test(); 19 | 20 | void BetaCircuit_uint_Adder_Test(); 21 | void BetaCircuit_uint_Subtractor_Test(); 22 | void BetaCircuit_uint_Multiply_Test(); 23 | void BetaCircuit_uint_LessThan_Test(); 24 | void BetaCircuit_uint_GreaterThanEq_Test(); 25 | 26 | void BetaCircuit_multiplex_Test(); 27 | 28 | void BetaCircuit_xor_and_lvl_test(const oc::CLP& cmd); 29 | 30 | void BetaCircuit_aes_test(); 31 | void BetaCircuit_json_Tests(); 32 | void BetaCircuit_bin_Tests(); 33 | 34 | oc::i64 signExtend(oc::i64 v, oc::u64 b); 35 | -------------------------------------------------------------------------------- /tests_cryptoTools/Common.cpp: -------------------------------------------------------------------------------- 1 | //#include "stdafx.h" 2 | #include "Common.h" 3 | #include 4 | 5 | #include 6 | #include 7 | 8 | using namespace osuCrypto; 9 | 10 | namespace tests_cryptoTools 11 | { 12 | static std::fstream* file = nullptr; 13 | std::string SolutionDir = "../.."; 14 | 15 | void InitDebugPrinting(std::string filePath) 16 | { 17 | std::cout << "changing sink" << std::endl; 18 | 19 | if (file == nullptr) 20 | { 21 | file = new std::fstream; 22 | } 23 | else 24 | { 25 | file->close(); 26 | } 27 | 28 | file->open(filePath, std::ios::trunc | std::ofstream::out); 29 | 30 | if (!file->is_open()) 31 | throw UnitTestFail(); 32 | 33 | //time_t now = time(0); 34 | 35 | std::cout.rdbuf(file->rdbuf()); 36 | std::cerr.rdbuf(file->rdbuf()); 37 | //Log::SetSink(*file); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /tests_cryptoTools/Common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | #include 4 | 5 | 6 | namespace tests_cryptoTools 7 | { 8 | 9 | // 10 | void InitDebugPrinting(std::string file = "../../testout.txt"); 11 | // 12 | extern std::string SolutionDir; 13 | 14 | class UnitTestFail : public std::exception 15 | { 16 | std::string mWhat; 17 | public: 18 | explicit UnitTestFail(std::string reason) 19 | :std::exception(), 20 | mWhat(reason) 21 | {} 22 | 23 | explicit UnitTestFail() 24 | :std::exception(), 25 | mWhat("UnitTestFailed exception") 26 | { 27 | } 28 | 29 | virtual const char* what() const throw() 30 | { 31 | return mWhat.c_str(); 32 | } 33 | }; 34 | } 35 | -------------------------------------------------------------------------------- /tests_cryptoTools/Cuckoo_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace tests_cryptoTools 4 | { 5 | void CuckooIndex_many_Test_Impl(); 6 | void CuckooIndex_paramSweep_Test_Impl(); 7 | void CuckooIndex_parallel_Test_Impl(); 8 | 9 | //void CuckooIndexVsCuckooHasher(); 10 | } -------------------------------------------------------------------------------- /tests_cryptoTools/Misc_Tests.cpp: -------------------------------------------------------------------------------- 1 | #include "Misc_Tests.h" 2 | 3 | #include 4 | #include "Common.h" 5 | 6 | using namespace osuCrypto; 7 | 8 | namespace tests_cryptoTools 9 | { 10 | void BitVector_Indexing_Test_Impl() 11 | { 12 | BitVector bb(128); 13 | std::vectorgold(128); 14 | 15 | 16 | for (u64 i : std::vector{ { 2,33,34,26,85,33,99,12,126 } }) 17 | { 18 | bb[i] = gold[i] = true; 19 | } 20 | 21 | 22 | for (auto i = 0; i < 128; ++i) 23 | { 24 | if ((bb[i] > 0) != gold[i]) 25 | throw std::runtime_error(""); 26 | 27 | if ((bb[i] > 0) != gold[i]) 28 | throw UnitTestFail(); 29 | } 30 | } 31 | 32 | void BitVector_Parity_Test_Impl() 33 | { 34 | PRNG prng(ZeroBlock); 35 | for (u64 i = 0; i < 100; ++i) 36 | { 37 | u8 size = prng.get(); 38 | u8 parity = 0; 39 | u64 sum = 0; 40 | BitVector bv(size); 41 | 42 | bv.randomize(prng); 43 | 44 | for (u64 j = 0; j < size; ++j) 45 | { 46 | parity ^= bv[j]; 47 | sum += bv[j]; 48 | } 49 | 50 | if (sum != bv.hammingWeight()) 51 | throw UnitTestFail(); 52 | 53 | if (parity != bv.parity()) 54 | throw UnitTestFail(); 55 | } 56 | 57 | } 58 | 59 | void BitVector_Append_Test_Impl() 60 | { 61 | 62 | BitVector bv0(3); 63 | BitVector bv1(6); 64 | BitVector bv2(9); 65 | BitVector bv4; 66 | 67 | 68 | bv0[0] = 1; bv2[0] = 1; 69 | bv0[2] = 1; bv2[2] = 1; 70 | bv1[2] = 1; bv2[3 + 2] = 1; 71 | bv1[5] = 1; bv2[3 + 5] = 1; 72 | 73 | bv4.append(bv0); 74 | bv4.append(bv1); 75 | 76 | //std::cout << bv0 << bv1 << std::endl; 77 | //std::cout << bv2 << std::endl; 78 | //std::cout << bv4 << std::endl; 79 | 80 | if (bv4 != bv2) 81 | throw UnitTestFail(); 82 | } 83 | 84 | 85 | void BitVector_Copy_Test_Impl() 86 | { 87 | u64 offset = 3; 88 | BitVector bb(128), c(128 - offset); 89 | 90 | 91 | for (u64 i : std::vector{ { 2,33,34,26,85,33,99,12,126 } }) 92 | { 93 | bb[i] = true; 94 | } 95 | 96 | c.copy(bb, offset, 128 - offset); 97 | 98 | 99 | ////std::cout << "bb ";// << bb << Logger::endl; 100 | //for (u64 i = 0; i < bb.size(); ++i) 101 | //{ 102 | // if (bb[i]) std::cout << "1"; 103 | // else std::cout << "0"; 104 | 105 | //} 106 | //std::cout << std::endl; 107 | //std::cout << "c "; 108 | //for (u64 i = 0; i < c.size(); ++i) 109 | //{ 110 | // if (c[i]) std::cout << "1"; 111 | // else std::cout << "0"; 112 | 113 | //} 114 | //std::cout << std::endl; 115 | 116 | for (u64 i = 0; i < 128 - offset; ++i) 117 | { 118 | if (bb[i + offset] != c[i]) 119 | throw std::runtime_error(""); 120 | 121 | } 122 | } 123 | 124 | void BitVector_Resize_Test_Impl() 125 | { 126 | u64 size0 = 9; 127 | BitVector bb(size0); 128 | 129 | u64 size1 = 11; 130 | bb.resize(size1, 1); 131 | 132 | u64 size2 = 13; 133 | bb.resize(size2, 0); 134 | 135 | u64 size3 = 31; 136 | bb.resize(size3, 1); 137 | 138 | for (u64 i{ 0 }; i < size0; ++i) 139 | if (bb[i])throw std::runtime_error(LOCATION); 140 | 141 | for (u64 i{ size0 }; i < size1; ++i) 142 | if (!bb[i])throw std::runtime_error(LOCATION); 143 | 144 | for (u64 i{ size1 }; i < size2; ++i) 145 | if (bb[i])throw std::runtime_error(LOCATION); 146 | 147 | for (u64 i{ size2 }; i < size3; ++i) 148 | if (!bb[i])throw std::runtime_error(LOCATION); 149 | 150 | 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /tests_cryptoTools/Misc_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace tests_cryptoTools 4 | { 5 | 6 | 7 | void BitVector_Indexing_Test_Impl(); 8 | void BitVector_Parity_Test_Impl(); 9 | void BitVector_Append_Test_Impl(); 10 | void BitVector_Copy_Test_Impl(); 11 | void BitVector_Resize_Test_Impl(); 12 | } -------------------------------------------------------------------------------- /tests_cryptoTools/MxCircuit_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "cryptoTools/Common/CLP.h" 4 | 5 | void MxCircuit_Bit_Ops_Test(const oc::CLP& cmd); 6 | void MxCircuit_BInt_Ops_Test(const oc::CLP& cmd); 7 | void MxCircuit_BUInt_Ops_Test(const oc::CLP& cmd); 8 | void MxCircuit_BDynInt_Ops_Test(const oc::CLP& cmd); 9 | void MxCircuit_BDynUInt_Ops_Test(const oc::CLP& cmd); 10 | void MxCircuit_Cast_Test(const oc::CLP& cmd); 11 | void MxCircuit_asBetaCircuit_Test(const oc::CLP& cmd); 12 | void MxCircuit_parallelPrefix_Test(const oc::CLP& cmd); 13 | void MxCircuit_rippleAdder_Test(const oc::CLP& cmd); 14 | void MxCircuit_parallelSummation_Test(const oc::CLP& cmd); 15 | void MxCircuit_multiply_Test(const oc::CLP& cmd); 16 | void MxCircuit_divideRemainder_Test(const oc::CLP& cmd); 17 | 18 | void MxCircuit_Subtractor_Test(); 19 | void MxCircuit_Subtractor_const_Test(); 20 | void MxCircuit_Multiply_Test(); 21 | void MxCircuit_Divide_Test(); 22 | void MxCircuit_LessThan_Test(); 23 | void MxCircuit_GreaterThanEq_Test(); 24 | 25 | void MxCircuit_negate_Test(); 26 | void MxCircuit_bitInvert_Test(); 27 | void MxCircuit_removeSign_Test(); 28 | void MxCircuit_addSign_Test(); 29 | 30 | void MxCircuit_uint_Adder_Test(); 31 | void MxCircuit_uint_Subtractor_Test(); 32 | void MxCircuit_uint_Multiply_Test(); 33 | void MxCircuit_uint_LessThan_Test(); 34 | void MxCircuit_uint_GreaterThanEq_Test(); 35 | 36 | void MxCircuit_multiplex_Test(); 37 | 38 | void MxCircuit_xor_and_lvl_test(const oc::CLP& cmd); 39 | 40 | void MxCircuit_aes_test(); 41 | void MxCircuit_json_Tests(); 42 | void MxCircuit_bin_Tests(); 43 | -------------------------------------------------------------------------------- /tests_cryptoTools/REcc_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | 4 | namespace tests_cryptoTools 5 | { 6 | 7 | void REccpNumber_Test(); 8 | void REccpPoint_Test(); 9 | } -------------------------------------------------------------------------------- /tests_cryptoTools/Rijndael256_Tests.cpp: -------------------------------------------------------------------------------- 1 | //#include "stdafx.h" 2 | 3 | #include 4 | #ifdef OC_ENABLE_AESNI 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include "Common.h" 11 | #include 12 | #include 13 | 14 | using namespace osuCrypto; 15 | 16 | #include 17 | namespace tests_cryptoTools 18 | { 19 | void Rijndael256_EncDec_Test() 20 | { 21 | using Block = typename Rijndael256Enc::Block; 22 | 23 | const std::uint8_t userKeyArr[] = { 24 | 0x6e, 0x49, 0x0e, 0xe6, 0x2b, 0xa8, 0xf4, 0x0a, 25 | 0x95, 0x83, 0xff, 0xa1, 0x59, 0xa5, 0x9d, 0x33, 26 | 0x1d, 0xa6, 0x15, 0xcd, 0x1e, 0x8c, 0x75, 0xe1, 27 | 0xea, 0xe3, 0x35, 0xe4, 0x76, 0xed, 0xf1, 0xdf, 28 | }; 29 | const std::uint8_t ptxtArr[] = { 30 | 0x79, 0xfd, 0x3f, 0xf6, 0x5b, 0xa2, 0xfd, 0x26, 31 | 0x4d, 0xb4, 0x8a, 0xe6, 0x89, 0x07, 0x52, 0x25, 32 | 0x05, 0xa4, 0xa7, 0x83, 0xd7, 0xea, 0xe8, 0x27, 33 | 0xec, 0xb5, 0x3e, 0x5e, 0x76, 0x3d, 0x30, 0x37, 34 | }; 35 | const std::uint8_t expCtxtArr[] = { 36 | 0x25, 0x8d, 0xa5, 0xeb, 0xce, 0xf2, 0x4a, 0xa7, 37 | 0x41, 0xb5, 0xa2, 0xa0, 0x78, 0x86, 0x59, 0xfc, 38 | 0x0a, 0xcc, 0x3d, 0x25, 0x66, 0x58, 0x4f, 0xb6, 39 | 0x4d, 0xda, 0xef, 0x25, 0xc1, 0xcd, 0xe0, 0xee, 40 | }; 41 | 42 | Block userKey = Block256(userKeyArr); 43 | Block ptxt = Block256(ptxtArr); 44 | Block expCtxt = Block256(expCtxtArr); 45 | 46 | Rijndael256Enc encKey(userKey); 47 | 48 | auto ctxt = encKey.encBlock(ptxt); 49 | if (ctxt != expCtxt) 50 | throw UnitTestFail(); 51 | 52 | Rijndael256Dec decKey(encKey); 53 | 54 | auto ptxt2 = decKey.decBlock(ctxt); 55 | if (ptxt2 != ptxt) 56 | throw UnitTestFail(); 57 | 58 | size_t length = 1 << 10; 59 | 60 | std::vector data(length); 61 | std::vector ciphertext1(length); 62 | std::vector ciphertext2(length); 63 | 64 | for (size_t i = 0; i < length; ++i) 65 | { 66 | data[i] = Block256(i); 67 | 68 | ciphertext1[i] = encKey.encBlock(data[i]); 69 | ptxt = decKey.decBlock(ciphertext1[i]); 70 | 71 | if (data[i] != ptxt) 72 | throw UnitTestFail(); 73 | } 74 | 75 | encKey.encBlocks(data.data(), data.size(), ciphertext2.data()); 76 | 77 | for (size_t i = 0; i < length; ++i) 78 | if (ciphertext1[i] != ciphertext2[i]) 79 | throw UnitTestFail(); 80 | 81 | std::vector plaintext = std::move(ciphertext2); 82 | decKey.decBlocks(ciphertext1.data(), ciphertext1.size(), plaintext.data()); 83 | 84 | for (size_t i = 0; i < length; ++i) 85 | if (data[i] != plaintext[i]) 86 | throw UnitTestFail(); 87 | } 88 | } 89 | 90 | #endif // ENABLE_AESNI 91 | -------------------------------------------------------------------------------- /tests_cryptoTools/Rijndael256_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. 3 | 4 | #ifdef OC_ENABLE_AESNI 5 | namespace tests_cryptoTools 6 | { 7 | void Rijndael256_EncDec_Test(); 8 | } 9 | #endif // ENABLE_AESNI 10 | -------------------------------------------------------------------------------- /tests_cryptoTools/SimpleCuckoo.h: -------------------------------------------------------------------------------- 1 | //#pragma once 2 | //#include "cryptoTools/Common/Defines.h" 3 | //#include "cryptoTools/Common/Log.h" 4 | //#include "cryptoTools/Common/BitVector.h" 5 | // 6 | //#include "cryptoTools/Common/Matrix.h" 7 | ////#include 8 | //#include 9 | ////#define THREAD_SAFE_CUCKOO 10 | //#include "cryptoTools/Common/CuckooIndex.h" 11 | // 12 | //namespace osuCrypto 13 | //{ 14 | // 15 | // class SimpleCuckoo 16 | // { 17 | // public: 18 | // SimpleCuckoo(); 19 | // ~SimpleCuckoo(); 20 | // 21 | // struct Bin 22 | // { 23 | // Bin() :mVal(-1) {} 24 | // Bin(u64 idx, u64 hashIdx) : mVal(idx | (hashIdx << 56)) {} 25 | // 26 | // bool isEmpty() const; 27 | // u64 idx() const; 28 | // u64 hashIdx() const; 29 | // 30 | // void swap(u64& idx, u64& hashIdx); 31 | //#ifdef THREAD_SAFE_CUCKOO 32 | // Bin(const Bin& b) : mVal(b.mVal.load(std::memory_order_relaxed)) {} 33 | // Bin(Bin&& b) : mVal(b.mVal.load(std::memory_order_relaxed)) {} 34 | // std::atomic mVal; 35 | //#else 36 | // Bin(const Bin& b) : mVal(b.mVal) {} 37 | // Bin(Bin&& b) : mVal(b.mVal) {} 38 | // u64 mVal; 39 | //#endif 40 | // }; 41 | // struct Workspace 42 | // { 43 | // Workspace(u64 n, u64 h) 44 | // : curAddrs(n) 45 | // , curHashIdxs(n) 46 | // , oldVals(n) 47 | // , findVal(n, h) 48 | // {} 49 | // 50 | // std::vector 51 | // curAddrs, 52 | // curHashIdxs, 53 | // oldVals; 54 | // 55 | // Matrix findVal; 56 | // }; 57 | // 58 | // 59 | // 60 | // u64 mTotalTries; 61 | // 62 | // bool operator==(const SimpleCuckoo& cmp)const; 63 | // bool operator!=(const SimpleCuckoo& cmp)const; 64 | // 65 | // //std::mutex mStashx; 66 | // 67 | // CuckooParam mParams; 68 | // 69 | // void print() const; 70 | // void init(); 71 | // 72 | // void insert(span itemIdxs, span hashs) 73 | // { 74 | // Workspace ws(itemIdxs.size(), mParams.mNumHashes); 75 | // std::vector bb(mParams.mNumHashes); 76 | // Matrix hh(hashs.size(), mParams.mNumHashes); 77 | // 78 | // for (i64 i = 0; i < hashs.size(); ++i) 79 | // { 80 | // //AES aes(hashs[i]); 81 | // //aes.ecbEncCounterMode(0, bb.size(), bb.data()); 82 | // for (u64 j = 0; j < mParams.mNumHashes; ++j) 83 | // { 84 | // //hh(i, j) = *(u64*)&bb[j]; 85 | // hh(i,j) = CuckooIndex<>::getHash(hashs[i], j, mParams.numBins()); 86 | // } 87 | // } 88 | // 89 | // insertBatch(itemIdxs, hh, ws); 90 | // } 91 | // void insertBatch(span itemIdxs, MatrixView hashs, Workspace& workspace); 92 | // 93 | // u64 findBatch(MatrixView hashes, 94 | // span idxs, 95 | // Workspace& wordkspace); 96 | // 97 | // 98 | // u64 stashUtilization(); 99 | // 100 | // std::vector mLocations; 101 | // MatrixView mHashesView; 102 | // 103 | // std::vector mBins; 104 | // std::vector mStash; 105 | // 106 | // //std::vector mBins; 107 | // //std::vector mStash; 108 | // 109 | // 110 | // //void insertItems(std::array,4>& hashs); 111 | // }; 112 | // 113 | //} 114 | -------------------------------------------------------------------------------- /tests_cryptoTools/UnitTests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | 6 | namespace tests_cryptoTools 7 | { 8 | extern osuCrypto::TestCollection Tests; 9 | } -------------------------------------------------------------------------------- /tests_cryptoTools/WolfSSL_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | 5 | void wolfSSL_echoServer_test(const osuCrypto::CLP& cmd); 6 | void wolfSSL_mutualAuth_test(const osuCrypto::CLP& cmd); 7 | void wolfSSL_channel_test(const osuCrypto::CLP& cmd); 8 | void wolfSSL_CancelChannel_Test(); -------------------------------------------------------------------------------- /tests_cryptoTools/block_Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | namespace tests_cryptoTools 3 | { 4 | void block_operation_test(); 5 | }; 6 | 7 | -------------------------------------------------------------------------------- /tests_cryptoTools/cmakeTests/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | project(cmakeTest) 3 | add_executable(main main.cpp) 4 | 5 | find_package(cryptoTools REQUIRED HINTS ${CRYPTOTOOLS_HINT}) 6 | 7 | target_link_libraries(main oc::cryptoTools) 8 | 9 | 10 | if(MSVC) 11 | target_compile_options(main PRIVATE $<$:/std:c++${CRYPTO_TOOLS_STD_VER}>) 12 | 13 | else() 14 | target_compile_options(main PRIVATE $<$:-std=c++${CRYPTO_TOOLS_STD_VER}>) 15 | endif() -------------------------------------------------------------------------------- /tests_cryptoTools/cmakeTests/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include "cryptoTools/Crypto/PRNG.h" 4 | 5 | int main() 6 | { 7 | using namespace oc; 8 | PRNG prng(oc::ZeroBlock); 9 | std::cout << prng.get() << std::endl; 10 | return 0; 11 | } -------------------------------------------------------------------------------- /thirdparty/fetch.cmake: -------------------------------------------------------------------------------- 1 | 2 | 3 | function(RUN) 4 | cmake_parse_arguments( 5 | PARSED_ARGS # prefix of parameters 6 | "" # list of names of the boolean arguments (only defined ones will be true) 7 | "WD" # list of names of mono-valued arguments 8 | "CMD;NAME" # list of names of multi-valued arguments (output variables are lists) 9 | ${ARGN} # arguments of the function to parse, here we take the all original ones 10 | ) 11 | message("${PARSED_ARGS_NAME}") 12 | 13 | 14 | execute_process( 15 | COMMAND ${PARSED_ARGS_CMD} 16 | WORKING_DIRECTORY ${PARSED_ARGS_WD} 17 | RESULT_VARIABLE RESULT 18 | COMMAND_ECHO STDOUT 19 | ) 20 | if(RESULT) 21 | message(FATAL_ERROR "${PARSED_ARGS_NAME} failed (${RESULT}).") 22 | endif() 23 | endfunction() 24 | 25 | set(FINDVS_PATH ${CMAKE_CURRENT_LIST_DIR}/findvs.ps1) 26 | 27 | file(READ ${FINDVS_PATH} FINDVS) 28 | 29 | function(VSRUN) 30 | cmake_parse_arguments( 31 | PARSED_ARGS # prefix of parameters 32 | "" # list of names of the boolean arguments (only defined ones will be true) 33 | "WD" # list of names of mono-valued arguments 34 | "CMD;NAME" # list of names of multi-valued arguments (output variables are lists) 35 | ${ARGN} # arguments of the function to parse, here we take the all original ones 36 | ) 37 | message("${PARSED_ARGS_NAME}") 38 | 39 | set(TEMP_PATH "${CMAKE_CURRENT_LIST_DIR}/runvs-${PARSED_ARGS_NAME}_delete-me.ps1") 40 | file(WRITE ${TEMP_PATH} "${FINDVS}\n\n" ${PARSED_ARGS_CMD}) 41 | 42 | find_program(POWERSHELL 43 | NAMES powershell 44 | REQUIRED 45 | ) 46 | 47 | set(BUILD_CMD "${POWERSHELL}" "${TEMP_PATH}") 48 | 49 | 50 | execute_process( 51 | COMMAND ${BUILD_CMD} 52 | WORKING_DIRECTORY ${PARSED_ARGS_WD} 53 | RESULT_VARIABLE RESULT 54 | COMMAND_ECHO STDOUT 55 | ) 56 | 57 | if(RESULT) 58 | message(FATAL_ERROR "${PARSED_ARGS_NAME} failed (${RESULT})") 59 | endif() 60 | 61 | if(NOT DEFINED VSRUN_NO_DEL) 62 | file(REMOVE ${TEMP_PATH}) 63 | endif() 64 | endfunction() 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | if(NOT MSVC AND SUDO_FETCH) 73 | set(SUDO "sudo ") 74 | endif() 75 | 76 | if(NOT DEFINED PARALLEL_FETCH) 77 | include(ProcessorCount) 78 | ProcessorCount(NUM_PROCESSORS) 79 | if(NOT NUM_PROCESSORS EQUAL 0) 80 | set(PARALLEL_FETCH ${NUM_PROCESSORS}) 81 | else() 82 | set(PARALLEL_FETCH 1) 83 | endif() 84 | endif() -------------------------------------------------------------------------------- /thirdparty/findvs.ps1: -------------------------------------------------------------------------------- 1 | # 2 | # Find vswhere (installed with recent Visual Studio versions). 3 | # 4 | If ($vsWhere = Get-Command "vswhere.exe" -ErrorAction SilentlyContinue) { 5 | $vsWhere = $vsWhere.Path 6 | } ElseIf (Test-Path "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe") { 7 | $vsWhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" 8 | } 9 | Else { 10 | $bbb = Test-Path "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" 11 | Write-Error "vswhere not found. Aborting. $bbb" -ErrorAction Stop 12 | } 13 | Write-Host "vswhere found at: $vsWhere" -ForegroundColor Yellow 14 | 15 | 16 | # 17 | # Get path to Visual Studio installation using vswhere. 18 | # 19 | $vsPath = &$vsWhere -version '[17.0,19.0)' -products * -requires Microsoft.Component.MSBuild -property installationPath -prerelease 20 | If ([string]::IsNullOrEmpty("$vsPath")) { 21 | Write-Error "Failed to find Visual Studio installation. Aborting." -ErrorAction Stop 22 | } 23 | Write-Host "Using Visual Studio installation at: ${vsPath}" -ForegroundColor Yellow 24 | 25 | 26 | # 27 | # Make sure the Visual Studio Command Prompt variables are set. 28 | # 29 | If (Test-Path env:LIBPATH) { 30 | Write-Host "Visual Studio Command Prompt variables already set." -ForegroundColor Yellow 31 | } Else { 32 | # Load VC vars 33 | Push-Location "${vsPath}\VC\Auxiliary\Build" 34 | cmd /c "vcvarsall.bat x64&set" | 35 | ForEach-Object { 36 | If ($_ -match "=") { 37 | $v = $_.split("="); Set-Item -Force -Path "ENV:\$($v[0])" -Value "$($v[1])" 38 | } 39 | } 40 | Pop-Location 41 | Write-Host "Visual Studio Command Prompt variables set." -ForegroundColor Yellow 42 | } -------------------------------------------------------------------------------- /thirdparty/getCoproto.cmake: -------------------------------------------------------------------------------- 1 | 2 | set(USER_NAME ) 3 | set(TOKEN ) 4 | #set(GIT_REPOSITORY "https://github.com/Visa-Research/coproto.git") 5 | set(GIT_REPOSITORY "https://github.com/ladnir/coproto.git") 6 | 7 | if(DEFINED COPROTO_GIT_TAG) 8 | set(GIT_TAG ${COPROTO_GIT_TAG}) 9 | else() 10 | set(GIT_TAG "adcfcc47e86190fd26be49d37caefcff9020f6b9" ) 11 | endif() 12 | 13 | set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/coproto") 14 | set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") 15 | set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-coproto.txt") 16 | 17 | 18 | include("${CMAKE_CURRENT_LIST_DIR}/fetch.cmake") 19 | if(NOT DEFINED FETCH_BOOST) 20 | set(LOCAL_COPROTO_FETCH_BOOST ${ENABLE_BOOST}) 21 | else() 22 | set(LOCAL_COPROTO_FETCH_BOOST ${FETCH_BOOST}) 23 | endif() 24 | 25 | string (REPLACE ";" "%" CMAKE_PREFIX_PATH_STR "${CMAKE_PREFIX_PATH}") 26 | find_program(GIT git REQUIRED) 27 | set(DOWNLOAD_CMD ${GIT} clone ${GIT_REPOSITORY}) 28 | set(CHECK_TAG_CMD ${GIT} show-ref --tags ${GIT_TAG} --quiet) 29 | set(CHECKOUT_CMD ${GIT} checkout ${GIT_TAG}) 30 | #set(CONFIGURE_CMD ${CMAKE_COMMAND} -S ${CLONE_DIR} -B ${BUILD_DIR} -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} 31 | # "-DCMAKE_PREFIX_PATH=${CMAKE_PREFIX_PATH_STR}" 32 | # -DCOPROTO_NO_SYSTEM_PATH=${NO_SYSTEM_PATH} 33 | # -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} 34 | # -DVERBOSE_FETCH=true 35 | # -DCOPROTO_FETCH_SPAN=OFF 36 | # -DCOPROTO_FETCH_FUNCTION2=ON 37 | # -DCOPROTO_FETCH_MACORO=ON 38 | # -DCOPROTO_FETCH_BOOST=${LOCAL_COPROTO_FETCH_BOOST} 39 | # -DCOPROTO_ENABLE_BOOST=${ENABLE_BOOST} 40 | # -DCOPROTO_ENABLE_OPENSSL=${ENABLE_OPENSSL} 41 | # -DCOPROTO_CPP_VER=${CRYPTO_TOOLS_STD_VER} 42 | # -DCOPROTO_PIC=${ENABLE_PIC} 43 | # -DCOPROTO_ASAN=${ENABLE_ASAN} 44 | # -DCOPROTO_THIRDPARTY_CLONE_DIR=${OC_THIRDPARTY_CLONE_DIR} 45 | # -DCOPROTO_STAGE=${OC_THIRDPARTY_INSTALL_PREFIX} 46 | # ) 47 | #set(BUILD_CMD ${CMAKE_COMMAND} --build ${BUILD_DIR} --config ${CMAKE_BUILD_TYPE}) 48 | #set(INSTALL_CMD ${CMAKE_COMMAND} --install ${BUILD_DIR} --config ${CMAKE_BUILD_TYPE} --prefix ${OC_THIRDPARTY_INSTALL_PREFIX}) 49 | 50 | 51 | message("============= Building coproto =============") 52 | if(NOT EXISTS ${CLONE_DIR}) 53 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${OC_THIRDPARTY_CLONE_DIR}) 54 | endif() 55 | 56 | execute_process( 57 | COMMAND ${CHECK_TAG_CMD} 58 | WORKING_DIRECTORY ${CLONE_DIR} 59 | RESULT_VARIABLE CHECK_TAG_REUSLT 60 | COMMAND_ECHO STDOUT 61 | ) 62 | message("CHECK_TAG_REUSLT=${CHECK_TAG_REUSLT}") 63 | if(CHECK_TAG_REUSLT) 64 | 65 | execute_process( 66 | COMMAND ${GIT} fetch 67 | WORKING_DIRECTORY ${CLONE_DIR} 68 | COMMAND_ECHO STDOUT 69 | ) 70 | endif() 71 | 72 | run(NAME "Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) 73 | #run(NAME "Configure" CMD ${CONFIGURE_CMD} WD ${CLONE_DIR}) 74 | #run(NAME "Build" CMD ${BUILD_CMD} WD ${CLONE_DIR}) 75 | #run(NAME "Install" CMD ${INSTALL_CMD} WD ${CLONE_DIR}) 76 | 77 | SET(COPROTO_NO_SYSTEM_PATH ${NO_SYSTEM_PATH} ) 78 | SET(COPROTO_FETCH_SPAN OFF ) 79 | SET(COPROTO_FETCH_FUNCTION2 ON ) 80 | SET(COPROTO_FETCH_MACORO ON ) 81 | SET(COPROTO_FETCH_BOOST ${LOCAL_COPROTO_FETCH_BOOST} ) 82 | SET(COPROTO_ENABLE_BOOST ${ENABLE_BOOST} ) 83 | SET(COPROTO_ENABLE_OPENSSL ${ENABLE_OPENSSL} ) 84 | SET(COPROTO_CPP_VER ${CRYPTO_TOOLS_STD_VER} ) 85 | SET(COPROTO_PIC ${ENABLE_PIC} ) 86 | SET(COPROTO_ASAN ${ENABLE_ASAN} ) 87 | SET(COPROTO_THIRDPARTY_CLONE_DIR ${OC_THIRDPARTY_CLONE_DIR} ) 88 | SET(COPROTO_STAGE ${OC_THIRDPARTY_INSTALL_PREFIX} ) 89 | 90 | add_subdirectory(${CLONE_DIR} ${CMAKE_BINARY_DIR}/coproto) 91 | 92 | -------------------------------------------------------------------------------- /thirdparty/getLibDivide.cmake: -------------------------------------------------------------------------------- 1 | set(DEP_NAME libdivide) 2 | set(GIT_REPOSITORY https://github.com/ridiculousfish/libdivide.git) 3 | set(GIT_TAG "v5.2.0" ) 4 | 5 | set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/${DEP_NAME}") 6 | set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") 7 | set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-${DEP_NAME}.txt") 8 | 9 | 10 | include("${CMAKE_CURRENT_LIST_DIR}/fetch.cmake") 11 | 12 | if(NOT LIBDIVIDE_FOUND) 13 | find_program(GIT git REQUIRED) 14 | set(DOWNLOAD_CMD ${GIT} clone ${GIT_REPOSITORY}) 15 | set(CHECKOUT_CMD ${GIT} checkout ${GIT_TAG}) 16 | 17 | 18 | 19 | message("============= Building ${DEP_NAME} =============") 20 | if(NOT EXISTS ${CLONE_DIR}) 21 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${OC_THIRDPARTY_CLONE_DIR}) 22 | endif() 23 | 24 | run(NAME "Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) 25 | message("Install: cp ${CLONE_DIR}/libdivide.h ${OC_THIRDPARTY_INSTALL_PREFIX}/include/") 26 | file(COPY ${CLONE_DIR}/libdivide.h DESTINATION ${OC_THIRDPARTY_INSTALL_PREFIX}/include/) 27 | message("log ${LOG_FILE}\n==========================================") 28 | else() 29 | message("${DEP_NAME} already fetched.") 30 | endif() 31 | 32 | install(CODE " 33 | if(NOT CMAKE_INSTALL_PREFIX STREQUAL \"${OC_THIRDPARTY_INSTALL_PREFIX}\" AND EXISTS ${CLONE_DIR}/libdivide.h) 34 | file(INSTALL ${CLONE_DIR}/libdivide.h DESTINATION \${CMAKE_INSTALL_PREFIX}/include/) 35 | endif() 36 | ") -------------------------------------------------------------------------------- /thirdparty/getRelic.cmake: -------------------------------------------------------------------------------- 1 | 2 | if(NOT DEFINED RELIC_GIT_REPOSITORY) 3 | set(RELIC_GIT_REPOSITORY https://github.com/relic-toolkit/relic.git ) 4 | endif() 5 | if(NOT DEFINED RELIC_GIT_TAG) 6 | set(RELIC_GIT_TAG "3b9a4a8ab2b854953d9982040fa1ca74f57c06c7" ) 7 | endif() 8 | set(GIT_REPOSITORY ${RELIC_GIT_REPOSITORY}) 9 | set(GIT_TAG ${RELIC_GIT_TAG}) 10 | 11 | set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/relic") 12 | set(BUILD_DIR "${CLONE_DIR}/build/${OC_CONFIG}") 13 | set(CONFIG --config Release) 14 | set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-relic.txt") 15 | 16 | if(MSVC) 17 | set(MP_ARG "-DMULTI:STRING=OPENMP") 18 | else() 19 | set(MP_ARG "-DMULTI:STRING=PTHREAD") 20 | endif() 21 | 22 | 23 | if(NOT MSVC AND ENABLE_PIC) 24 | set(PIC_ARG "-DCMAKE_C_FLAGS=-fPIC") 25 | endif() 26 | 27 | 28 | include("${CMAKE_CURRENT_LIST_DIR}/fetch.cmake") 29 | 30 | if(NOT EXISTS ${BUILD_DIR} OR NOT RELIC_FOUND) 31 | find_program(GIT git REQUIRED) 32 | set(DOWNLOAD_CMD ${GIT} clone ${GIT_REPOSITORY}) 33 | set(CHECKOUT_CMD ${GIT} checkout ${GIT_TAG}) 34 | set(CONFIGURE_CMD ${CMAKE_COMMAND} -S ${CLONE_DIR} -B ${BUILD_DIR} -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} 35 | -DCMAKE_BUILD_TYPE:STRING=Release 36 | ${MP_ARG} ${PIC_ARG}) 37 | set(BUILD_CMD ${CMAKE_COMMAND} --build ${BUILD_DIR} ${CONFIG}) 38 | set(INSTALL_CMD ${CMAKE_COMMAND} --install ${BUILD_DIR} ${CONFIG} --prefix ${OC_THIRDPARTY_INSTALL_PREFIX}) 39 | 40 | 41 | message("============= Building Relic =============") 42 | if(NOT EXISTS ${CLONE_DIR}) 43 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${OC_THIRDPARTY_CLONE_DIR}) 44 | endif() 45 | 46 | run(NAME "Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) 47 | run(NAME "Configure" CMD ${CONFIGURE_CMD} WD ${CLONE_DIR}) 48 | run(NAME "Build" CMD ${BUILD_CMD} WD ${CLONE_DIR}) 49 | run(NAME "Install" CMD ${INSTALL_CMD} WD ${CLONE_DIR}) 50 | 51 | message("log ${LOG_FILE}\n==========================================") 52 | else() 53 | message("relic already fetched.") 54 | endif() 55 | 56 | install(CODE " 57 | 58 | if(NOT CMAKE_INSTALL_PREFIX STREQUAL \"${OC_THIRDPARTY_INSTALL_PREFIX}\") 59 | execute_process( 60 | COMMAND ${SUDO} \${CMAKE_COMMAND} --install \"${BUILD_DIR}\" ${CONFIG} --prefix \${CMAKE_INSTALL_PREFIX} 61 | WORKING_DIRECTORY ${CLONE_DIR} 62 | RESULT_VARIABLE RESULT 63 | COMMAND_ECHO STDOUT 64 | ) 65 | endif() 66 | ") -------------------------------------------------------------------------------- /thirdparty/getSodium.cmake: -------------------------------------------------------------------------------- 1 | 2 | 3 | set(GIT_REPOSITORY https://github.com/osu-crypto/libsodium.git) 4 | set(GIT_TAG "778c9cf491fdeeef362512fb964db0943732f275" ) 5 | 6 | set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/libsodium") 7 | set(BUILD_DIR "${CLONE_DIR}/build/${OC_CONFIG}") 8 | set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-libsodium.txt") 9 | 10 | include("${CMAKE_CURRENT_LIST_DIR}/fetch.cmake") 11 | 12 | find_program(GIT git REQUIRED) 13 | set(DOWNLOAD_CMD ${GIT} clone ${GIT_REPOSITORY}) 14 | set(CHECKOUT_CMD ${GIT} checkout ${GIT_TAG}) 15 | 16 | 17 | if(NOT SODIUM_FOUND) 18 | message("============= Building Sodium =============") 19 | 20 | if(NOT EXISTS ${CLONE_DIR}) 21 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${OC_THIRDPARTY_CLONE_DIR}) 22 | endif() 23 | run(NAME "Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) 24 | 25 | if(MSVC) 26 | # delete the post build tests 27 | file(WRITE ${CLONE_DIR}/test/default/wintest.bat "") 28 | vsrun(NAME "build-sodium" CMD 29 | "MSBuild.exe ./libsodium.sln -t:libsodium -p:Configuration=Release /p:PlatformToolset=v${MSVC_TOOLSET_VERSION} /p:Platform=x64\n" 30 | "mkdir ${OC_THIRDPARTY_INSTALL_PREFIX}/include/ -Force\n" 31 | "mkdir ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/ -Force\n" 32 | "cp ./src/libsodium/include/* ${OC_THIRDPARTY_INSTALL_PREFIX}/include/ -Recurse -Force\n" 33 | "cp ./Build/Release/x64/libsodium.lib ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/ -Force\n" 34 | "mkdir ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/cmake/libsodium/ -Force\n" 35 | WD ${CLONE_DIR} 36 | ) 37 | 38 | if(NOT EXISTS "${CLONE_DIR}/Build/Release/x64/libsodium.lib") 39 | message(FATAL_ERROR "Sodium failed to build. See ${LOG_FILE}") 40 | endif() 41 | else() 42 | 43 | ## in case this is hosted in WSL 44 | find_program(DOS2UNIX dos2unix) 45 | if(DOS2UNIX) 46 | set(DOS2UNIX_CMD bash -c "find . \\( -name \"*.m4\" -o -name \"*.ac\" -o -name \"*.am\" -o -name \"*.sh\" \\) | xargs ${DOS2UNIX}") 47 | run(NAME "dos2unix" CMD ${DOS2UNIX_CMD} WD ${CLONE_DIR}) 48 | endif() 49 | 50 | #find_program(AUTOGEN autogen) 51 | #if(NOT AUTOGEN) 52 | # message(FATAL_ERROR "program autogen must be installed.") 53 | #endif() 54 | #find_program(LIBTOOL libtool) 55 | #if(NOT LIBTOOL) 56 | # message(FATAL_ERROR "program libtool must be installed.") 57 | #endif() 58 | 59 | if(ENABLE_PIC) 60 | set(WITH_PIC "--with-pic=yes") 61 | else() 62 | set(WITH_PIC "--with-pic=no") 63 | endif() 64 | 65 | 66 | set(AUTOGEN_CMD "./autogen.sh" "-s") 67 | set(CONFIGURE_CMD "./configure" "--prefix=${OC_THIRDPARTY_INSTALL_PREFIX}" ${WITH_PIC} "--verbose") 68 | set(BUILD_CMD "make" "-j" "${PARALLEL_FETCH}") 69 | set(INSTALL_CMD ${SUDO} "make" "install") 70 | 71 | if(NOT EXISTS ${CLONE_DIR}) 72 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${CMAKE_CURRENT_LIST_DIR}) 73 | endif() 74 | 75 | run(NAME "Autogen" CMD ${AUTOGEN_CMD} WD ${CLONE_DIR}) 76 | run(NAME "Configure" CMD ${CONFIGURE_CMD} WD ${CLONE_DIR}) 77 | run(NAME "Build" CMD ${BUILD_CMD} WD ${CLONE_DIR}) 78 | run(NAME "Install" CMD ${INSTALL_CMD} WD ${CLONE_DIR}) 79 | run(NAME "Install2" CMD "mkdir" "-p" "${OC_THIRDPARTY_INSTALL_PREFIX}/lib/cmake/libsodium" WD ${CLONE_DIR}) 80 | endif() 81 | 82 | file(WRITE ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/cmake/libsodium/libsodiumConfig.cmake "set(libsodium_pic ${ENABLE_PIC})") 83 | message("log ${LOG_FILE}\n==========================================") 84 | 85 | else() 86 | message("sodium already fetched.") 87 | endif() 88 | 89 | 90 | if(MSVC) 91 | install( 92 | DIRECTORY "${CLONE_DIR}/src/libsodium/include/" 93 | DESTINATION "include" 94 | FILES_MATCHING PATTERN "*.h") 95 | install( 96 | FILES "${CLONE_DIR}/Build/Release/x64/libsodium.lib" 97 | DESTINATION "lib") 98 | else() 99 | install(CODE " 100 | 101 | if(NOT CMAKE_INSTALL_PREFIX STREQUAL \"${OC_THIRDPARTY_INSTALL_PREFIX}\") 102 | execute_process( 103 | COMMAND ${SUDO} mkdir -p \${CMAKE_INSTALL_PREFIX}/lib/cmake/libsodium 104 | COMMAND ${SUDO} mkdir -p \${CMAKE_INSTALL_PREFIX}/include/sodium 105 | COMMAND ${SUDO} cp ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/libsodium.a \${CMAKE_INSTALL_PREFIX}/lib/ 106 | COMMAND ${SUDO} cp -r ${OC_THIRDPARTY_INSTALL_PREFIX}/lib/cmake/libsodium/libsodiumConfig.cmake \${CMAKE_INSTALL_PREFIX}/lib/cmake/libsodium/ 107 | COMMAND ${SUDO} cp ${OC_THIRDPARTY_INSTALL_PREFIX}/include/sodium.h \${CMAKE_INSTALL_PREFIX}/include/ 108 | COMMAND ${SUDO} cp -r ${OC_THIRDPARTY_INSTALL_PREFIX}/include/sodium \${CMAKE_INSTALL_PREFIX}/include/ 109 | WORKING_DIRECTORY \"${CLONE_DIR}\" 110 | RESULT_VARIABLE RESULT 111 | COMMAND_ECHO STDOUT 112 | ) 113 | endif() 114 | ") 115 | endif() -------------------------------------------------------------------------------- /thirdparty/getSpanLite.cmake: -------------------------------------------------------------------------------- 1 | 2 | set(DEP_NAME span-lite) 3 | set(GIT_REPOSITORY https://github.com/martinmoene/span-lite.git) 4 | set(GIT_TAG "2987dd8d3b8fe7c861e3c3f879234cc1c412f03f" ) 5 | 6 | set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/${DEP_NAME}") 7 | set(BUILD_DIR "${CLONE_DIR}/build/${OC_CONFIG}") 8 | set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-${DEP_NAME}.txt") 9 | 10 | include("${CMAKE_CURRENT_LIST_DIR}/fetch.cmake") 11 | 12 | if(NOT EXISTS ${BUILD_DIR} OR NOT span-lite_FOUND) 13 | find_program(GIT git REQUIRED) 14 | set(DOWNLOAD_CMD ${GIT} clone ${GIT_REPOSITORY}) 15 | set(CHECKOUT_CMD ${GIT} checkout ${GIT_TAG}) 16 | set(CONFIGURE_CMD ${CMAKE_COMMAND} -S ${CLONE_DIR} -B ${BUILD_DIR} -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} 17 | -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DSPAN_LITE_OPT_BUILD_TESTS=OFF) 18 | set(BUILD_CMD ${CMAKE_COMMAND} --build ${BUILD_DIR} --config ${CMAKE_BUILD_TYPE}) 19 | set(INSTALL_CMD ${CMAKE_COMMAND} --install ${BUILD_DIR} --config ${CMAKE_BUILD_TYPE} --prefix ${OC_THIRDPARTY_INSTALL_PREFIX}) 20 | 21 | 22 | message("============= Building ${DEP_NAME} =============") 23 | if(NOT EXISTS ${CLONE_DIR}) 24 | run(NAME "Cloning ${GIT_REPOSITORY}" CMD ${DOWNLOAD_CMD} WD ${OC_THIRDPARTY_CLONE_DIR}) 25 | endif() 26 | 27 | run(NAME "Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) 28 | run(NAME "Configure" CMD ${CONFIGURE_CMD} WD ${CLONE_DIR}) 29 | run(NAME "Build" CMD ${BUILD_CMD} WD ${CLONE_DIR}) 30 | run(NAME "Install" CMD ${INSTALL_CMD} WD ${CLONE_DIR}) 31 | 32 | message("log ${LOG_FILE}\n==========================================") 33 | else() 34 | message("${DEP_NAME} already fetched (cryptoTools).") 35 | endif() 36 | 37 | install(CODE " 38 | if(NOT CMAKE_INSTALL_PREFIX STREQUAL \"${OC_THIRDPARTY_INSTALL_PREFIX}\") 39 | execute_process( 40 | COMMAND ${SUDO} \${CMAKE_COMMAND} --install \"${BUILD_DIR}\" --config ${CMAKE_BUILD_TYPE} --prefix \${CMAKE_INSTALL_PREFIX} 41 | WORKING_DIRECTORY ${CLONE_DIR} 42 | RESULT_VARIABLE RESULT 43 | COMMAND_ECHO STDOUT 44 | ) 45 | endif() 46 | ") 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /title.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ladnir/cryptoTools/c2735302694ff4c0c44dff3732deb4d7e2fd304e/title.PNG --------------------------------------------------------------------------------