├── .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