├── .clang-format ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGES.md ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUES.md ├── LICENSE ├── NOTICE ├── README.md ├── SECURITY.md ├── android ├── .gitignore ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ├── cmake ├── CheckCXXIntrinsicsHeader.cmake ├── CheckCXXIntrinsicsSpecific.cmake ├── CheckMemset.cmake ├── CleanArtifacts.cmake ├── EnableCXX17.cmake ├── EnableCXXCompilerFlags.cmake ├── ExternalBenchmark.cmake ├── ExternalGTest.cmake ├── ExternalIntelHEXL.cmake ├── ExternalMSGSL.cmake ├── ExternalZLIB.cmake ├── ExternalZSTD.cmake ├── SEALConfig.cmake.in ├── SEALMacros.cmake └── functions.iOS.cmake ├── dotnet ├── SEALNet.sln.in ├── examples │ ├── 1_BFV_Basics.cs │ ├── 2_Encoders.cs │ ├── 3_Levels.cs │ ├── 4_BGV_Basics.cs │ ├── 5_CKKS_Basics.cs │ ├── 6_Rotation.cs │ ├── 7_Serialization.cs │ ├── 8_Performance.cs │ ├── Examples.cs │ ├── SEALNetExamples.csproj.in │ └── Utilities.cs ├── nuget │ ├── NUGET.md │ ├── SEALNet-multi.nuspec.in │ ├── SEALNet.nuspec.in │ └── SEALNet.targets ├── src │ ├── BatchEncoder.cs │ ├── CKKSEncoder.cs │ ├── Ciphertext.cs │ ├── Decryptor.cs │ ├── EncryptionParameterQualifiers.cs │ ├── EncryptionParameters.cs │ ├── Encryptor.cs │ ├── Evaluator.cs │ ├── GaloisKeys.cs │ ├── KSwitchKeys.cs │ ├── KeyGenerator.cs │ ├── MMProf.cs │ ├── MemoryManager.cs │ ├── MemoryPoolHandle.cs │ ├── Modulus.cs │ ├── NativeMethods.cs │ ├── ParmsId.cs │ ├── Plaintext.cs │ ├── PublicKey.cs │ ├── RelinKeys.cs │ ├── SEALContext.cs │ ├── SEALNet.csproj.in │ ├── SecretKey.cs │ ├── Serializable.cs │ ├── Serialization.cs │ ├── ValCheck.cs │ ├── Version.cs │ └── tools │ │ ├── DisposableObject.cs │ │ ├── NativeObject.cs │ │ └── Utilities.cs └── tests │ ├── BatchEncoderTests.cs │ ├── CKKSEncoderTests.cs │ ├── CiphertextTests.cs │ ├── DecryptorTests.cs │ ├── EncryptionParameterQualifiersTests.cs │ ├── EncryptionParametersTests.cs │ ├── EncryptorTests.cs │ ├── EvaluatorTests.cs │ ├── GaloisKeysTests.cs │ ├── GlobalContext.cs │ ├── KeyGeneratorTests.cs │ ├── MemoryManagerTests.cs │ ├── MemoryPoolHandleTests.cs │ ├── ModulusTests.cs │ ├── NativeObjectTests.cs │ ├── ParmsIdTests.cs │ ├── PlaintextTests.cs │ ├── PublicKeyTests.cs │ ├── RelinKeysTests.cs │ ├── SEALContextTests.cs │ ├── SEALNetTest.csproj.in │ ├── SecretKeyTests.cs │ ├── SerializationTests.cs │ ├── TestAssemblyCleanup.cs │ └── Utilities.cs ├── native ├── bench │ ├── CMakeLists.txt │ ├── bench.cpp │ ├── bench.h │ ├── bfv.cpp │ ├── bgv.cpp │ ├── ckks.cpp │ ├── keygen.cpp │ └── ntt.cpp ├── examples │ ├── 1_bfv_basics.cpp │ ├── 2_encoders.cpp │ ├── 3_levels.cpp │ ├── 4_bgv_basics.cpp │ ├── 5_ckks_basics.cpp │ ├── 6_rotation.cpp │ ├── 7_serialization.cpp │ ├── 8_performance.cpp │ ├── CMakeLists.txt │ ├── examples.cpp │ └── examples.h ├── src │ └── seal │ │ ├── CMakeLists.txt │ │ ├── batchencoder.cpp │ │ ├── batchencoder.h │ │ ├── c │ │ ├── CMakeLists.txt │ │ ├── batchencoder.cpp │ │ ├── batchencoder.h │ │ ├── ciphertext.cpp │ │ ├── ciphertext.h │ │ ├── ckksencoder.cpp │ │ ├── ckksencoder.h │ │ ├── contextdata.cpp │ │ ├── contextdata.h │ │ ├── decryptor.cpp │ │ ├── decryptor.h │ │ ├── defines.h │ │ ├── encryptionparameterqualifiers.cpp │ │ ├── encryptionparameterqualifiers.h │ │ ├── encryptionparameters.cpp │ │ ├── encryptionparameters.h │ │ ├── encryptor.cpp │ │ ├── encryptor.h │ │ ├── evaluator.cpp │ │ ├── evaluator.h │ │ ├── galoiskeys.cpp │ │ ├── galoiskeys.h │ │ ├── keygenerator.cpp │ │ ├── keygenerator.h │ │ ├── kswitchkeys.cpp │ │ ├── kswitchkeys.h │ │ ├── memorymanager.cpp │ │ ├── memorymanager.h │ │ ├── memorypoolhandle.cpp │ │ ├── memorypoolhandle.h │ │ ├── modulus.cpp │ │ ├── modulus.h │ │ ├── plaintext.cpp │ │ ├── plaintext.h │ │ ├── publickey.cpp │ │ ├── publickey.h │ │ ├── relinkeys.cpp │ │ ├── relinkeys.h │ │ ├── sealcontext.cpp │ │ ├── sealcontext.h │ │ ├── secretkey.cpp │ │ ├── secretkey.h │ │ ├── serialization.cpp │ │ ├── serialization.h │ │ ├── stdafx.cpp │ │ ├── stdafx.h │ │ ├── targetver.h │ │ ├── utilities.cpp │ │ ├── utilities.h │ │ ├── valcheck.cpp │ │ ├── valcheck.h │ │ ├── version.cpp │ │ └── version.h │ │ ├── ciphertext.cpp │ │ ├── ciphertext.h │ │ ├── ckks.cpp │ │ ├── ckks.h │ │ ├── context.cpp │ │ ├── context.h │ │ ├── decryptor.cpp │ │ ├── decryptor.h │ │ ├── dynarray.h │ │ ├── encryptionparams.cpp │ │ ├── encryptionparams.h │ │ ├── encryptor.cpp │ │ ├── encryptor.h │ │ ├── evaluator.cpp │ │ ├── evaluator.h │ │ ├── galoiskeys.h │ │ ├── keygenerator.cpp │ │ ├── keygenerator.h │ │ ├── kswitchkeys.cpp │ │ ├── kswitchkeys.h │ │ ├── memorymanager.cpp │ │ ├── memorymanager.h │ │ ├── modulus.cpp │ │ ├── modulus.h │ │ ├── plaintext.cpp │ │ ├── plaintext.h │ │ ├── publickey.h │ │ ├── randomgen.cpp │ │ ├── randomgen.h │ │ ├── randomtostd.h │ │ ├── relinkeys.h │ │ ├── seal.h │ │ ├── secretkey.h │ │ ├── serializable.h │ │ ├── serialization.cpp │ │ ├── serialization.h │ │ ├── util │ │ ├── CMakeLists.txt │ │ ├── blake2-impl.h │ │ ├── blake2.h │ │ ├── blake2b.c │ │ ├── blake2xb.c │ │ ├── cgmanifest.json │ │ ├── clang.h │ │ ├── clipnormal.cpp │ │ ├── clipnormal.h │ │ ├── common.cpp │ │ ├── common.h │ │ ├── config.h.in │ │ ├── croots.cpp │ │ ├── croots.h │ │ ├── defines.h │ │ ├── dwthandler.h │ │ ├── fips202.c │ │ ├── fips202.h │ │ ├── galois.cpp │ │ ├── galois.h │ │ ├── gcc.h │ │ ├── globals.cpp │ │ ├── globals.h │ │ ├── hash.cpp │ │ ├── hash.h │ │ ├── hestdparms.h │ │ ├── iterator.cpp │ │ ├── iterator.h │ │ ├── locks.h │ │ ├── mempool.cpp │ │ ├── mempool.h │ │ ├── msvc.h │ │ ├── ntt.cpp │ │ ├── ntt.h │ │ ├── numth.cpp │ │ ├── numth.h │ │ ├── pointer.h │ │ ├── polyarithsmallmod.cpp │ │ ├── polyarithsmallmod.h │ │ ├── polycore.h │ │ ├── rlwe.cpp │ │ ├── rlwe.h │ │ ├── rns.cpp │ │ ├── rns.h │ │ ├── scalingvariant.cpp │ │ ├── scalingvariant.h │ │ ├── streambuf.cpp │ │ ├── streambuf.h │ │ ├── uintarith.cpp │ │ ├── uintarith.h │ │ ├── uintarithmod.cpp │ │ ├── uintarithmod.h │ │ ├── uintarithsmallmod.cpp │ │ ├── uintarithsmallmod.h │ │ ├── uintcore.cpp │ │ ├── uintcore.h │ │ ├── ztools.cpp │ │ └── ztools.h │ │ ├── valcheck.cpp │ │ ├── valcheck.h │ │ └── version.h └── tests │ ├── CMakeLists.txt │ └── seal │ ├── CMakeLists.txt │ ├── batchencoder.cpp │ ├── ciphertext.cpp │ ├── ckks.cpp │ ├── context.cpp │ ├── dynarray.cpp │ ├── encryptionparams.cpp │ ├── encryptor.cpp │ ├── evaluator.cpp │ ├── galoiskeys.cpp │ ├── keygenerator.cpp │ ├── memorymanager.cpp │ ├── modulus.cpp │ ├── plaintext.cpp │ ├── publickey.cpp │ ├── randomgen.cpp │ ├── randomtostd.cpp │ ├── relinkeys.cpp │ ├── secretkey.cpp │ ├── serialization.cpp │ ├── testrunner.cpp │ └── util │ ├── CMakeLists.txt │ ├── clipnormal.cpp │ ├── common.cpp │ ├── galois.cpp │ ├── hash.cpp │ ├── iterator.cpp │ ├── locks.cpp │ ├── mempool.cpp │ ├── ntt.cpp │ ├── numth.cpp │ ├── polyarithsmallmod.cpp │ ├── polycore.cpp │ ├── rns.cpp │ ├── stringtouint64.cpp │ ├── uint64tostring.cpp │ ├── uintarith.cpp │ ├── uintarithmod.cpp │ ├── uintarithsmallmod.cpp │ └── uintcore.cpp ├── pipelines ├── android.yml ├── ios.yml ├── jobs.yml ├── nix.yml ├── nuget.yml ├── pipeline-CI-Debug-Android.yml ├── pipeline-CI-Debug-Linux.yml ├── pipeline-CI-Debug-Windows.yml ├── pipeline-CI-Debug-iOS.yml ├── pipeline-CI-Debug-macOS.yml ├── pipeline-CI-Release-All.yml ├── pipeline-PR-Debug-All.yml └── windows.yml ├── pkgconfig ├── seal.pc.in ├── seal_msgsl.pc.in └── seal_shared.pc.in └── tools ├── Makefile ├── config └── packages.config └── scripts ├── clang-format-all.sh └── collect_system_info.sh /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.0.0 4 | hooks: 5 | - id: check-added-large-files 6 | - id: trailing-whitespace 7 | - id: end-of-file-fixer 8 | - repo: local 9 | hooks: 10 | - id: clang-format 11 | name: clang-format 12 | entry: clang-format 13 | language: system 14 | files: \.(cpp|h)$ 15 | args: ["-i"] 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This project welcomes contributions and suggestions. 4 | Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. 5 | For details, visit https://cla.opensource.microsoft.com. 6 | 7 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 8 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/). 9 | Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) for any additional questions or comments. 10 | 11 | ### Pull Requests 12 | 13 | Submit pull requrests to **branch *contrib***. 14 | Pull requests to any other branch will not be accepted. 15 | 16 | When you submit a pull request, a CLA bot will automatically determine whether you need to **provide a CLA** and decorate the PR appropriately (e.g., status check, comment). 17 | Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. 18 | 19 | ### Formatting 20 | 21 | Microsoft SEAL uses a customized `.clang-format` configuration for C++ code styling. 22 | A script `tools/scripts/clang-format-all.sh` is provided to easily format all C++ sources and headers in the `native` directory. 23 | To ensure the code is properly formatted before making a pull request, we highly recommend using [pre-commit](https://pre-commit.com/). 24 | Note that the repository includes a `.pre-commit-config.yaml` that describes the appropriate formatting checks. 25 | 26 | Documentation are mostly written in GitHub-flavored Markdown. 27 | A line break is required after each full sentence. 28 | -------------------------------------------------------------------------------- /ISSUES.md: -------------------------------------------------------------------------------- 1 | # Issues 2 | 3 | ## Technical questions 4 | 5 | The best way to get help with technical questions is on 6 | [StackOverflow](https://stackoverflow.com/questions/tagged/seal) using the `[seal]` 7 | tag. To contact the Microsoft SEAL team directly, please email 8 | [sealcrypto@microsoft.com](mailto:sealcrypto@microsoft.com). 9 | 10 | ## Bug reports 11 | 12 | We appreciate community efforts to find and fix bugs and issues in Microsoft SEAL. 13 | If you believe you have found a bug or want to report some other issue, please 14 | do so on [GitHub](https://github.com/Microsoft/SEAL/issues). To help others 15 | determine what the problem may be, we provide a helpful script that collects 16 | relevant system information that you can submit with the bug report (see below). 17 | 18 | ### System information 19 | 20 | To collect system information for an improved bug report, please run 21 | ``` 22 | make -C tools system_info 23 | ``` 24 | This will result in a file `system_info.tar.gz` to be generated, which you can 25 | optionally attach with your bug report. 26 | 27 | ## Critical security issues 28 | 29 | For reporting critical security issues, see [SECURITY.md](SECURITY.md). 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | THIRD-PARTY SOFTWARE NOTICES AND INFORMATION 2 | 3 | This software incorporates components from the projects listed below. The original copyright notices 4 | and the licenses under which Microsoft received such components are set forth below and are provided for 5 | informational purposes only. Microsoft reserves all rights not expressly granted herein, whether by 6 | implication, estoppel or otherwise. 7 | 8 | This software includes parts of the BLAKE2 library (https://github.com/BLAKE2/BLAKE2). 9 | The BLAKE2 library is licensed under CC0 Universal, version 1.0. You can find a copy of this license at https://creativecommons.org/publicdomain/zero/1.0/legalcode 10 | 11 | This software includes parts of the Kyber library (https://github.com/pq-crystals/kyber). 12 | The Kyber library is licensed under CC0 Universal, version 1.0. You can find a copy of this license at https://creativecommons.org/publicdomain/zero/1.0/legalcode 13 | 14 | This software includes parts of the ZSTD library, version 1.4.5 (https://github.com/facebook/zstd): 15 | ZSTD NOTICES AND INFORMATION BEGIN HERE 16 | =============================================================================== 17 | BSD License 18 | 19 | For Zstandard software 20 | 21 | Copyright (c) 2016-present, Facebook, Inc. All rights reserved. 22 | 23 | Redistribution and use in source and binary forms, with or without modification, 24 | are permitted provided that the following conditions are met: 25 | 26 | * Redistributions of source code must retain the above copyright notice, this 27 | list of conditions and the following disclaimer. 28 | 29 | * Redistributions in binary form must reproduce the above copyright notice, 30 | this list of conditions and the following disclaimer in the documentation 31 | and/or other materials provided with the distribution. 32 | 33 | * Neither the name Facebook nor the names of its contributors may be used to 34 | endorse or promote products derived from this software without specific 35 | prior written permission. 36 | 37 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 38 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 39 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 40 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 41 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 42 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 43 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 44 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 45 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 46 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 47 | =============================================================================== 48 | END OF ZSTD NOTICES AND INFORMATION 49 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Correct Use of Microsoft SEAL 2 | 3 | Homomorphic encryption schemes have various and often unexpected security models that may be surprising even to cryptography experts. 4 | In particular, decryptions of Microsoft SEAL ciphertexts should be treated as private information only available to the secret key owner, as sharing decryptions of ciphertexts may in some cases lead to leaking the secret key. 5 | If it is absolutely necessary to share information about the decryption of a ciphertext, for example when building a protocol of some kind, the number of bits shared should be kept to a minimum, and secret keys should be rotated regularly. 6 | Commercial applications of Microsoft SEAL should be carefully reviewed by cryptography experts who are familiar with homomorphic encryption security models. 7 | 8 | ## Security 9 | 10 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 11 | 12 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. 13 | 14 | ## Reporting Security Issues 15 | 16 | **Please do not report security vulnerabilities through public GitHub issues.** 17 | 18 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). 19 | 20 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). 21 | 22 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 23 | 24 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 25 | 26 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 27 | * Full paths of source file(s) related to the manifestation of the issue 28 | * The location of the affected source code (tag/branch/commit or direct URL) 29 | * Any special configuration required to reproduce the issue 30 | * Step-by-step instructions to reproduce the issue 31 | * Proof-of-concept or exploit code (if possible) 32 | * Impact of the issue, including how an attacker might exploit the issue 33 | 34 | This information will help us triage your report more quickly. 35 | 36 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. 37 | 38 | ## Preferred Languages 39 | 40 | We prefer all communications to be in English. 41 | 42 | ## Policy 43 | 44 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). 45 | -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /android/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /android/app/build.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | plugins { 5 | id 'com.android.application' 6 | } 7 | 8 | android { 9 | namespace 'com.microsoft.research.SEAL' 10 | compileSdk 32 11 | 12 | defaultConfig { 13 | applicationId "com.microsoft.research.SEAL" 14 | minSdk 28 15 | targetSdk 32 16 | versionCode 1 17 | versionName "1.0" 18 | 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | externalNativeBuild { 21 | cmake { 22 | cppFlags "" 23 | arguments "-DSEAL_BUILD_SEAL_C=1", 24 | "-DSEAL_USE_INTRIN=1", 25 | "-DSEAL_ARM64_EXITCODE=0", 26 | "-DSEAL_ARM64_EXITCODE__TRYRUN_OUTPUT=''", 27 | "-DSEAL___BUILTIN_CLZLL_FOUND_EXITCODE=0", 28 | "-DSEAL___BUILTIN_CLZLL_FOUND_EXITCODE__TRYRUN_OUTPUT=''", 29 | "-DSEAL__ADDCARRY_U64_FOUND_EXITCODE=0", 30 | "-DSEAL__ADDCARRY_U64_FOUND_EXITCODE__TRYRUN_OUTPUT=''", 31 | "-DSEAL__SUBBORROW_U64_FOUND_EXITCODE=0", 32 | "-DSEAL__SUBBORROW_U64_FOUND_EXITCODE__TRYRUN_OUTPUT=''" 33 | } 34 | } 35 | ndk { 36 | abiFilters 'x86_64' 37 | abiFilters 'arm64-v8a' 38 | } 39 | } 40 | 41 | buildTypes { 42 | release { 43 | minifyEnabled false 44 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 45 | } 46 | } 47 | compileOptions { 48 | sourceCompatibility JavaVersion.VERSION_1_8 49 | targetCompatibility JavaVersion.VERSION_1_8 50 | } 51 | externalNativeBuild { 52 | cmake { 53 | path file('../../CMakeLists.txt') 54 | version '3.18.1+' 55 | } 56 | } 57 | buildFeatures { 58 | viewBinding true 59 | } 60 | } 61 | 62 | dependencies { 63 | implementation 'androidx.appcompat:appcompat:1.4.1' 64 | implementation 'com.google.android.material:material:1.5.0' 65 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3' 66 | testImplementation 'junit:junit:4.13.2' 67 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 68 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 69 | } 70 | -------------------------------------------------------------------------------- /android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Add project specific ProGuard rules here. 5 | # You can control the set of applied configuration files using the 6 | # proguardFiles setting in build.gradle. 7 | # 8 | # For more details, see 9 | # http://developer.android.com/guide/developing/tools/proguard.html 10 | 11 | # If your project uses WebView with JS, uncomment the following 12 | # and specify the fully qualified class name to the JavaScript interface 13 | # class: 14 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 15 | # public *; 16 | #} 17 | 18 | # Uncomment this to preserve the line number information for 19 | # debugging stack traces. 20 | #-keepattributes SourceFile,LineNumberTable 21 | 22 | # If you keep the line number information, uncomment this to 23 | # hide the original source file name. 24 | #-renamesourcefileattribute SourceFile 25 | -------------------------------------------------------------------------------- /android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 2 | Licensed under the MIT license. --> 3 | 4 | <manifest xmlns:android="http://schemas.android.com/apk/res/android" 5 | package="com.microsoft.seal"> 6 | 7 | <application 8 | android:allowBackup="true" 9 | android:icon="@mipmap/ic_launcher" 10 | android:label="@string/app_name" 11 | android:roundIcon="@mipmap/ic_launcher_round" 12 | android:supportsRtl="true" 13 | android:theme="@style/AppTheme" /> 14 | </manifest> 15 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | <vector xmlns:android="http://schemas.android.com/apk/res/android" 2 | xmlns:aapt="http://schemas.android.com/aapt" 3 | android:width="108dp" 4 | android:height="108dp" 5 | android:viewportWidth="108" 6 | android:viewportHeight="108"> 7 | <path 8 | android:fillType="evenOdd" 9 | android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z" 10 | android:strokeWidth="1" 11 | android:strokeColor="#00000000"> 12 | <aapt:attr name="android:fillColor"> 13 | <gradient 14 | android:endX="78.5885" 15 | android:endY="90.9159" 16 | android:startX="48.7653" 17 | android:startY="61.0927" 18 | android:type="linear"> 19 | <item 20 | android:color="#44000000" 21 | android:offset="0.0" /> 22 | <item 23 | android:color="#00000000" 24 | android:offset="1.0" /> 25 | </gradient> 26 | </aapt:attr> 27 | </path> 28 | <path 29 | android:fillColor="#FFFFFF" 30 | android:fillType="nonZero" 31 | android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z" 32 | android:strokeWidth="1" 33 | android:strokeColor="#00000000" /> 34 | </vector> 35 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> 3 | <background android:drawable="@drawable/ic_launcher_background" /> 4 | <foreground android:drawable="@drawable/ic_launcher_foreground" /> 5 | </adaptive-icon> 6 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> 3 | <background android:drawable="@drawable/ic_launcher_background" /> 4 | <foreground android:drawable="@drawable/ic_launcher_foreground" /> 5 | </adaptive-icon> 6 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | 3 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 4 | Licensed under the MIT license. --> 5 | 6 | <resources> 7 | <color name="colorPrimary">#008577</color> 8 | <color name="colorPrimaryDark">#00574B</color> 9 | <color name="colorAccent">#D81B60</color> 10 | </resources> 11 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 2 | Licensed under the MIT license. --> 3 | 4 | <resources> 5 | <string name="app_name">SEAL</string> 6 | </resources> 7 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 2 | Licensed under the MIT license. --> 3 | 4 | <resources> 5 | <!-- Base application theme. --> 6 | <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 7 | <!-- Customize your theme here. --> 8 | <item name="colorPrimary">@color/colorPrimary</item> 9 | <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 10 | <item name="colorAccent">@color/colorAccent</item> 11 | </style> 12 | 13 | </resources> 14 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 5 | plugins { 6 | id 'com.android.application' version '7.3.1' apply false 7 | id 'com.android.library' version '7.3.1' apply false 8 | } 9 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Project-wide Gradle settings. 5 | # IDE (e.g. Android Studio) users: 6 | # Gradle settings configured through the IDE *will override* 7 | # any settings specified in this file. 8 | # For more details on how to configure your build environment visit 9 | # http://www.gradle.org/docs/current/userguide/build_environment.html 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 13 | # When configured, Gradle will run in incubating parallel mode. 14 | # This option should only be used with decoupled projects. More details, visit 15 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 16 | # org.gradle.parallel=true 17 | # AndroidX package structure to make it clearer which packages are bundled with the 18 | # Android operating system, and which are packaged with your app's APK 19 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 20 | android.useAndroidX=true 21 | # Enables namespacing of each library's R class so that its R class includes only the 22 | # resources declared in the library itself and none from the library's dependencies, 23 | # thereby reducing the size of the R class for that library 24 | android.nonTransitiveRClass=true 25 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/SEAL/7a931d55ba84a40b85938f6ca3ac206f18654093/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | #Fri Dec 23 22:19:39 PST 2022 5 | distributionBase=GRADLE_USER_HOME 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 7 | distributionPath=wrapper/dists 8 | zipStorePath=wrapper/dists 9 | zipStoreBase=GRADLE_USER_HOME 10 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | pluginManagement { 5 | repositories { 6 | gradlePluginPortal() 7 | google() 8 | mavenCentral() 9 | } 10 | } 11 | dependencyResolutionManagement { 12 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 13 | repositories { 14 | google() 15 | mavenCentral() 16 | } 17 | } 18 | rootProject.name = "SEAL" 19 | include ':app' 20 | -------------------------------------------------------------------------------- /cmake/CheckCXXIntrinsicsHeader.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Check for intrin.h or x86intrin.h 5 | if(SEAL_USE_INTRIN) 6 | set(CMAKE_REQUIRED_QUIET_OLD ${CMAKE_REQUIRED_QUIET}) 7 | set(CMAKE_REQUIRED_QUIET ON) 8 | 9 | if(MSVC) 10 | set(SEAL_INTRIN_HEADER "intrin.h") 11 | else() 12 | if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64") 13 | set(SEAL_ARM64 ON) 14 | else() 15 | set(SEAL_ARM64 OFF) 16 | endif() 17 | if(SEAL_ARM64) 18 | set(SEAL_INTRIN_HEADER "arm_neon.h") 19 | elseif(EMSCRIPTEN) 20 | set(SEAL_INTRIN_HEADER "wasm_simd128.h") 21 | else() 22 | set(SEAL_INTRIN_HEADER "x86intrin.h") 23 | endif() 24 | endif() 25 | 26 | check_include_file_cxx(${SEAL_INTRIN_HEADER} SEAL_INTRIN_HEADER_FOUND) 27 | set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_OLD}) 28 | 29 | if(SEAL_INTRIN_HEADER_FOUND) 30 | message(STATUS "${SEAL_INTRIN_HEADER} - found") 31 | else() 32 | message(STATUS "${SEAL_INTRIN_HEADER} - not found") 33 | endif() 34 | endif() 35 | -------------------------------------------------------------------------------- /cmake/CheckCXXIntrinsicsSpecific.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | if(SEAL_USE_INTRIN) 5 | cmake_push_check_state(RESET) 6 | set(CMAKE_REQUIRED_QUIET TRUE) 7 | if(NOT MSVC) 8 | set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -O0 ${SEAL_LANG_FLAG}") 9 | endif() 10 | 11 | if(MSVC) 12 | # Check for presence of _umul128 13 | check_cxx_source_runs(" 14 | #include <${SEAL_INTRIN_HEADER}> 15 | int main() { 16 | unsigned long long a = 0, b = 0; 17 | unsigned long long c; 18 | volatile unsigned long long d; 19 | d = _umul128(a, b, &c); 20 | return 0; 21 | }" 22 | SEAL__UMUL128_FOUND 23 | ) 24 | 25 | # Check for _BitScanReverse64 26 | check_cxx_source_runs(" 27 | #include <${SEAL_INTRIN_HEADER}> 28 | int main() { 29 | unsigned long a = 0, b = 0; 30 | volatile unsigned char res = _BitScanReverse64(&a, b); 31 | return 0; 32 | }" 33 | SEAL__BITSCANREVERSE64_FOUND 34 | ) 35 | else() 36 | # Check for presence of __int128 37 | set(CMAKE_EXTRA_INCLUDE_FILES ${SEAL_INTRIN_HEADER}) 38 | check_type_size("__int128" INT128 LANGUAGE CXX) 39 | if(INT128 EQUAL 16) 40 | set(SEAL___INT128_FOUND ON) 41 | else() 42 | set(SEAL___INT128_FOUND OFF) 43 | endif() 44 | 45 | # Check for __builtin_clzll 46 | check_cxx_source_runs(" 47 | int main() { 48 | volatile auto res = __builtin_clzll(0); 49 | return 0; 50 | }" 51 | SEAL___BUILTIN_CLZLL_FOUND 52 | ) 53 | endif() 54 | 55 | # Check for _addcarry_u64 56 | check_cxx_source_runs(" 57 | #include <${SEAL_INTRIN_HEADER}> 58 | int main() { 59 | unsigned long long a; 60 | volatile auto res = _addcarry_u64(0,0,0,&a); 61 | return 0; 62 | }" 63 | SEAL__ADDCARRY_U64_FOUND 64 | ) 65 | 66 | # Check for _subborrow_u64 67 | check_cxx_source_runs(" 68 | #include <${SEAL_INTRIN_HEADER}> 69 | int main() { 70 | unsigned long long a; 71 | volatile auto res = _subborrow_u64(0,0,0,&a); 72 | return 0; 73 | }" 74 | SEAL__SUBBORROW_U64_FOUND 75 | ) 76 | 77 | cmake_pop_check_state() 78 | endif() 79 | -------------------------------------------------------------------------------- /cmake/CheckMemset.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Check for memset_s 5 | check_cxx_source_runs(" 6 | #define __STDC_WANT_LIB_EXT1__ 1 7 | #include <string.h> 8 | int main(void) 9 | { 10 | char str[] = \"ghghghghghghghghghghgh\"; 11 | int r = memset_s(str, sizeof(str), 'a', 5); 12 | return r; 13 | }" 14 | SEAL_MEMSET_S_FOUND) 15 | 16 | # Check for explicit_bzero 17 | check_symbol_exists(explicit_bzero "string.h" SEAL_EXPLICIT_BZERO_FOUND) 18 | 19 | # Check for explicit_memset 20 | check_symbol_exists(explicit_memset "string.h" SEAL_EXPLICIT_MEMSET_FOUND) 21 | -------------------------------------------------------------------------------- /cmake/CleanArtifacts.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Remove native/src/gsl directory which is no longer used in version >= 3.5.0 5 | if(EXISTS ${SEAL_INCLUDES_DIR}/gsl) 6 | message(STATUS "Removing ${SEAL_INCLUDES_DIR}/gsl; this is no longer used by Microsoft SEAL >= 3.5.0") 7 | file(REMOVE_RECURSE ${SEAL_INCLUDES_DIR}/gsl) 8 | endif() 9 | 10 | # Remove thirdparty/zlib/src/CMakeCache.txt: the location changed in SEAL >= 3.5.4 11 | if(EXISTS ${SEAL_THIRDPARTY_DIR}/zlib/src/CMakeCache.txt) 12 | message(STATUS "Removing old ${SEAL_THIRDPARTY_DIR}/zlib/src/CMakeCache.txt") 13 | file(REMOVE ${SEAL_THIRDPARTY_DIR}/zlib/src/CMakeCache.txt) 14 | endif() 15 | 16 | # Remove config.h from source tree 17 | if(EXISTS ${SEAL_INCLUDES_DIR}/seal/util/config.h) 18 | message(STATUS "Removing old ${SEAL_INCLUDES_DIR}/seal/util/config.h") 19 | file(REMOVE ${SEAL_INCLUDES_DIR}/seal/util/config.h) 20 | endif() 21 | -------------------------------------------------------------------------------- /cmake/EnableCXX17.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | set(SEAL_USE_STD_BYTE OFF) 5 | set(SEAL_USE_SHARED_MUTEX OFF) 6 | set(SEAL_USE_IF_CONSTEXPR OFF) 7 | set(SEAL_USE_MAYBE_UNUSED OFF) 8 | set(SEAL_USE_NODISCARD OFF) 9 | set(SEAL_USE_STD_FOR_EACH_N OFF) 10 | set(SEAL_LANG_FLAG "-std=c++14") 11 | if(SEAL_USE_CXX17) 12 | set(SEAL_USE_STD_BYTE ON) 13 | set(SEAL_USE_SHARED_MUTEX ON) 14 | set(SEAL_USE_IF_CONSTEXPR ON) 15 | set(SEAL_USE_MAYBE_UNUSED ON) 16 | set(SEAL_USE_NODISCARD ON) 17 | set(SEAL_USE_STD_FOR_EACH_N ON) 18 | set(SEAL_LANG_FLAG "-std=c++17") 19 | endif() 20 | 21 | # In some non-MSVC compilers std::for_each_n is not available even when compiling as C++17 22 | if(SEAL_USE_STD_FOR_EACH_N) 23 | cmake_push_check_state(RESET) 24 | set(CMAKE_REQUIRED_QUIET TRUE) 25 | 26 | if(NOT MSVC) 27 | set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -O0 ${SEAL_LANG_FLAG}") 28 | check_cxx_source_compiles(" 29 | #include <algorithm> 30 | int main() { 31 | int a[1]{ 0 }; 32 | volatile auto fun = std::for_each_n(a, 1, [](auto b) {}); 33 | return 0; 34 | }" 35 | USE_STD_FOR_EACH_N 36 | ) 37 | if(NOT USE_STD_FOR_EACH_N EQUAL 1) 38 | set(SEAL_USE_STD_FOR_EACH_N OFF) 39 | endif() 40 | unset(USE_STD_FOR_EACH_N CACHE) 41 | endif() 42 | 43 | cmake_pop_check_state() 44 | endif() 45 | -------------------------------------------------------------------------------- /cmake/EnableCXXCompilerFlags.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | include(CheckCXXCompilerFlag) 5 | 6 | # For easier adding of CXX compiler flags 7 | function(seal_enable_cxx_compiler_flag_if_supported flag) 8 | string(FIND "${CMAKE_CXX_FLAGS}" "${flag}" flag_already_set) 9 | if(flag_already_set EQUAL -1) 10 | message(STATUS "Adding CXX compiler flag: ${flag} ...") 11 | check_cxx_compiler_flag("${flag}" flag_supported) 12 | if(flag_supported) 13 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE) 14 | endif() 15 | unset(flag_supported CACHE) 16 | endif() 17 | endfunction() 18 | 19 | if(NOT MSVC AND SEAL_DEBUG) 20 | seal_enable_cxx_compiler_flag_if_supported("-Wall") 21 | seal_enable_cxx_compiler_flag_if_supported("-Wextra") 22 | seal_enable_cxx_compiler_flag_if_supported("-Wconversion") 23 | seal_enable_cxx_compiler_flag_if_supported("-Wshadow") 24 | seal_enable_cxx_compiler_flag_if_supported("-pedantic") 25 | endif() 26 | -------------------------------------------------------------------------------- /cmake/ExternalBenchmark.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | FetchContent_Declare( 5 | benchmark 6 | GIT_REPOSITORY https://github.com/google/benchmark.git 7 | GIT_TAG d572f4777349d43653b21d6c2fc63020ab326db2 # 1.7.1 8 | ) 9 | FetchContent_GetProperties(benchmark) 10 | 11 | if(NOT benchmark) 12 | FetchContent_Populate(benchmark) 13 | 14 | set(LLVMAR_EXECUTABLE ${CMAKE_AR}) 15 | set(LLVMNM_EXECUTABLE ${CMAKE_NM}) 16 | set(LLVMRANLIB_EXECUTABLE ${CMAKE_RANLIB}) 17 | set(LLVM_FILECHECK_EXE ${CMAKE_CXX_COMPILER_AR}/../FileCheck) 18 | set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE) 19 | set(BENCHMARK_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) 20 | set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE) 21 | set(BENCHMARK_ENABLE_LTO OFF CACHE BOOL "" FORCE) 22 | mark_as_advanced(LIBRT) 23 | mark_as_advanced(LLVM_FILECHECK_EXE) 24 | mark_as_advanced(BENCHMARK_BUILD_32_BITS) 25 | mark_as_advanced(BENCHMARK_DOWNLOAD_DEPENDENCIES) 26 | mark_as_advanced(BENCHMARK_ENABLE_ASSEMBLY_TESTS) 27 | mark_as_advanced(BENCHMARK_ENABLE_EXCEPTIONS) 28 | mark_as_advanced(BENCHMARK_ENABLE_GTEST_TESTS) 29 | mark_as_advanced(BENCHMARK_ENABLE_INSTALL) 30 | mark_as_advanced(BENCHMARK_ENABLE_LTO) 31 | mark_as_advanced(BENCHMARK_ENABLE_TESTING) 32 | mark_as_advanced(BENCHMARK_USE_LIBCXX) 33 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_BENCHMARK) 34 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_BENCHMARK) 35 | 36 | if(NOT WIN32) 37 | # Google Benchmark contains unsafe conversions so force -Wno-conversion temporarily 38 | set(OLD_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) 39 | set(CMAKE_CXX_FLAGS "${OLD_CMAKE_CXX_FLAGS} -Wno-conversion") 40 | endif() 41 | 42 | add_subdirectory( 43 | ${benchmark_SOURCE_DIR} 44 | ${THIRDPARTY_BINARY_DIR}/benchmark-src 45 | EXCLUDE_FROM_ALL) 46 | 47 | if(NOT WIN32) 48 | set(CMAKE_CXX_FLAGS ${OLD_CMAKE_CXX_FLAGS}) 49 | endif() 50 | endif() 51 | -------------------------------------------------------------------------------- /cmake/ExternalGTest.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | FetchContent_Declare( 5 | googletest 6 | GIT_REPOSITORY https://github.com/google/googletest.git 7 | GIT_TAG 58d77fa8070e8cec2dc1ed015d66b454c8d78850 # 1.12.1 8 | ) 9 | FetchContent_GetProperties(googletest) 10 | 11 | if(NOT googletest_POPULATED) 12 | FetchContent_Populate(googletest) 13 | 14 | set(BUILD_GMOCK OFF CACHE BOOL "" FORCE) 15 | set(INSTALL_GTEST OFF CACHE BOOL "" FORCE) 16 | set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) 17 | mark_as_advanced(BUILD_GMOCK) 18 | mark_as_advanced(INSTALL_GTEST) 19 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_GOOGLETEST) 20 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_GOOGLETEST) 21 | 22 | add_subdirectory( 23 | ${googletest_SOURCE_DIR} 24 | ${THIRDPARTY_BINARY_DIR}/googletest-src 25 | EXCLUDE_FROM_ALL) 26 | endif() 27 | -------------------------------------------------------------------------------- /cmake/ExternalIntelHEXL.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | FetchContent_Declare( 5 | hexl 6 | PREFIX hexl 7 | GIT_REPOSITORY https://github.com/intel/hexl 8 | GIT_TAG f95acf1 # 1.2.5 9 | ) 10 | FetchContent_GetProperties(hexl) 11 | 12 | if(NOT hexl_POPULATED) 13 | FetchContent_Populate(hexl) 14 | set(CMAKE_C_COMPILER ${CMAKE_C_COMPILER} CACHE STRING "" FORCE) 15 | set(CMAKE_CXX_COMPILER ${CMAKE_CXX_COMPILER} CACHE STRING "" FORCE) 16 | set(CMAKE_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} CACHE STRING "" FORCE) 17 | set(HEXL_BENCHMARK OFF CACHE BOOL "" FORCE) 18 | set(HEXL_COVERAGE OFF CACHE BOOL "" FORCE) 19 | set(HEXL_TESTING OFF CACHE BOOL "" FORCE) 20 | set(HEXL_SHARED_LIB ${BUILD_SHARED_LIBS} CACHE BOOL "" FORCE) 21 | set(EXCLUDE_FROM_ALL TRUE) 22 | 23 | mark_as_advanced(BUILD_HEXL) 24 | mark_as_advanced(INSTALL_HEXL) 25 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_HEXL) 26 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_HEXL) 27 | 28 | add_subdirectory( 29 | ${hexl_SOURCE_DIR} 30 | ${hexl_SOURCE_DIR}/../hexl-build 31 | EXCLUDE_FROM_ALL 32 | ) 33 | endif() 34 | -------------------------------------------------------------------------------- /cmake/ExternalMSGSL.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | FetchContent_Declare( 5 | msgsl 6 | GIT_REPOSITORY https://github.com/microsoft/GSL.git 7 | GIT_TAG a3534567187d2edc428efd3f13466ff75fe5805c # 4.0.0 8 | ) 9 | FetchContent_GetProperties(msgsl) 10 | 11 | if(NOT msgsl_POPULATED) 12 | FetchContent_Populate(msgsl) 13 | 14 | set(GSL_CXX_STANDARD "14" CACHE STRING "" FORCE) 15 | set(GSL_TEST OFF CACHE BOOL "" FORCE) 16 | mark_as_advanced(GSL_CXX_STANDARD ) 17 | mark_as_advanced(GSL_TEST) 18 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_MSGSL) 19 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_MSGSL) 20 | 21 | add_subdirectory( 22 | ${msgsl_SOURCE_DIR} 23 | ${msgsl_SOURCE_DIR}/../msgsl-build 24 | EXCLUDE_FROM_ALL) 25 | endif() 26 | -------------------------------------------------------------------------------- /cmake/ExternalZLIB.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. 2 | 3 | FetchContent_Declare( 4 | zlib 5 | GIT_REPOSITORY https://github.com/madler/zlib.git 6 | GIT_TAG 51b7f2abdade71cd9bb0e7a373ef2610ec6f9daf # 1.3.1 7 | ) 8 | FetchContent_GetProperties(zlib) 9 | if(NOT zlib_POPULATED) 10 | FetchContent_Populate(zlib) 11 | 12 | set(SKIP_INSTALL_ALL ON CACHE BOOL "" FORCE) 13 | mark_as_advanced(AMD64) 14 | mark_as_advanced(ASM686) 15 | mark_as_advanced(EXECUTABLE_OUTPUT_PATH) 16 | mark_as_advanced(CMAKE_INSTALL_PREFIX) 17 | mark_as_advanced(INSTALL_BIN_DIR) 18 | mark_as_advanced(INSTALL_INC_DIR) 19 | mark_as_advanced(INSTALL_LIB_DIR) 20 | mark_as_advanced(INSTALL_MAN_DIR) 21 | mark_as_advanced(INSTALL_PKGCONFIG_DIR) 22 | mark_as_advanced(LIBRARY_OUTPUT_PATH) 23 | mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY) 24 | mark_as_advanced(ZLIB_BUILD_STATIC) 25 | mark_as_advanced(SKIP_INSTALL_ALL) 26 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_ZLIB) 27 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_ZLIB) 28 | 29 | # ZLIB has no VERSION given to project(), needs to suppress CMP0048 warning 30 | set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS TRUE CACHE INTERNAL "Suppress CMP0048 warning" FORCE) 31 | add_subdirectory( 32 | ${zlib_SOURCE_DIR} 33 | ${zlib_SOURCE_DIR}/../zlib-build 34 | EXCLUDE_FROM_ALL) 35 | endif() 36 | -------------------------------------------------------------------------------- /cmake/ExternalZSTD.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | FetchContent_Declare( 5 | zstd 6 | GIT_REPOSITORY https://github.com/facebook/zstd.git 7 | GIT_TAG f8745da6ff1ad1e7bab384bd1f9d742439278e99 # 1.5.7 8 | ) 9 | FetchContent_GetProperties(zstd) 10 | if(NOT zstd_POPULATED) 11 | FetchContent_Populate(zstd) 12 | 13 | set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE) 14 | set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE) 15 | set(ZLIB_BUILD_STATIC ON CACHE BOOL "" FORCE) 16 | set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE) 17 | set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE) 18 | mark_as_advanced(ZSTD_BUILD_CONTRIB) 19 | mark_as_advanced(ZSTD_BUILD_PROGRAMS) 20 | mark_as_advanced(ZSTD_BUILD_SHARED) 21 | mark_as_advanced(ZSTD_BUILD_STATIC) 22 | mark_as_advanced(ZSTD_BUILD_TESTS) 23 | mark_as_advanced(ZSTD_LEGACY_SUPPORT) 24 | mark_as_advanced(ZSTD_MULTITHREAD_SUPPORT) 25 | mark_as_advanced(ZSTD_PROGRAMS_LINK_SHARED) 26 | mark_as_advanced(FETCHCONTENT_SOURCE_DIR_ZSTD) 27 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_ZSTD) 28 | 29 | add_subdirectory( 30 | ${zstd_SOURCE_DIR}/build/cmake 31 | ${zstd_SOURCE_DIR}/../zstd-build 32 | EXCLUDE_FROM_ALL) 33 | endif() 34 | -------------------------------------------------------------------------------- /cmake/functions.iOS.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # This cache-initialization file will be used to enable functions when cross-compiling 5 | # for iOS, as check_cxx_source_runs fails for cross-compilers. 6 | 7 | set(SEAL_MEMSET_S_FOUND_EXITCODE 8 | "0" 9 | CACHE STRING "Result from TRY_RUN" FORCE) 10 | 11 | set(SEAL_MEMSET_S_FOUND_EXITCODE__TRYRUN_OUTPUT 12 | "" 13 | CACHE STRING "Output from TRY_RUN" FORCE) 14 | 15 | set(SEAL_ARM64_EXITCODE 16 | "0" 17 | CACHE STRING "Result from TRY_RUN" FORCE) 18 | 19 | set (SEAL_ARM64_EXITCODE__TRYRUN_OUTPUT 20 | "" 21 | CACHE STRING "Output from TRY_RUN" FORCE) 22 | 23 | set(SEAL___BUILTIN_CLZLL_FOUND_EXITCODE 24 | "0" 25 | CACHE STRING "Result from TRY_RUN" FORCE) 26 | 27 | set(SEAL___BUILTIN_CLZLL_FOUND_EXITCODE__TRYRUN_OUTPUT 28 | "" 29 | CACHE STRING "Output from TRY_RUN" FORCE) 30 | 31 | set(SEAL__ADDCARRY_U64_FOUND_EXITCODE 32 | "0" 33 | CACHE STRING "Result from TRY_RUN" FORCE) 34 | 35 | set(SEAL__ADDCARRY_U64_FOUND_EXITCODE__TRYRUN_OUTPUT 36 | "" 37 | CACHE STRING "Output from TRY_RUN" FORCE) 38 | 39 | set(SEAL__SUBBORROW_U64_FOUND_EXITCODE 40 | "0" 41 | CACHE STRING "Result from TRY_RUN" FORCE) 42 | 43 | set(SEAL__SUBBORROW_U64_FOUND_EXITCODE__TRYRUN_OUTPUT 44 | "" 45 | CACHE STRING "Output from TRY_RUN" FORCE) 46 | -------------------------------------------------------------------------------- /dotnet/examples/SEALNetExamples.csproj.in: -------------------------------------------------------------------------------- 1 | <Project Sdk="Microsoft.NET.Sdk"> 2 | 3 | <PropertyGroup> 4 | <OutputType>Exe</OutputType> 5 | <TargetFramework>net6.0</TargetFramework> 6 | <Authors>Microsoft Research</Authors> 7 | <Company>Microsoft Corporation</Company> 8 | <Description>.NET wrapper examples for Microsoft SEAL</Description> 9 | <Copyright>Microsoft Corporation 2022</Copyright> 10 | </PropertyGroup> 11 | 12 | <PropertyGroup> 13 | <PlatformTarget>x64</PlatformTarget> 14 | <OutputPath>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/dotnet/$(Configuration)</OutputPath> 15 | </PropertyGroup> 16 | 17 | <ItemGroup> 18 | <ProjectReference Include="$(ProjectDir)../src/SEALNet.csproj" /> 19 | </ItemGroup> 20 | 21 | <ItemGroup> 22 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(Windows))" Include="@SEAL_WINDOWS_SEAL_C_DIRECTORY@\sealc.dll" /> 23 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(Linux))" Include="@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/libsealc.so*" /> 24 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(OSX))" Include="@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/libsealc*.dylib" /> 25 | </ItemGroup> 26 | 27 | <Target Name="PostBuild" AfterTargets="PostBuildEvent"> 28 | <Copy SourceFiles="@(SEALCBinaryFiles)" DestinationFolder="$(TargetDir)" /> 29 | </Target> 30 | 31 | <ItemGroup> 32 | <Compile Include="@CMAKE_CURRENT_SOURCE_DIR@\dotnet\examples\**\*.cs" /> 33 | </ItemGroup> 34 | </Project> 35 | -------------------------------------------------------------------------------- /dotnet/nuget/NUGET.md: -------------------------------------------------------------------------------- 1 | # Creating a NuGet package 2 | 3 | After building `dotnet\src\SEALNet.csproj` you can create a NuGet package that you can 4 | use to easily add Microsoft SEAL capabilities to all of your .NET projects. 5 | 6 | You will need to do the following: 7 | 1. Compile both SEAL and SEAL_C projects with CMake. Build `dotnet\src\SEALNet.csproj`. 8 | 1. [Download and install the NuGet command line tool](https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools). 9 | 1. Run the command below to create NuGet package. 10 | 1. Add NuGet package reference to your .NET projects. 11 | 12 | The command to create the NuGet package after compiling binaries is the following: 13 | 14 | ```` 15 | cd dotnet\nuget 16 | nuget pack SEALNet.nuspec -properties Configuration=Release -Verbosity detailed -OutputDir Release 17 | cd ..\.. 18 | ```` 19 | 20 | After the package is created, copy it from `dotnet\nuget\Release` to a known location (e.g., `C:\NuGetPackages`). 21 | 22 | To add a reference to the NuGet package, you will need to configure Visual Studio so it can find 23 | packages in this known location. In Microsoft Visual Studio 2022, for example, you can: 24 | 1. Select the menu uption `Tools / Options...` 25 | 2. On the left pane of the Options dialog, navigate to `NuGet Package Manager / Package Sources` 26 | 3. On the right pane of the Options dialog, add a new package source that points to the directory 27 | where you copied the NuGet package (e.g., `C:\NuGetPackages`) 28 | 29 | After this, you should be able to add a reference to this package in your own .NET project. After 30 | creating or opening your project in Visual Studio, you can right click on the project in the 31 | Solution Explorer window, and select `Manage NuGet packages...`. In the window that appears 32 | you will be able to select the `Microsoft.Research.SEAL` NuGet package to add to your project. 33 | -------------------------------------------------------------------------------- /dotnet/nuget/SEALNet-multi.nuspec.in: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | 3 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 4 | Licensed under the MIT license. --> 5 | 6 | <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> 7 | <metadata> 8 | <id>Microsoft.Research.SEALNet</id> 9 | <version>@SEAL_VERSION@</version> 10 | <title>Microsoft SEAL</title> 11 | <authors>Microsoft</authors> 12 | <owners>Microsoft</owners> 13 | <projectUrl>http://sealcrypto.org</projectUrl> 14 | <license type="file">LICENSE</license> 15 | <requireLicenseAcceptance>false</requireLicenseAcceptance> 16 | <description>Microsoft SEAL is an easy-to-use and powerful open source homomorphic encryption library, developed by researchers in the Cryptography and Privacy Research Group at Microsoft Research. Microsoft SEAL is licensed under the MIT license.</description> 17 | <releaseNotes>https://GitHub.com/Microsoft/SEAL</releaseNotes> 18 | <copyright>© Microsoft Corporation. All rights reserved.</copyright> 19 | <tags>c# crypto cryptography homomorphic encryption</tags> 20 | <dependencies> 21 | <group targetFramework=".NETStandard2.0" /> 22 | <group targetFramework="Xamarin.iOS10" /> 23 | </dependencies> 24 | </metadata> 25 | <files> 26 | <file src="SEALNet.targets" target="build/Microsoft.Research.SEALNet.targets" /> 27 | <file src="$NUGET_WINDOWS_SEAL_C_PATHquot; target="runtimes/win10-x64/" /> 28 | <file src="$NUGET_LINUX_SEAL_C_PATHquot; target="runtimes/linux-x64/" /> 29 | <file src="$NUGET_MACOS_SEAL_C_PATHquot; target="runtimes/macos-x64/" /> 30 | <file src="$NUGET_ANDROIDARM64_SEAL_C_PATHquot; target="runtimes/android-arm64/" /> 31 | <file src="$NUGET_ANDROIDX64_SEAL_C_PATHquot; target="runtimes/android-x64/" /> 32 | <file src="$NUGET_IOS64_SEAL_C_PATHquot; target="runtimes/ios64/" /> 33 | <file src="$NUGET_IOS64_SEAL_PATHquot; target="runtimes/ios64/" /> 34 | <file src="../../build/bin/dotnet/$configuration$/netstandard2.0/SEALNet.dll" target="lib/netstandard2.0/" /> 35 | <file src="../../build/bin/dotnet/$configuration$/SEALNet.xml" target="lib/netstandard2.0/" /> 36 | <file src="../../build/bin/dotnet/ios/$configuration$/netstandard2.0/SEALNet.dll" target="lib/Xamarin.iOS10/" /> 37 | <file src="../../build/bin/dotnet/ios/$configuration$/SEALNet.xml" target="lib/Xamarin.iOS10/" /> 38 | <file src="../../LICENSE" target="LICENSE" /> 39 | <file src="../../NOTICE" target="/ThirdPartyNotices" /> 40 | </files> 41 | </package> 42 | -------------------------------------------------------------------------------- /dotnet/nuget/SEALNet.nuspec.in: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | 3 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 4 | Licensed under the MIT license. --> 5 | 6 | <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> 7 | <metadata> 8 | <id>Microsoft.Research.SEALNet</id> 9 | <version>@SEAL_VERSION@</version> 10 | <title>Microsoft SEAL</title> 11 | <authors>Microsoft</authors> 12 | <owners>Microsoft</owners> 13 | <projectUrl>http://sealcrypto.org</projectUrl> 14 | <license type="file">LICENSE</license> 15 | <requireLicenseAcceptance>false</requireLicenseAcceptance> 16 | <description>Microsoft SEAL is an easy-to-use and powerful open source homomorphic encryption library, developed by researchers in the Cryptography and Privacy Research Group at Microsoft Research. Microsoft SEAL is licensed under the MIT license.</description> 17 | <releaseNotes>https://GitHub.com/Microsoft/SEAL</releaseNotes> 18 | <copyright>© Microsoft Corporation. All rights reserved.</copyright> 19 | <tags>c# crypto cryptography homomorphic encryption</tags> 20 | <dependencies> 21 | <group targetFramework=".NETStandard2.0" /> 22 | </dependencies> 23 | </metadata> 24 | <files> 25 | <file src="SEALNet.targets" target="build/Microsoft.Research.SEALNet.targets" /> 26 | <file src="@NUGET_WINDOWS_SEAL_C_PATH@" target="runtimes/win10-x64" /> 27 | <file src="@NUGET_LINUX_SEAL_C_PATH@" target="runtimes/linux-x64" /> 28 | <file src="@NUGET_MACOS_SEAL_C_PATH@" target="runtimes/macos-x64" /> 29 | <file src="@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/dotnet/$configuration$/netstandard2.0/SEALNet.dll" target="lib/netstandard2.0/" /> 30 | <file src="@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/dotnet/$configuration$/SEALNet.xml" target="lib/netstandard2.0/" /> 31 | <file src="../../LICENSE" target="LICENSE" /> 32 | <file src="../../NOTICE" target="/ThirdPartyNotices" /> 33 | </files> 34 | </package> 35 | -------------------------------------------------------------------------------- /dotnet/nuget/SEALNet.targets: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | 3 | <!-- Copyright (c) Microsoft Corporation. All rights reserved. 4 | Licensed under the MIT license. --> 5 | 6 | <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 7 | <PropertyGroup> 8 | <IsSEALMobile>False</IsSEALMobile> 9 | <IsSEALMobile Condition="'$(AndroidApplication)'=='True' Or '$(Platform)'=='iPhone' Or '$(Platform)'=='iPhoneSimulator'">True</IsSEALMobile> 10 | </PropertyGroup> 11 | <ItemGroup> 12 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform('Windows'))" Include="$(MSBuildThisFileDirectory)../runtimes/win10-x64/sealc.dll" /> 13 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform('Linux'))" Include="$(MSBuildThisFileDirectory)../runtimes/linux-x64/libsealc.so*" /> 14 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform('OSX'))" Include="$(MSBuildThisFileDirectory)../runtimes/macos-x64/libsealc*.dylib" /> 15 | </ItemGroup> 16 | <ItemGroup Condition="!$(IsSEALMobile)"> 17 | <None Include="@(SEALCBinaryFiles)"> 18 | <Link Condition="$([MSBuild]::IsOsPlatform('Windows'))">sealc.dll</Link> 19 | <Link Condition="$([MSBuild]::IsOsPlatform('Linux'))">libsealc.so</Link> 20 | <Link Condition="$([MSBuild]::IsOsPlatform('OSX'))">libsealc.dylib</Link> 21 | <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> 22 | </None> 23 | </ItemGroup> 24 | <ItemGroup Condition="'$(AndroidApplication)'=='True'"> 25 | <AndroidNativeLibrary Include="$(MSBuildThisFileDirectory)../runtimes/android-arm64/libsealc.so"> 26 | <Abi>arm64-v8a</Abi> 27 | <Link>libs\arm64-v8a\libsealc.so</Link> 28 | </AndroidNativeLibrary> 29 | <AndroidNativeLibrary Include="$(MSBuildThisFileDirectory)../runtimes/android-x64/libsealc.so"> 30 | <Abi>x86_64</Abi> 31 | <Link>libs\x86_64\libsealc.so</Link> 32 | </AndroidNativeLibrary> 33 | </ItemGroup> 34 | <ItemGroup Condition="'$(Platform)'=='iPhone' Or '$(Platform)'=='iPhoneSimulator'"> 35 | <NativeReference Include="$(MSBuildThisFileDirectory)../runtimes/ios64/libsealc.a"> 36 | <Kind>Static</Kind> 37 | <ForceLoad>True</ForceLoad> 38 | <IsCxx>True</IsCxx> 39 | </NativeReference> 40 | <NativeReference Include="$(MSBuildThisFileDirectory)../runtimes/ios64/libseal.a"> 41 | <Kind>Static</Kind> 42 | <ForceLoad>True</ForceLoad> 43 | <IsCxx>True</IsCxx> 44 | </NativeReference> 45 | </ItemGroup> 46 | </Project> 47 | -------------------------------------------------------------------------------- /dotnet/src/SEALNet.csproj.in: -------------------------------------------------------------------------------- 1 | <Project Sdk="Microsoft.NET.Sdk"> 2 | <PropertyGroup> 3 | <TargetFramework>netstandard2.0</TargetFramework> 4 | <GeneratePackageOnBuild>false</GeneratePackageOnBuild> 5 | <Authors>Microsoft Research</Authors> 6 | <Company>Microsoft Corporation</Company> 7 | <Description>.NET wrapper library for Microsoft SEAL</Description> 8 | <Copyright>Microsoft Corporation 2020</Copyright> 9 | <SignAssembly Condition="'$(OS)' == 'Windows_NT' And '$(SEALNetSigningCertificate)' != ''">true</SignAssembly> 10 | <AssemblyOriginatorKeyFile Condition="'$(OS)' == 'Windows_NT' And '$(SEALNetSigningCertificate)' != ''">SEALNetCert.snk</AssemblyOriginatorKeyFile> 11 | <DelaySign Condition="'$(OS)' == 'Windows_NT' And '$(SEALNetSigningCertificate)' != ''">true</DelaySign> 12 | </PropertyGroup> 13 | <PropertyGroup> 14 | <DocumentationFile>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\dotnet\$(Configuration)/SEALNet.xml</DocumentationFile> 15 | <PlatformTarget>x64</PlatformTarget> 16 | <OutputPath>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\dotnet\$(Configuration)</OutputPath> 17 | </PropertyGroup> 18 | <PropertyGroup Condition="'$(BuildIOS)' != ''"> 19 | <DefineConstants>$(DefineConstants);SEAL_IOS</DefineConstants> 20 | <DocumentationFile>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\dotnet\ios\$(Configuration)\SEALNet.xml</DocumentationFile> 21 | <OutputPath>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\dotnet\ios\$(Configuration)</OutputPath> 22 | </PropertyGroup> 23 | <PropertyGroup Condition="'$(Configuration)'=='Release'"> 24 | <DebugType>pdbonly</DebugType> 25 | <DebugSymbols>true</DebugSymbols> 26 | </PropertyGroup> 27 | <PropertyGroup Condition="'$(Configuration)'=='Debug'"> 28 | <DefineConstants>$(DefineConstants);DEBUG;TRACE</DefineConstants> 29 | </PropertyGroup> 30 | 31 | <ItemGroup> 32 | <Compile Include="@CMAKE_CURRENT_SOURCE_DIR@\dotnet\src\**\*.cs" /> 33 | </ItemGroup> 34 | </Project> 35 | -------------------------------------------------------------------------------- /dotnet/src/Version.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using System; 5 | using System.IO; 6 | using System.Text; 7 | 8 | namespace Microsoft.Research.SEAL 9 | { 10 | /// <summary> 11 | /// This class contains static methods for retrieving Microsoft SEAL's version numbers. 12 | /// </summary> 13 | /// <remark> 14 | /// Use the name SEALVersion to distinguish it from System.Version. 15 | /// </remark> 16 | public static class SEALVersion 17 | { 18 | /// <summary> 19 | /// Returns Microsoft SEAL's version number string. 20 | /// </summary> 21 | static public string Version => quot;{SEALVersion.Major}.{SEALVersion.Minor}.{SEALVersion.Patch}"; 22 | 23 | /// 24 | /// <summary> 25 | /// Returns Microsoft SEAL's major version number. 26 | /// </summary> 27 | static public byte Major 28 | { 29 | get 30 | { 31 | NativeMethods.Version_Major(out byte result); 32 | return result; 33 | } 34 | } 35 | 36 | /// <summary> 37 | /// Returns Microsoft SEAL's minor version number. 38 | /// </summary> 39 | static public byte Minor 40 | { 41 | get 42 | { 43 | NativeMethods.Version_Minor(out byte result); 44 | return result; 45 | } 46 | } 47 | 48 | /// <summary> 49 | /// Returns Microsoft SEAL's patch version number. 50 | /// </summary> 51 | static public byte Patch 52 | { 53 | get 54 | { 55 | NativeMethods.Version_Patch(out byte result); 56 | return result; 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /dotnet/src/tools/DisposableObject.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Research.SEAL.Tools 7 | { 8 | /// <summary> 9 | /// Class that implements the Disposable pattern 10 | /// </summary> 11 | public class DisposableObject : IDisposable 12 | { 13 | /// <summary> 14 | /// Derived classes should override this method to release managed resources. 15 | /// </summary> 16 | protected virtual void DisposeManagedResources() 17 | { 18 | } 19 | 20 | /// <summary> 21 | /// Derived classes should override this method to release native resources. 22 | /// </summary> 23 | protected virtual void DisposeNativeResources() 24 | { 25 | } 26 | 27 | /// <summary> 28 | /// Whether this object is disposed 29 | /// </summary> 30 | public bool IsDisposed 31 | { 32 | get 33 | { 34 | return disposedValue; 35 | } 36 | } 37 | 38 | #region IDisposable Support 39 | 40 | private bool disposedValue = false; // To detect redundant calls 41 | 42 | private void Dispose(bool disposing) 43 | { 44 | if (!disposedValue) 45 | { 46 | if (disposing) 47 | { 48 | DisposeManagedResources(); 49 | } 50 | 51 | DisposeNativeResources(); 52 | 53 | disposedValue = true; 54 | } 55 | } 56 | 57 | /// <summary> 58 | /// DisposableObject destructor 59 | /// </summary> 60 | ~DisposableObject() 61 | { 62 | // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 63 | Dispose(false); 64 | } 65 | 66 | /// <summary> 67 | /// This code is added to correctly implement the disposable pattern. 68 | /// </summary> 69 | public void Dispose() 70 | { 71 | // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 72 | Dispose(true); 73 | GC.SuppressFinalize(this); 74 | } 75 | 76 | #endregion 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /dotnet/src/tools/NativeObject.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Research.SEAL.Tools 7 | { 8 | /// <summary> 9 | /// Class that encapsulates the behavior of a class backed by a 10 | /// pointer to a native object. 11 | /// 12 | /// In particular, this class encapsulates the correct disposal 13 | /// of the native pointer. 14 | /// </summary> 15 | public abstract class NativeObject : DisposableObject 16 | { 17 | /// <summary> 18 | /// Construct a NativeObject instance 19 | /// </summary> 20 | public NativeObject() 21 | { 22 | NativePtr = IntPtr.Zero; 23 | owned_ = true; 24 | } 25 | 26 | /// <summary> 27 | /// Construct a NativeObject instance initializing it with a pointer 28 | /// to a native object. 29 | /// </summary> 30 | /// <param name="nativePtr">Pointer to native object.</param> 31 | /// <param name="owned">Whether this instance owns the native pointer.</param> 32 | public NativeObject(IntPtr nativePtr, bool owned = true) 33 | { 34 | NativePtr = nativePtr; 35 | owned_ = owned; 36 | } 37 | 38 | /// <summary> 39 | /// Descendants should call the appropriate method to 40 | /// destroy the backing native object. 41 | /// </summary> 42 | protected abstract void DestroyNativeObject(); 43 | 44 | /// <summary> 45 | /// Destroy native object if necessary 46 | /// </summary> 47 | protected override void DisposeNativeResources() 48 | { 49 | base.DisposeNativeResources(); 50 | 51 | if (owned_ && !IntPtr.Zero.Equals(NativePtr)) 52 | { 53 | DestroyNativeObject(); 54 | } 55 | 56 | NativePtr = IntPtr.Zero; 57 | } 58 | 59 | /// <summary> 60 | /// Get/Set pointer to native object 61 | /// </summary> 62 | internal IntPtr NativePtr 63 | { 64 | get 65 | { 66 | if (IsDisposed) 67 | { 68 | Type objType = this.GetType(); 69 | string objName = objType?.FullName ?? "Unknown object name"; 70 | throw new ObjectDisposedException(objName); 71 | } 72 | 73 | return nativePtr_; 74 | } 75 | set 76 | { 77 | nativePtr_ = value; 78 | } 79 | } 80 | 81 | /// <summary> 82 | /// Whether this instance owns the native pointer. 83 | /// </summary> 84 | private readonly bool owned_ = true; 85 | 86 | /// <summary> 87 | /// Pointer to native object 88 | /// </summary> 89 | private IntPtr nativePtr_ = IntPtr.Zero; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /dotnet/src/tools/Utilities.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Research.SEAL.Tools 7 | { 8 | static class Utilities 9 | { 10 | public static readonly int BitsPerUInt64 = 64; 11 | public static readonly int BitsPerUInt8 = 8; 12 | 13 | public static int DivideRoundUp(int value, int divisor) 14 | { 15 | return (value + divisor - 1) / divisor; 16 | } 17 | 18 | public static int ComputeArrayHashCode(ulong[] array) 19 | { 20 | if (null == array) 21 | throw new ArgumentNullException(nameof(array)); 22 | 23 | const int hash_seed = 17; 24 | const int hash_multiply = 23; 25 | int hash = hash_seed; 26 | 27 | unchecked 28 | { 29 | for (int i = 0; i < array.Length; i++) 30 | { 31 | ulong value = array[i]; 32 | if (value != 0) 33 | { 34 | hash *= hash_multiply; 35 | hash += (int)value; 36 | value >>= 32; 37 | hash *= hash_multiply; 38 | hash += (int)value; 39 | } 40 | } 41 | } 42 | 43 | return hash; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /dotnet/tests/GlobalContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using Microsoft.Research.SEAL; 5 | 6 | namespace SEALNetTest 7 | { 8 | /// <summary> 9 | /// Provides a global SEALContext that can be used by Tests. 10 | /// Necessary to run tests fast, as creating a SEALContext can take around 11 | /// 2 seconds. 12 | /// </summary> 13 | static class GlobalContext 14 | { 15 | static GlobalContext() 16 | { 17 | EncryptionParameters encParams = new EncryptionParameters(SchemeType.BFV) 18 | { 19 | PolyModulusDegree = 8192, 20 | CoeffModulus = CoeffModulus.BFVDefault(polyModulusDegree: 8192) 21 | }; 22 | encParams.SetPlainModulus(65537ul); 23 | BFVContext = new SEALContext(encParams); 24 | 25 | encParams = new EncryptionParameters(SchemeType.CKKS) 26 | { 27 | PolyModulusDegree = 8192, 28 | CoeffModulus = CoeffModulus.BFVDefault(polyModulusDegree: 8192) 29 | }; 30 | CKKSContext = new SEALContext(encParams); 31 | 32 | encParams = new EncryptionParameters(SchemeType.BGV) 33 | { 34 | PolyModulusDegree = 8192, 35 | CoeffModulus = CoeffModulus.BFVDefault(polyModulusDegree: 8192) 36 | }; 37 | encParams.SetPlainModulus(65537ul); 38 | BGVContext = new SEALContext(encParams); 39 | } 40 | 41 | public static SEALContext BFVContext { get; private set; } = null; 42 | public static SEALContext CKKSContext { get; private set; } = null; 43 | public static SEALContext BGVContext { get; private set; } = null; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /dotnet/tests/MemoryManagerTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using Microsoft.Research.SEAL; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | namespace SEALNetTest 8 | { 9 | [TestClass] 10 | public class MemoryManagerTests 11 | { 12 | [TestMethod] 13 | public void SwitchProfileTest() 14 | { 15 | MemoryPoolHandle handle = MemoryManager.GetPool(MMProfOpt.ForceNew); 16 | MMProfFixed fixedProfile = new MMProfFixed(handle); 17 | 18 | MMProf oldProfile = MemoryManager.SwitchProfile(fixedProfile); 19 | Assert.IsInstanceOfType(oldProfile, typeof(MMProfGlobal)); 20 | 21 | MMProfNew newProfile = new MMProfNew(); 22 | oldProfile = MemoryManager.SwitchProfile(newProfile); 23 | 24 | Assert.IsInstanceOfType(oldProfile, typeof(MMProfFixed)); 25 | 26 | MMProfGlobal globalProfile = new MMProfGlobal(); 27 | oldProfile = MemoryManager.SwitchProfile(globalProfile); 28 | 29 | Assert.IsInstanceOfType(oldProfile, typeof(MMProfNew)); 30 | 31 | MemoryPoolHandle globalHandle = globalProfile.GetPool(); 32 | Assert.IsNotNull(globalHandle); 33 | Assert.IsTrue(globalHandle.IsInitialized); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dotnet/tests/NativeObjectTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | using Microsoft.Research.SEAL; 5 | using Microsoft.Research.SEAL.Tools; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Text; 10 | 11 | namespace SEALNetTest 12 | { 13 | [TestClass] 14 | public class NativeObjectTests 15 | { 16 | [TestMethod] 17 | public void IsDisposedTest() 18 | { 19 | Ciphertext cipher = new Ciphertext(); 20 | Assert.IsNotNull(cipher); 21 | Assert.AreEqual(0ul, cipher.Size); 22 | Assert.AreEqual(0ul, cipher.PolyModulusDegree); 23 | Assert.AreEqual(0ul, cipher.CoeffModulusSize); 24 | 25 | // After disposing object, accessing any field should fail. 26 | cipher.Dispose(); 27 | Utilities.AssertThrows<ObjectDisposedException>(() => cipher.Size); 28 | Utilities.AssertThrows<ObjectDisposedException>(() => cipher.PolyModulusDegree); 29 | Utilities.AssertThrows<ObjectDisposedException>(() => cipher.CoeffModulusSize); 30 | Utilities.AssertThrows<ObjectDisposedException>(() => cipher.IsTransparent); 31 | Utilities.AssertThrows<ObjectDisposedException>(() => cipher.IsNTTForm); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dotnet/tests/ParmsIdTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Research.SEAL; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace SEALNetTest 8 | { 9 | [TestClass] 10 | public class ParmsIdTests 11 | { 12 | [TestMethod] 13 | public void ParamIDConstructorTest() 14 | { 15 | ParmsId id = new ParmsId(); 16 | 17 | Assert.AreEqual(0ul, id.Block[0]); 18 | Assert.AreEqual(0ul, id.Block[1]); 19 | Assert.AreEqual(0ul, id.Block[2]); 20 | Assert.AreEqual(0ul, id.Block[3]); 21 | 22 | id.Block[0] = 5; 23 | id.Block[1] = 4; 24 | id.Block[2] = 3; 25 | id.Block[3] = 2; 26 | 27 | ParmsId id2 = new ParmsId(id); 28 | 29 | id.Block[1] = 7; 30 | 31 | Assert.AreEqual(5ul, id2.Block[0]); 32 | Assert.AreEqual(4ul, id2.Block[1]); 33 | Assert.AreEqual(3ul, id2.Block[2]); 34 | Assert.AreEqual(2ul, id2.Block[3]); 35 | Assert.AreEqual(7ul, id.Block[1]); 36 | 37 | Assert.IsFalse(id2.Equals(null)); 38 | Assert.AreNotEqual(id.GetHashCode(), id2.GetHashCode()); 39 | } 40 | 41 | [TestMethod] 42 | public void ToStringTest() 43 | { 44 | ParmsId id = new ParmsId(); 45 | 46 | id.Block[0] = 1; 47 | id.Block[1] = 2; 48 | id.Block[2] = 3; 49 | id.Block[3] = 4; 50 | 51 | Assert.AreEqual("0000000000000001 0000000000000002 0000000000000003 0000000000000004", id.ToString()); 52 | } 53 | 54 | [TestMethod] 55 | public void OperatorsTest() 56 | { 57 | ParmsId id = new ParmsId(); 58 | 59 | id.Block[0] = 1; 60 | id.Block[1] = 2; 61 | id.Block[2] = 3; 62 | id.Block[3] = 4; 63 | 64 | ParmsId id2 = new ParmsId(id); 65 | 66 | ParmsId id3 = new ParmsId(id); 67 | id3.Block[0] = 2; 68 | 69 | Assert.IsTrue(id == id2); 70 | Assert.IsFalse(id == id3); 71 | 72 | ParmsId id_null1 = null; 73 | ParmsId id_null2 = null; 74 | 75 | Assert.IsFalse(id_null1 != id_null2); 76 | Assert.IsTrue(id_null1 != id); 77 | } 78 | 79 | [TestMethod] 80 | public void ExceptionsTest() 81 | { 82 | ParmsId id = new ParmsId(); 83 | ParmsId id_null = null; 84 | 85 | Utilities.AssertThrows<ArgumentNullException>(() => id = new ParmsId(id_null)); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /dotnet/tests/SEALNetTest.csproj.in: -------------------------------------------------------------------------------- 1 | <Project Sdk="Microsoft.NET.Sdk"> 2 | 3 | <PropertyGroup> 4 | <TargetFramework>net6.0</TargetFramework> 5 | <IsPackable>false</IsPackable> 6 | <Authors>Microsoft Research</Authors> 7 | <Company>Microsoft Corporation</Company> 8 | <Description>.NET wrapper unit tests for Microsoft SEAL</Description> 9 | <Copyright>Microsoft Corporation 2022</Copyright> 10 | </PropertyGroup> 11 | 12 | <PropertyGroup> 13 | <PlatformTarget>x64</PlatformTarget> 14 | <OutputPath>@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/dotnet/$(Configuration)</OutputPath> 15 | </PropertyGroup> 16 | 17 | <ItemGroup> 18 | <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> 19 | <PackageReference Include="MSTest.TestAdapter" Version="2.2.8" /> 20 | <PackageReference Include="MSTest.TestFramework" Version="2.2.8" /> 21 | </ItemGroup> 22 | 23 | <ItemGroup> 24 | <ProjectReference Include="$(ProjectDir)../src/SEALNet.csproj" /> 25 | </ItemGroup> 26 | 27 | <ItemGroup> 28 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(Windows))" Include="@SEAL_WINDOWS_SEAL_C_DIRECTORY@\sealc.dll" /> 29 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(Linux))" Include="@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/libsealc.so*" /> 30 | <SEALCBinaryFiles Condition="$([MSBuild]::IsOsPlatform(OSX))" Include="@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/libsealc*.dylib" /> 31 | </ItemGroup> 32 | 33 | <Target Name="PostBuild" AfterTargets="PostBuildEvent"> 34 | <Copy SourceFiles="@(SEALCBinaryFiles)" DestinationFolder="$(TargetDir)" /> 35 | </Target> 36 | 37 | <ItemGroup> 38 | <Compile Include="@CMAKE_CURRENT_SOURCE_DIR@\dotnet\tests\**\*.cs" /> 39 | </ItemGroup> 40 | </Project> 41 | -------------------------------------------------------------------------------- /dotnet/tests/TestAssemblyCleanup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | 7 | namespace SEALNetTest 8 | { 9 | [TestClass] 10 | public class TestAssemblyCleanup 11 | { 12 | [AssemblyCleanup] 13 | public static void AssemblyCleanup() 14 | { 15 | // Check that our Assert.Throw workaround is not getting out of hand 16 | Assert.IsTrue(Utilities.WorkaroundInstanceCount <= 2, quot;WorkaroundInstanceCount should be <= 2, it is: {Utilities.WorkaroundInstanceCount}"); 17 | Trace.WriteLine(quot;Assert.Throw workaround instances found: {Utilities.WorkaroundInstanceCount}"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /native/bench/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | cmake_minimum_required(VERSION 3.13) 5 | 6 | project(SEALBench VERSION 4.1.1 LANGUAGES CXX) 7 | 8 | # If not called from root CMakeLists.txt 9 | if(NOT DEFINED SEAL_BUILD_BENCH) 10 | set(SEAL_BUILD_BENCH ON) 11 | 12 | # Import Microsoft SEAL 13 | find_package(SEAL 4.1.1 EXACT REQUIRED) 14 | 15 | # Must define these variables and include macros 16 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${OUTLIB_PATH}) 17 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) 18 | set(SEAL_THIRDPARTY_DIR ${CMAKE_CURRENT_LIST_DIR}/../../thirdparty) 19 | set(THIRDPARTY_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/thirdparty) 20 | include(FetchContent) 21 | mark_as_advanced(FETCHCONTENT_BASE_DIR) 22 | mark_as_advanced(FETCHCONTENT_FULLY_DISCONNECTED) 23 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED) 24 | mark_as_advanced(FETCHCONTENT_QUIET) 25 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../cmake) 26 | include(SEALMacros) 27 | else() 28 | set(THIRDPARTY_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/../../thirdparty) 29 | endif() 30 | 31 | if(NOT DEFINED SEAL_BUILD_DEPS) 32 | # [option] SEAL_BUILD_DEPS (default: ON) 33 | # Download and build missing dependencies, throw error if disabled. 34 | set(SEAL_BUILD_DEPS_OPTION_STR "Automatically download and build unmet dependencies") 35 | option(SEAL_BUILD_DEPS ${SEAL_BUILD_DEPS_OPTION_STR} ON) 36 | endif() 37 | 38 | # if SEAL_BUILD_BENCH is ON, use GoogleBenchmark 39 | if(SEAL_BUILD_BENCH) 40 | if(SEAL_BUILD_DEPS) 41 | seal_fetch_thirdparty_content(ExternalBenchmark) 42 | else() 43 | find_package(benchmark REQUIRED) 44 | if(NOT benchmark_FOUND) 45 | message(FATAL_ERROR "GoogleBenchmark: not found") 46 | else() 47 | message(STATUS "GoogleBenchmark: found") 48 | endif() 49 | endif() 50 | 51 | add_executable(sealbench) 52 | # If we're targeting WASM, add the appropriate link flags 53 | if(EMSCRIPTEN) 54 | set_target_properties(sealbench PROPERTIES LINK_FLAGS "-flto -O3 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s MAXIMUM_MEMORY=4GB") 55 | endif() 56 | target_sources(sealbench 57 | PRIVATE 58 | ${CMAKE_CURRENT_LIST_DIR}/bench.cpp 59 | ${CMAKE_CURRENT_LIST_DIR}/keygen.cpp 60 | ${CMAKE_CURRENT_LIST_DIR}/ntt.cpp 61 | ${CMAKE_CURRENT_LIST_DIR}/bfv.cpp 62 | ${CMAKE_CURRENT_LIST_DIR}/bgv.cpp 63 | ${CMAKE_CURRENT_LIST_DIR}/ckks.cpp 64 | ) 65 | 66 | if(TARGET SEAL::seal) 67 | target_link_libraries(sealbench PRIVATE SEAL::seal benchmark::benchmark) 68 | elseif(TARGET SEAL::seal_shared) 69 | target_link_libraries(sealbench PRIVATE SEAL::seal_shared benchmark::benchmark) 70 | else() 71 | message(FATAL_ERROR "Cannot find target SEAL::seal or SEAL::seal_shared") 72 | endif() 73 | endif() 74 | -------------------------------------------------------------------------------- /native/bench/keygen.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/seal.h" 5 | #include "seal/util/rlwe.h" 6 | #include "bench.h" 7 | 8 | using namespace benchmark; 9 | using namespace sealbench; 10 | using namespace seal; 11 | using namespace std; 12 | 13 | /** 14 | This file defines benchmarks for KeyGen-related HE primitives. 15 | */ 16 | 17 | namespace seal 18 | { 19 | struct KeyGenerator::KeyGeneratorPrivateHelper 20 | { 21 | static void generate_sk(KeyGenerator *keygen) 22 | { 23 | return keygen->generate_sk(); 24 | } 25 | }; 26 | } // namespace seal 27 | 28 | namespace sealbench 29 | { 30 | void bm_keygen_secret(State &state, shared_ptr<BMEnv> bm_env) 31 | { 32 | KeyGenerator keygen(bm_env->context()); 33 | for (auto _ : state) 34 | { 35 | KeyGenerator::KeyGeneratorPrivateHelper::generate_sk(&keygen); 36 | } 37 | } 38 | 39 | void bm_keygen_public(State &state, shared_ptr<BMEnv> bm_env) 40 | { 41 | shared_ptr<KeyGenerator> keygen = bm_env->keygen(); 42 | PublicKey pk; 43 | for (auto _ : state) 44 | { 45 | keygen->create_public_key(pk); 46 | } 47 | } 48 | 49 | void bm_keygen_relin(State &state, shared_ptr<BMEnv> bm_env) 50 | { 51 | shared_ptr<KeyGenerator> keygen = bm_env->keygen(); 52 | RelinKeys rlk; 53 | for (auto _ : state) 54 | { 55 | keygen->create_relin_keys(rlk); 56 | } 57 | } 58 | 59 | void bm_keygen_galois(State &state, shared_ptr<BMEnv> bm_env) 60 | { 61 | shared_ptr<KeyGenerator> keygen = bm_env->keygen(); 62 | GaloisKeys glk; 63 | size_t slot_count = bm_env->parms().poly_modulus_degree() >> 1; 64 | 65 | auto random_one_step = [&]() { 66 | vector<int> res; 67 | res.emplace_back(rand() & static_cast<int>(slot_count - 1)); 68 | return res; 69 | }; 70 | 71 | for (auto _ : state) 72 | { 73 | keygen->create_galois_keys({ random_one_step() }, glk); 74 | } 75 | } 76 | } // namespace sealbench 77 | -------------------------------------------------------------------------------- /native/examples/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | cmake_minimum_required(VERSION 3.13) 5 | 6 | project(SEALExamples VERSION 4.1.2 LANGUAGES CXX) 7 | 8 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 9 | 10 | # If not called from root CMakeLists.txt 11 | if(NOT DEFINED SEAL_BUILD_EXAMPLES) 12 | set(SEAL_BUILD_EXAMPLES ON) 13 | 14 | # Import Microsoft SEAL 15 | find_package(SEAL 4.1.2 EXACT REQUIRED) 16 | 17 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) 18 | endif() 19 | 20 | if(SEAL_BUILD_EXAMPLES) 21 | add_executable(sealexamples) 22 | 23 | target_sources(sealexamples 24 | PRIVATE 25 | ${CMAKE_CURRENT_LIST_DIR}/examples.cpp 26 | ${CMAKE_CURRENT_LIST_DIR}/1_bfv_basics.cpp 27 | ${CMAKE_CURRENT_LIST_DIR}/2_encoders.cpp 28 | ${CMAKE_CURRENT_LIST_DIR}/3_levels.cpp 29 | ${CMAKE_CURRENT_LIST_DIR}/4_bgv_basics.cpp 30 | ${CMAKE_CURRENT_LIST_DIR}/5_ckks_basics.cpp 31 | ${CMAKE_CURRENT_LIST_DIR}/6_rotation.cpp 32 | ${CMAKE_CURRENT_LIST_DIR}/7_serialization.cpp 33 | ${CMAKE_CURRENT_LIST_DIR}/8_performance.cpp 34 | ) 35 | 36 | if(TARGET SEAL::seal) 37 | target_link_libraries(sealexamples PRIVATE SEAL::seal) 38 | elseif(TARGET SEAL::seal_shared) 39 | target_link_libraries(sealexamples PRIVATE SEAL::seal_shared) 40 | else() 41 | message(FATAL_ERROR "Cannot find target SEAL::seal or SEAL::seal_shared") 42 | endif() 43 | endif() 44 | -------------------------------------------------------------------------------- /native/src/seal/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Source files in this directory 5 | set(SEAL_SOURCE_FILES ${SEAL_SOURCE_FILES} 6 | ${CMAKE_CURRENT_LIST_DIR}/batchencoder.cpp 7 | ${CMAKE_CURRENT_LIST_DIR}/ciphertext.cpp 8 | ${CMAKE_CURRENT_LIST_DIR}/ckks.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/context.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/decryptor.cpp 11 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparams.cpp 12 | ${CMAKE_CURRENT_LIST_DIR}/encryptor.cpp 13 | ${CMAKE_CURRENT_LIST_DIR}/evaluator.cpp 14 | ${CMAKE_CURRENT_LIST_DIR}/keygenerator.cpp 15 | ${CMAKE_CURRENT_LIST_DIR}/kswitchkeys.cpp 16 | ${CMAKE_CURRENT_LIST_DIR}/memorymanager.cpp 17 | ${CMAKE_CURRENT_LIST_DIR}/modulus.cpp 18 | ${CMAKE_CURRENT_LIST_DIR}/plaintext.cpp 19 | ${CMAKE_CURRENT_LIST_DIR}/randomgen.cpp 20 | ${CMAKE_CURRENT_LIST_DIR}/serialization.cpp 21 | ${CMAKE_CURRENT_LIST_DIR}/valcheck.cpp 22 | ) 23 | 24 | # Add header files for installation 25 | install( 26 | FILES 27 | ${CMAKE_CURRENT_LIST_DIR}/batchencoder.h 28 | ${CMAKE_CURRENT_LIST_DIR}/ciphertext.h 29 | ${CMAKE_CURRENT_LIST_DIR}/ckks.h 30 | ${CMAKE_CURRENT_LIST_DIR}/modulus.h 31 | ${CMAKE_CURRENT_LIST_DIR}/context.h 32 | ${CMAKE_CURRENT_LIST_DIR}/decryptor.h 33 | ${CMAKE_CURRENT_LIST_DIR}/dynarray.h 34 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparams.h 35 | ${CMAKE_CURRENT_LIST_DIR}/encryptor.h 36 | ${CMAKE_CURRENT_LIST_DIR}/evaluator.h 37 | ${CMAKE_CURRENT_LIST_DIR}/galoiskeys.h 38 | ${CMAKE_CURRENT_LIST_DIR}/keygenerator.h 39 | ${CMAKE_CURRENT_LIST_DIR}/kswitchkeys.h 40 | ${CMAKE_CURRENT_LIST_DIR}/memorymanager.h 41 | ${CMAKE_CURRENT_LIST_DIR}/plaintext.h 42 | ${CMAKE_CURRENT_LIST_DIR}/publickey.h 43 | ${CMAKE_CURRENT_LIST_DIR}/randomgen.h 44 | ${CMAKE_CURRENT_LIST_DIR}/randomtostd.h 45 | ${CMAKE_CURRENT_LIST_DIR}/relinkeys.h 46 | ${CMAKE_CURRENT_LIST_DIR}/seal.h 47 | ${CMAKE_CURRENT_LIST_DIR}/secretkey.h 48 | ${CMAKE_CURRENT_LIST_DIR}/serializable.h 49 | ${CMAKE_CURRENT_LIST_DIR}/serialization.h 50 | ${CMAKE_CURRENT_LIST_DIR}/valcheck.h 51 | ${CMAKE_CURRENT_LIST_DIR}/version.h 52 | DESTINATION 53 | ${SEAL_INCLUDES_INSTALL_DIR}/seal 54 | ) 55 | 56 | add_subdirectory(util) 57 | set(SEAL_SOURCE_FILES ${SEAL_SOURCE_FILES} PARENT_SCOPE) 58 | -------------------------------------------------------------------------------- /native/src/seal/c/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Source files in this directory 5 | target_sources(sealc PRIVATE 6 | ${CMAKE_CURRENT_LIST_DIR}/batchencoder.cpp 7 | ${CMAKE_CURRENT_LIST_DIR}/ciphertext.cpp 8 | ${CMAKE_CURRENT_LIST_DIR}/ckksencoder.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/contextdata.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/decryptor.cpp 11 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparameterqualifiers.cpp 12 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparameters.cpp 13 | ${CMAKE_CURRENT_LIST_DIR}/encryptor.cpp 14 | ${CMAKE_CURRENT_LIST_DIR}/evaluator.cpp 15 | ${CMAKE_CURRENT_LIST_DIR}/galoiskeys.cpp 16 | ${CMAKE_CURRENT_LIST_DIR}/keygenerator.cpp 17 | ${CMAKE_CURRENT_LIST_DIR}/kswitchkeys.cpp 18 | ${CMAKE_CURRENT_LIST_DIR}/memorymanager.cpp 19 | ${CMAKE_CURRENT_LIST_DIR}/memorypoolhandle.cpp 20 | ${CMAKE_CURRENT_LIST_DIR}/modulus.cpp 21 | ${CMAKE_CURRENT_LIST_DIR}/plaintext.cpp 22 | ${CMAKE_CURRENT_LIST_DIR}/publickey.cpp 23 | ${CMAKE_CURRENT_LIST_DIR}/relinkeys.cpp 24 | ${CMAKE_CURRENT_LIST_DIR}/sealcontext.cpp 25 | ${CMAKE_CURRENT_LIST_DIR}/secretkey.cpp 26 | ${CMAKE_CURRENT_LIST_DIR}/serialization.cpp 27 | ${CMAKE_CURRENT_LIST_DIR}/utilities.cpp 28 | ${CMAKE_CURRENT_LIST_DIR}/valcheck.cpp 29 | ${CMAKE_CURRENT_LIST_DIR}/version.cpp 30 | ) 31 | 32 | # Add header files for installation 33 | install( 34 | FILES 35 | ${CMAKE_CURRENT_LIST_DIR}/batchencoder.h 36 | ${CMAKE_CURRENT_LIST_DIR}/ciphertext.h 37 | ${CMAKE_CURRENT_LIST_DIR}/ckksencoder.h 38 | ${CMAKE_CURRENT_LIST_DIR}/contextdata.h 39 | ${CMAKE_CURRENT_LIST_DIR}/decryptor.h 40 | ${CMAKE_CURRENT_LIST_DIR}/defines.h 41 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparameterqualifiers.h 42 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparameters.h 43 | ${CMAKE_CURRENT_LIST_DIR}/encryptor.h 44 | ${CMAKE_CURRENT_LIST_DIR}/evaluator.h 45 | ${CMAKE_CURRENT_LIST_DIR}/galoiskeys.h 46 | ${CMAKE_CURRENT_LIST_DIR}/keygenerator.h 47 | ${CMAKE_CURRENT_LIST_DIR}/kswitchkeys.h 48 | ${CMAKE_CURRENT_LIST_DIR}/memorymanager.h 49 | ${CMAKE_CURRENT_LIST_DIR}/memorypoolhandle.h 50 | ${CMAKE_CURRENT_LIST_DIR}/modulus.h 51 | ${CMAKE_CURRENT_LIST_DIR}/plaintext.h 52 | ${CMAKE_CURRENT_LIST_DIR}/publickey.h 53 | ${CMAKE_CURRENT_LIST_DIR}/relinkeys.h 54 | ${CMAKE_CURRENT_LIST_DIR}/sealcontext.h 55 | ${CMAKE_CURRENT_LIST_DIR}/secretkey.h 56 | ${CMAKE_CURRENT_LIST_DIR}/serialization.h 57 | ${CMAKE_CURRENT_LIST_DIR}/stdafx.h 58 | ${CMAKE_CURRENT_LIST_DIR}/targetver.h 59 | ${CMAKE_CURRENT_LIST_DIR}/utilities.h 60 | ${CMAKE_CURRENT_LIST_DIR}/valcheck.h 61 | ${CMAKE_CURRENT_LIST_DIR}/version.h 62 | DESTINATION 63 | ${SEAL_INCLUDES_INSTALL_DIR}/seal/c 64 | ) 65 | -------------------------------------------------------------------------------- /native/src/seal/c/batchencoder.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC BatchEncoder_Create(void *context, void **batch_encoder); 17 | 18 | SEAL_C_FUNC BatchEncoder_Destroy(void *thisptr); 19 | 20 | SEAL_C_FUNC BatchEncoder_Encode1(void *thisptr, uint64_t count, uint64_t *values, void *destination); 21 | 22 | SEAL_C_FUNC BatchEncoder_Encode2(void *thisptr, uint64_t count, int64_t *values, void *destination); 23 | 24 | SEAL_C_FUNC BatchEncoder_Decode1(void *thisptr, void *plain, uint64_t *count, uint64_t *destination, void *pool); 25 | 26 | SEAL_C_FUNC BatchEncoder_Decode2(void *thisptr, void *plain, uint64_t *count, int64_t *destination, void *pool); 27 | 28 | SEAL_C_FUNC BatchEncoder_GetSlotCount(void *thisptr, uint64_t *slot_count); 29 | -------------------------------------------------------------------------------- /native/src/seal/c/ciphertext.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Ciphertext_Create1(void *pool, void **cipher); 17 | 18 | SEAL_C_FUNC Ciphertext_Create2(void *copy, void **cipher); 19 | 20 | SEAL_C_FUNC Ciphertext_Create3(void *context, void *pool, void **cipher); 21 | 22 | SEAL_C_FUNC Ciphertext_Create4(void *context, uint64_t *parms_id, void *pool, void **cipher); 23 | 24 | SEAL_C_FUNC Ciphertext_Create5(void *context, uint64_t *parms_id, uint64_t capacity, void *pool, void **ciphertext); 25 | 26 | SEAL_C_FUNC Ciphertext_Reserve1(void *thisptr, void *context, uint64_t *parms_id, uint64_t size_capacity); 27 | 28 | SEAL_C_FUNC Ciphertext_Reserve2(void *thisptr, void *context, uint64_t size_capacity); 29 | 30 | SEAL_C_FUNC Ciphertext_Reserve3(void *thisptr, uint64_t size_capacity); 31 | 32 | SEAL_C_FUNC Ciphertext_Set(void *thisptr, void *assign); 33 | 34 | SEAL_C_FUNC Ciphertext_Destroy(void *thisptr); 35 | 36 | SEAL_C_FUNC Ciphertext_Size(void *thisptr, uint64_t *size); 37 | 38 | SEAL_C_FUNC Ciphertext_SizeCapacity(void *thisptr, uint64_t *size_capacity); 39 | 40 | SEAL_C_FUNC Ciphertext_PolyModulusDegree(void *thisptr, uint64_t *poly_modulus_degree); 41 | 42 | SEAL_C_FUNC Ciphertext_CoeffModulusSize(void *thisptr, uint64_t *coeff_modulus_size); 43 | 44 | SEAL_C_FUNC Ciphertext_ParmsId(void *thisptr, uint64_t *parms_id); 45 | 46 | SEAL_C_FUNC Ciphertext_SetParmsId(void *thisptr, uint64_t *parms_id); 47 | 48 | SEAL_C_FUNC Ciphertext_Resize1(void *thisptr, void *context, uint64_t *parms_id, uint64_t size); 49 | 50 | SEAL_C_FUNC Ciphertext_Resize2(void *thisptr, void *context, uint64_t size); 51 | 52 | SEAL_C_FUNC Ciphertext_Resize3(void *thisptr, uint64_t size); 53 | 54 | SEAL_C_FUNC Ciphertext_Resize4(void *thisptr, uint64_t size, uint64_t polyModulusDegree, uint64_t coeffModCount); 55 | 56 | SEAL_C_FUNC Ciphertext_GetDataAt1(void *thisptr, uint64_t index, uint64_t *data); 57 | 58 | SEAL_C_FUNC Ciphertext_GetDataAt2(void *thisptr, uint64_t poly_index, uint64_t coeff_index, uint64_t *data); 59 | 60 | SEAL_C_FUNC Ciphertext_SetDataAt(void *thisptr, uint64_t index, uint64_t value); 61 | 62 | SEAL_C_FUNC Ciphertext_IsNTTForm(void *thisptr, bool *is_ntt_form); 63 | 64 | SEAL_C_FUNC Ciphertext_SetIsNTTForm(void *thisptr, bool is_ntt_form); 65 | 66 | SEAL_C_FUNC Ciphertext_Scale(void *thisptr, double *scale); 67 | 68 | SEAL_C_FUNC Ciphertext_SetScale(void *thisptr, double scale); 69 | 70 | SEAL_C_FUNC Ciphertext_CorrectionFactor(void *thisptr, uint64_t *correction_factor); 71 | 72 | SEAL_C_FUNC Ciphertext_SetCorrectionFactor(void *thisptr, uint64_t correction_factor); 73 | 74 | SEAL_C_FUNC Ciphertext_Release(void *thisptr); 75 | 76 | SEAL_C_FUNC Ciphertext_IsTransparent(void *thisptr, bool *result); 77 | 78 | SEAL_C_FUNC Ciphertext_Pool(void *thisptr, void **pool); 79 | 80 | SEAL_C_FUNC Ciphertext_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 81 | 82 | SEAL_C_FUNC Ciphertext_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 83 | 84 | SEAL_C_FUNC Ciphertext_UnsafeLoad(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 85 | 86 | SEAL_C_FUNC Ciphertext_Load(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 87 | -------------------------------------------------------------------------------- /native/src/seal/c/ckksencoder.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC CKKSEncoder_Create(void *context, void **ckks_encoder); 17 | 18 | SEAL_C_FUNC CKKSEncoder_Destroy(void *thisptr); 19 | 20 | // Array of doubles 21 | SEAL_C_FUNC CKKSEncoder_Encode1( 22 | void *thisptr, uint64_t value_count, double *values, uint64_t *parms_id, double scale, void *destination, 23 | void *pool); 24 | 25 | // Array of complex numbers (two doubles per value) 26 | SEAL_C_FUNC CKKSEncoder_Encode2( 27 | void *thisptr, uint64_t value_count, double *complex_values, uint64_t *parms_id, double scale, void *destination, 28 | void *pool); 29 | 30 | // Single double value 31 | SEAL_C_FUNC CKKSEncoder_Encode3( 32 | void *thisptr, double value, uint64_t *parms_id, double scale, void *destination, void *pool); 33 | 34 | // Single complex value 35 | SEAL_C_FUNC CKKSEncoder_Encode4( 36 | void *thisptr, double value_re, double value_im, uint64_t *parms_id, double scale, void *destination, void *pool); 37 | 38 | // Single Int64 value 39 | SEAL_C_FUNC CKKSEncoder_Encode5(void *thisptr, int64_t value, uint64_t *parms_id, void *destination); 40 | 41 | // Array of doubles 42 | SEAL_C_FUNC CKKSEncoder_Decode1(void *thisptr, void *plain, uint64_t *value_count, double *values, void *pool); 43 | 44 | // Array of complex numbers 45 | SEAL_C_FUNC CKKSEncoder_Decode2(void *thisptr, void *plain, uint64_t *value_count, double *values, void *pool); 46 | 47 | SEAL_C_FUNC CKKSEncoder_SlotCount(void *thisptr, uint64_t *slot_count); 48 | -------------------------------------------------------------------------------- /native/src/seal/c/contextdata.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC ContextData_Destroy(void *thisptr); 17 | 18 | SEAL_C_FUNC ContextData_TotalCoeffModulus(void *thisptr, uint64_t *count, uint64_t *total_coeff_modulus); 19 | 20 | SEAL_C_FUNC ContextData_TotalCoeffModulusBitCount(void *thisptr, int *bit_count); 21 | 22 | SEAL_C_FUNC ContextData_Parms(void *thisptr, void **parms); 23 | 24 | SEAL_C_FUNC ContextData_Qualifiers(void *thisptr, void **epq); 25 | 26 | SEAL_C_FUNC ContextData_CoeffDivPlainModulus(void *thisptr, uint64_t *count, uint64_t *coeff_div); 27 | 28 | SEAL_C_FUNC ContextData_PlainUpperHalfThreshold(void *thisptr, uint64_t *puht); 29 | 30 | SEAL_C_FUNC ContextData_PlainUpperHalfIncrement(void *thisptr, uint64_t *count, uint64_t *puhi); 31 | 32 | SEAL_C_FUNC ContextData_UpperHalfThreshold(void *thisptr, uint64_t *count, uint64_t *uht); 33 | 34 | SEAL_C_FUNC ContextData_UpperHalfIncrement(void *thisptr, uint64_t *count, uint64_t *uhi); 35 | 36 | SEAL_C_FUNC ContextData_PrevContextData(void *thisptr, void **prev_data); 37 | 38 | SEAL_C_FUNC ContextData_NextContextData(void *thisptr, void **next_data); 39 | 40 | SEAL_C_FUNC ContextData_ChainIndex(void *thisptr, uint64_t *index); 41 | -------------------------------------------------------------------------------- /native/src/seal/c/decryptor.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/decryptor.h" 6 | #include "seal/c/utilities.h" 7 | 8 | // SEAL 9 | #include "seal/decryptor.h" 10 | 11 | using namespace std; 12 | using namespace seal; 13 | using namespace seal::c; 14 | 15 | SEAL_C_FUNC Decryptor_Create(void *context, void *secret_key, void **decryptor) 16 | { 17 | const SEALContext *ctx = FromVoid<SEALContext>(context); 18 | IfNullRet(ctx, E_POINTER); 19 | SecretKey *secretKey = FromVoid<SecretKey>(secret_key); 20 | IfNullRet(secretKey, E_POINTER); 21 | IfNullRet(decryptor, E_POINTER); 22 | 23 | try 24 | { 25 | Decryptor *decr = new Decryptor(*ctx, *secretKey); 26 | *decryptor = decr; 27 | return S_OK; 28 | } 29 | catch (const invalid_argument &) 30 | { 31 | return E_INVALIDARG; 32 | } 33 | } 34 | 35 | SEAL_C_FUNC Decryptor_Destroy(void *thisptr) 36 | { 37 | Decryptor *decryptor = FromVoid<Decryptor>(thisptr); 38 | IfNullRet(decryptor, E_POINTER); 39 | 40 | delete decryptor; 41 | return S_OK; 42 | } 43 | 44 | SEAL_C_FUNC Decryptor_Decrypt(void *thisptr, void *encrypted, void *destination) 45 | { 46 | Decryptor *decryptor = FromVoid<Decryptor>(thisptr); 47 | IfNullRet(decryptor, E_POINTER); 48 | Ciphertext *encryptedptr = FromVoid<Ciphertext>(encrypted); 49 | IfNullRet(encryptedptr, E_POINTER); 50 | Plaintext *destinationptr = FromVoid<Plaintext>(destination); 51 | IfNullRet(destinationptr, E_POINTER); 52 | 53 | try 54 | { 55 | decryptor->decrypt(*encryptedptr, *destinationptr); 56 | return S_OK; 57 | } 58 | catch (const invalid_argument &) 59 | { 60 | return E_INVALIDARG; 61 | } 62 | } 63 | 64 | SEAL_C_FUNC Decryptor_InvariantNoiseBudget(void *thisptr, void *encrypted, int *invariant_noise_budget) 65 | { 66 | Decryptor *decryptor = FromVoid<Decryptor>(thisptr); 67 | IfNullRet(decryptor, E_POINTER); 68 | Ciphertext *encryptedptr = FromVoid<Ciphertext>(encrypted); 69 | IfNullRet(encryptedptr, E_POINTER); 70 | IfNullRet(invariant_noise_budget, E_POINTER); 71 | 72 | try 73 | { 74 | *invariant_noise_budget = decryptor->invariant_noise_budget(*encryptedptr); 75 | return S_OK; 76 | } 77 | catch (const invalid_argument &) 78 | { 79 | return E_INVALIDARG; 80 | } 81 | catch (const logic_error &) 82 | { 83 | return COR_E_INVALIDOPERATION; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /native/src/seal/c/decryptor.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Decryptor_Create(void *context, void *secret_key, void **decryptor); 17 | 18 | SEAL_C_FUNC Decryptor_Destroy(void *thisptr); 19 | 20 | SEAL_C_FUNC Decryptor_Decrypt(void *thisptr, void *encrypted, void *destination); 21 | 22 | SEAL_C_FUNC Decryptor_InvariantNoiseBudget(void *thisptr, void *encrypted, int *invariant_noise_budget); 23 | -------------------------------------------------------------------------------- /native/src/seal/c/defines.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | // STD 7 | #include <cstddef> 8 | 9 | // SEALNet 10 | #include "seal/c/stdafx.h" 11 | 12 | // Check that std::size_t is 64 bits 13 | static_assert(sizeof(std::size_t) == 8, "Require sizeof(std::size_t) == 8"); 14 | 15 | #ifdef _MSC_VER 16 | 17 | // Check that architecture (platform) is x64 18 | #ifndef _WIN64 19 | static_assert(false, "Require architecture == x64"); 20 | #endif 21 | 22 | #if defined(SEAL_C_EXPORTS) || defined(seal_c_EXPORTS) || defined(sealc_EXPORTS) 23 | #define SEAL_C_DECOR extern "C" __declspec(dllexport) 24 | #else 25 | #define SEAL_C_DECOR extern "C" __declspec(dllimport) 26 | #endif 27 | 28 | #define SEAL_C_CALL __cdecl 29 | 30 | #else // _MSC_VER 31 | 32 | #define SEAL_C_DECOR extern "C" 33 | #define SEAL_C_CALL 34 | 35 | #define HRESULT long 36 | 37 | #define _HRESULT_TYPEDEF_(hr) ((HRESULT)hr) 38 | 39 | #define E_POINTER _HRESULT_TYPEDEF_(0x80004003L) 40 | #define E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L) 41 | #define E_OUTOFMEMORY _HRESULT_TYPEDEF_(0x8007000EL) 42 | #define E_UNEXPECTED _HRESULT_TYPEDEF_(0x8000FFFFL) 43 | #define COR_E_IO _HRESULT_TYPEDEF_(0x80131620L) 44 | #define COR_E_INVALIDOPERATION _HRESULT_TYPEDEF_(0x80131509L) 45 | 46 | #define S_OK _HRESULT_TYPEDEF_(0L) 47 | #define S_FALSE _HRESULT_TYPEDEF_(1L) 48 | 49 | #define FACILITY_WIN32 7 50 | #define HRESULT_FROM_WIN32(x) \ 51 | ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT)(((x)&0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000))) 52 | 53 | #define ERROR_INSUFFICIENT_BUFFER 122L 54 | #define ERROR_INVALID_INDEX 1413L 55 | #define ERROR_INVALID_OPERATION 4317L 56 | 57 | #define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) 58 | #define FAILED(hr) (((HRESULT)(hr)) < 0) 59 | 60 | #endif // _MSC_VER 61 | 62 | #define SEAL_C_FUNC SEAL_C_DECOR HRESULT SEAL_C_CALL 63 | -------------------------------------------------------------------------------- /native/src/seal/c/encryptionparameterqualifiers.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC EPQ_Create(void *copy, void **epq); 17 | 18 | SEAL_C_FUNC EPQ_Destroy(void *thisptr); 19 | 20 | SEAL_C_FUNC EPQ_ParametersSet(void *thisptr, bool *parameters_set); 21 | 22 | SEAL_C_FUNC EPQ_UsingFFT(void *thisptr, bool *using_fft); 23 | 24 | SEAL_C_FUNC EPQ_UsingNTT(void *thisptr, bool *using_ntt); 25 | 26 | SEAL_C_FUNC EPQ_UsingBatching(void *thisptr, bool *using_batching); 27 | 28 | SEAL_C_FUNC EPQ_UsingFastPlainLift(void *thisptr, bool *using_fast_plain_lift); 29 | 30 | SEAL_C_FUNC EPQ_UsingDescendingModulusChain(void *thisptr, bool *using_descending_modulus_chain); 31 | 32 | SEAL_C_FUNC EPQ_SecLevel(void *thisptr, int *sec_level); 33 | 34 | SEAL_C_FUNC EPQ_ParameterErrorName(void *thisptr, char *outstr, uint64_t *length); 35 | 36 | SEAL_C_FUNC EPQ_ParameterErrorMessage(void *thisptr, char *outstr, uint64_t *length); 37 | -------------------------------------------------------------------------------- /native/src/seal/c/encryptionparameters.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC EncParams_Create1(uint8_t scheme, void **enc_params); 17 | 18 | SEAL_C_FUNC EncParams_Create2(void *copy, void **enc_params); 19 | 20 | SEAL_C_FUNC EncParams_Destroy(void *thisptr); 21 | 22 | SEAL_C_FUNC EncParams_Set(void *thisptr, void *assign); 23 | 24 | SEAL_C_FUNC EncParams_GetPolyModulusDegree(void *thisptr, uint64_t *degree); 25 | 26 | SEAL_C_FUNC EncParams_SetPolyModulusDegree(void *thisptr, uint64_t degree); 27 | 28 | SEAL_C_FUNC EncParams_GetCoeffModulus(void *thisptr, uint64_t *length, void **coeffs); 29 | 30 | SEAL_C_FUNC EncParams_SetCoeffModulus(void *thisptr, uint64_t length, void **coeffs); 31 | 32 | SEAL_C_FUNC EncParams_GetScheme(void *thisptr, uint8_t *scheme); 33 | 34 | SEAL_C_FUNC EncParams_GetParmsId(void *thisptr, uint64_t *parms_id); 35 | 36 | SEAL_C_FUNC EncParams_GetPlainModulus(void *thisptr, void **plain_modulus); 37 | 38 | SEAL_C_FUNC EncParams_SetPlainModulus1(void *thisptr, void *modulus); 39 | 40 | SEAL_C_FUNC EncParams_SetPlainModulus2(void *thisptr, uint64_t plain_modulus); 41 | 42 | SEAL_C_FUNC EncParams_Equals(void *thisptr, void *otherptr, bool *result); 43 | 44 | SEAL_C_FUNC EncParams_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 45 | 46 | SEAL_C_FUNC EncParams_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 47 | 48 | SEAL_C_FUNC EncParams_Load(void *thisptr, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 49 | -------------------------------------------------------------------------------- /native/src/seal/c/encryptor.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Encryptor_Create(void *context, void *public_key, void *secret_key, void **encryptor); 17 | 18 | SEAL_C_FUNC Encryptor_SetPublicKey(void *thisptr, void *public_key); 19 | 20 | SEAL_C_FUNC Encryptor_SetSecretKey(void *thisptr, void *secret_key); 21 | 22 | SEAL_C_FUNC Encryptor_Encrypt(void *thisptr, void *plaintext, void *destination, void *pool_handle); 23 | 24 | SEAL_C_FUNC Encryptor_EncryptZero1(void *thisptr, uint64_t *parms_id, void *destination, void *pool_handle); 25 | 26 | SEAL_C_FUNC Encryptor_EncryptZero2(void *thisptr, void *destination, void *pool_handle); 27 | 28 | SEAL_C_FUNC Encryptor_EncryptSymmetric( 29 | void *thisptr, void *plaintext, bool save_seed, void *destination, void *pool_handle); 30 | 31 | SEAL_C_FUNC Encryptor_EncryptZeroSymmetric1( 32 | void *thisptr, uint64_t *parms_id, bool save_seed, void *destination, void *pool_handle); 33 | 34 | SEAL_C_FUNC Encryptor_EncryptZeroSymmetric2(void *thisptr, bool save_seed, void *destination, void *pool_handle); 35 | 36 | SEAL_C_FUNC Encryptor_Destroy(void *thisptr); 37 | -------------------------------------------------------------------------------- /native/src/seal/c/galoiskeys.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/galoiskeys.h" 6 | #include "seal/c/utilities.h" 7 | 8 | // SEAL 9 | #include "seal/galoiskeys.h" 10 | 11 | using namespace std; 12 | using namespace seal; 13 | using namespace seal::c; 14 | 15 | SEAL_C_FUNC GaloisKeys_GetIndex(uint32_t galois_elt, uint64_t *index) 16 | { 17 | IfNullRet(index, E_POINTER); 18 | 19 | try 20 | { 21 | *index = GaloisKeys::get_index(galois_elt); 22 | return S_OK; 23 | } 24 | catch (const invalid_argument &) 25 | { 26 | return E_INVALIDARG; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /native/src/seal/c/galoiskeys.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC GaloisKeys_GetIndex(uint32_t galois_elt, uint64_t *index); 17 | -------------------------------------------------------------------------------- /native/src/seal/c/keygenerator.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC KeyGenerator_Create1(void *context, void **key_generator); 17 | 18 | SEAL_C_FUNC KeyGenerator_Create2(void *context, void *secret_key, void **key_generator); 19 | 20 | SEAL_C_FUNC KeyGenerator_Destroy(void *thisptr); 21 | 22 | SEAL_C_FUNC KeyGenerator_CreateRelinKeys(void *thisptr, bool save_seed, void **relin_keys); 23 | 24 | SEAL_C_FUNC KeyGenerator_CreateGaloisKeysFromElts( 25 | void *thisptr, uint64_t count, uint32_t *galois_elts, bool save_seed, void **galois_keys); 26 | 27 | SEAL_C_FUNC KeyGenerator_CreateGaloisKeysFromSteps( 28 | void *thisptr, uint64_t count, int *steps, bool save_seed, void **galois_keys); 29 | 30 | SEAL_C_FUNC KeyGenerator_CreateGaloisKeysAll(void *thisptr, bool save_seed, void **galois_keys); 31 | 32 | SEAL_C_FUNC KeyGenerator_CreatePublicKey(void *thisptr, bool save_seed, void **public_key); 33 | 34 | SEAL_C_FUNC KeyGenerator_SecretKey(void *thisptr, void **secret_key); 35 | 36 | SEAL_C_FUNC KeyGenerator_ContextUsingKeyswitching(void *thisptr, bool *using_keyswitching); 37 | -------------------------------------------------------------------------------- /native/src/seal/c/kswitchkeys.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC KSwitchKeys_Create1(void **kswitch_keys); 17 | 18 | SEAL_C_FUNC KSwitchKeys_Create2(void *copy, void **kswitch_keys); 19 | 20 | SEAL_C_FUNC KSwitchKeys_Destroy(void *thisptr); 21 | 22 | SEAL_C_FUNC KSwitchKeys_Set(void *thisptr, void *assign); 23 | 24 | SEAL_C_FUNC KSwitchKeys_Size(void *thisptr, uint64_t *size); 25 | 26 | SEAL_C_FUNC KSwitchKeys_RawSize(void *thisptr, uint64_t *key_count); 27 | 28 | SEAL_C_FUNC KSwitchKeys_GetKeyList(void *thisptr, uint64_t index, uint64_t *count, void **key_list); 29 | 30 | SEAL_C_FUNC KSwitchKeys_ClearDataAndReserve(void *thisptr, uint64_t size); 31 | 32 | SEAL_C_FUNC KSwitchKeys_AddKeyList(void *thisptr, uint64_t count, void **key_list); 33 | 34 | SEAL_C_FUNC KSwitchKeys_GetParmsId(void *thisptr, uint64_t *parms_id); 35 | 36 | SEAL_C_FUNC KSwitchKeys_SetParmsId(void *thisptr, uint64_t *parms_id); 37 | 38 | SEAL_C_FUNC KSwitchKeys_Pool(void *thisptr, void **pool); 39 | 40 | SEAL_C_FUNC KSwitchKeys_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 41 | 42 | SEAL_C_FUNC KSwitchKeys_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 43 | 44 | SEAL_C_FUNC KSwitchKeys_UnsafeLoad(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 45 | 46 | SEAL_C_FUNC KSwitchKeys_Load(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 47 | -------------------------------------------------------------------------------- /native/src/seal/c/memorymanager.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC MemoryManager_GetPool1(int prof_opt, bool clear_on_destruction, void **pool_handle); 17 | 18 | SEAL_C_FUNC MemoryManager_GetPool2(void **pool_handle); 19 | 20 | SEAL_C_FUNC MemoryManager_SwitchProfile(void *new_profile); 21 | 22 | SEAL_C_FUNC MMProf_CreateGlobal(void **profile); 23 | 24 | SEAL_C_FUNC MMProf_CreateFixed(void *pool, void **profile); 25 | 26 | SEAL_C_FUNC MMProf_CreateNew(void **profile); 27 | 28 | SEAL_C_FUNC MMProf_CreateThreadLocal(void **profile); 29 | 30 | SEAL_C_FUNC MMProf_GetPool(void *thisptr, void **pool_handle); 31 | 32 | SEAL_C_FUNC MMProf_Destroy(void *thisptr); 33 | -------------------------------------------------------------------------------- /native/src/seal/c/memorypoolhandle.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC MemoryPoolHandle_Create1(void **handle); 17 | 18 | SEAL_C_FUNC MemoryPoolHandle_Create2(void *otherptr, void **handle); 19 | 20 | SEAL_C_FUNC MemoryPoolHandle_Destroy(void *thisptr); 21 | 22 | SEAL_C_FUNC MemoryPoolHandle_Set(void *thisptr, void *assignptr); 23 | 24 | SEAL_C_FUNC MemoryPoolHandle_Global(void **handle); 25 | 26 | SEAL_C_FUNC MemoryPoolHandle_ThreadLocal(void **handle); 27 | 28 | SEAL_C_FUNC MemoryPoolHandle_New(bool clear_on_destruction, void **handle); 29 | 30 | SEAL_C_FUNC MemoryPoolHandle_PoolCount(void *thisptr, uint64_t *count); 31 | 32 | SEAL_C_FUNC MemoryPoolHandle_AllocByteCount(void *thisptr, uint64_t *count); 33 | 34 | SEAL_C_FUNC MemoryPoolHandle_UseCount(void *thisptr, long *count); 35 | 36 | SEAL_C_FUNC MemoryPoolHandle_IsInitialized(void *thisptr, bool *result); 37 | 38 | SEAL_C_FUNC MemoryPoolHandle_Equals(void *thisptr, void *otherptr, bool *result); 39 | -------------------------------------------------------------------------------- /native/src/seal/c/modulus.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Modulus_Create1(uint64_t value, void **small_modulus); 17 | 18 | SEAL_C_FUNC Modulus_Create2(void *copy, void **small_modulus); 19 | 20 | SEAL_C_FUNC Modulus_Destroy(void *thisptr); 21 | 22 | SEAL_C_FUNC Modulus_IsZero(void *thisptr, bool *is_zero); 23 | 24 | SEAL_C_FUNC Modulus_IsPrime(void *thisptr, bool *is_prime); 25 | 26 | SEAL_C_FUNC Modulus_Value(void *thisptr, uint64_t *value); 27 | 28 | SEAL_C_FUNC Modulus_BitCount(void *thisptr, int *bit_count); 29 | 30 | SEAL_C_FUNC Modulus_UInt64Count(void *thisptr, uint64_t *uint64_count); 31 | 32 | SEAL_C_FUNC Modulus_Set1(void *thisptr, void *assign); 33 | 34 | SEAL_C_FUNC Modulus_Set2(void *thisptr, uint64_t value); 35 | 36 | SEAL_C_FUNC Modulus_ConstRatio(void *thisptr, uint64_t length, uint64_t ratio[]); 37 | 38 | SEAL_C_FUNC Modulus_Equals1(void *thisptr, void *other, bool *result); 39 | 40 | SEAL_C_FUNC Modulus_Equals2(void *thisptr, uint64_t other, bool *result); 41 | 42 | SEAL_C_FUNC Modulus_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 43 | 44 | SEAL_C_FUNC Modulus_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 45 | 46 | SEAL_C_FUNC Modulus_Load(void *thisptr, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 47 | 48 | SEAL_C_FUNC Modulus_Reduce(void *thisptr, uint64_t value, uint64_t *result); 49 | 50 | SEAL_C_FUNC CoeffModulus_MaxBitCount(uint64_t poly_modulus_degree, int sec_level, int *bit_count); 51 | 52 | SEAL_C_FUNC CoeffModulus_BFVDefault(uint64_t poly_modulus_degree, int sec_level, uint64_t *length, void **coeffs); 53 | 54 | SEAL_C_FUNC CoeffModulus_Create1(uint64_t poly_modulus_degree, uint64_t length, int *bit_sizes, void **coeffs); 55 | 56 | SEAL_C_FUNC CoeffModulus_Create2( 57 | uint64_t poly_modulus_degree, uint64_t length, int *bit_sizes, void *plain_modulus, void **coeffs); 58 | -------------------------------------------------------------------------------- /native/src/seal/c/plaintext.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Plaintext_Create1(void *memoryPoolHandle, void **plaintext); 17 | 18 | SEAL_C_FUNC Plaintext_Create2(uint64_t coeffCount, void *memoryPoolHandle, void **plaintext); 19 | 20 | SEAL_C_FUNC Plaintext_Create3(uint64_t capacity, uint64_t coeffCount, void *memoryPoolHandle, void **plaintext); 21 | 22 | SEAL_C_FUNC Plaintext_Create4(char *hex_poly, void *memoryPoolHandle, void **plaintext); 23 | 24 | SEAL_C_FUNC Plaintext_Create5(void *copy, void **plaintext); 25 | 26 | SEAL_C_FUNC Plaintext_Set1(void *thisptr, void *assign); 27 | 28 | SEAL_C_FUNC Plaintext_Set2(void *thisptr, char *hex_poly); 29 | 30 | SEAL_C_FUNC Plaintext_Set3(void *thisptr, uint64_t const_coeff); 31 | 32 | SEAL_C_FUNC Plaintext_Set4(void *thisptr, uint64_t count, uint64_t *coeffs); 33 | 34 | SEAL_C_FUNC Plaintext_Destroy(void *thisptr); 35 | 36 | SEAL_C_FUNC Plaintext_CoeffCount(void *thisptr, uint64_t *coeff_count); 37 | 38 | SEAL_C_FUNC Plaintext_CoeffAt(void *thisptr, uint64_t index, uint64_t *coeff); 39 | 40 | SEAL_C_FUNC Plaintext_SetCoeffAt(void *thisptr, uint64_t index, uint64_t value); 41 | 42 | SEAL_C_FUNC Plaintext_ToString(void *thispt, char *outstr, uint64_t *length); 43 | 44 | SEAL_C_FUNC Plaintext_IsNTTForm(void *thisptr, bool *is_ntt_form); 45 | 46 | SEAL_C_FUNC Plaintext_IsZero(void *thisptr, bool *is_zero); 47 | 48 | SEAL_C_FUNC Plaintext_SetZero1(void *thisptr); 49 | 50 | SEAL_C_FUNC Plaintext_SetZero2(void *thisptr, uint64_t start_coeff); 51 | 52 | SEAL_C_FUNC Plaintext_SetZero3(void *thisptr, uint64_t start_coeff, uint64_t length); 53 | 54 | SEAL_C_FUNC Plaintext_GetParmsId(void *thisptr, uint64_t *parms_id); 55 | 56 | SEAL_C_FUNC Plaintext_SetParmsId(void *thisptr, uint64_t *parms_id); 57 | 58 | SEAL_C_FUNC Plaintext_Reserve(void *thisptr, uint64_t capacity); 59 | 60 | SEAL_C_FUNC Plaintext_Resize(void *thisptr, uint64_t coeff_count); 61 | 62 | SEAL_C_FUNC Plaintext_ShrinkToFit(void *thisptr); 63 | 64 | SEAL_C_FUNC Plaintext_Release(void *thisptr); 65 | 66 | SEAL_C_FUNC Plaintext_Capacity(void *thisptr, uint64_t *capacity); 67 | 68 | SEAL_C_FUNC Plaintext_SignificantCoeffCount(void *thisptr, uint64_t *significant_coeff_count); 69 | 70 | SEAL_C_FUNC Plaintext_NonZeroCoeffCount(void *thisptr, uint64_t *nonzero_coeff_count); 71 | 72 | SEAL_C_FUNC Plaintext_Scale(void *thisptr, double *scale); 73 | 74 | SEAL_C_FUNC Plaintext_SetScale(void *thisptr, double scale); 75 | 76 | SEAL_C_FUNC Plaintext_Equals(void *thisptr, void *other, bool *result); 77 | 78 | SEAL_C_FUNC Plaintext_SwapData(void *thisptr, uint64_t count, uint64_t *new_data); 79 | 80 | SEAL_C_FUNC Plaintext_Pool(void *thisptr, void **pool); 81 | 82 | SEAL_C_FUNC Plaintext_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 83 | 84 | SEAL_C_FUNC Plaintext_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 85 | 86 | SEAL_C_FUNC Plaintext_UnsafeLoad(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 87 | 88 | SEAL_C_FUNC Plaintext_Load(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 89 | -------------------------------------------------------------------------------- /native/src/seal/c/publickey.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC PublicKey_Create1(void **public_key); 17 | 18 | SEAL_C_FUNC PublicKey_Create2(void *copy, void **public_key); 19 | 20 | SEAL_C_FUNC PublicKey_Set(void *thisptr, void *assign); 21 | 22 | SEAL_C_FUNC PublicKey_Data(void *thisptr, void **data); 23 | 24 | SEAL_C_FUNC PublicKey_ParmsId(void *thisptr, uint64_t *parms_id); 25 | 26 | SEAL_C_FUNC PublicKey_Pool(void *thisptr, void **pool); 27 | 28 | SEAL_C_FUNC PublicKey_Destroy(void *thisptr); 29 | 30 | SEAL_C_FUNC PublicKey_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 31 | 32 | SEAL_C_FUNC PublicKey_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 33 | 34 | SEAL_C_FUNC PublicKey_UnsafeLoad(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 35 | 36 | SEAL_C_FUNC PublicKey_Load(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 37 | -------------------------------------------------------------------------------- /native/src/seal/c/relinkeys.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/relinkeys.h" 6 | #include "seal/c/utilities.h" 7 | 8 | // SEAL 9 | #include "seal/relinkeys.h" 10 | 11 | using namespace std; 12 | using namespace seal; 13 | using namespace seal::c; 14 | 15 | SEAL_C_FUNC RelinKeys_GetIndex(uint64_t key_power, uint64_t *index) 16 | { 17 | IfNullRet(index, E_POINTER); 18 | 19 | try 20 | { 21 | *index = RelinKeys::get_index(key_power); 22 | return S_OK; 23 | } 24 | catch (const invalid_argument &) 25 | { 26 | return E_INVALIDARG; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /native/src/seal/c/relinkeys.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC RelinKeys_GetIndex(uint64_t key_power, uint64_t *index); 17 | -------------------------------------------------------------------------------- /native/src/seal/c/sealcontext.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC SEALContext_Create(void *encryptionParams, bool expand_mod_chain, int sec_level, void **context); 17 | 18 | SEAL_C_FUNC SEALContext_Destroy(void *thisptr); 19 | 20 | SEAL_C_FUNC SEALContext_KeyParmsId(void *thisptr, uint64_t *parms_id); 21 | 22 | SEAL_C_FUNC SEALContext_FirstParmsId(void *thisptr, uint64_t *parms_id); 23 | 24 | SEAL_C_FUNC SEALContext_LastParmsId(void *thisptr, uint64_t *parms_id); 25 | 26 | SEAL_C_FUNC SEALContext_ParametersSet(void *thisptr, bool *params_set); 27 | 28 | SEAL_C_FUNC SEALContext_KeyContextData(void *thisptr, void **context_data); 29 | 30 | SEAL_C_FUNC SEALContext_FirstContextData(void *thisptr, void **context_data); 31 | 32 | SEAL_C_FUNC SEALContext_LastContextData(void *thisptr, void **context_data); 33 | 34 | SEAL_C_FUNC SEALContext_GetContextData(void *thisptr, uint64_t *parms_id, void **context_data); 35 | 36 | SEAL_C_FUNC SEALContext_UsingKeyswitching(void *thisptr, bool *using_keyswitching); 37 | 38 | SEAL_C_FUNC SEALContext_ParameterErrorName(void *thisptr, char *outstr, uint64_t *length); 39 | 40 | SEAL_C_FUNC SEALContext_ParameterErrorMessage(void *thisptr, char *outstr, uint64_t *length); 41 | -------------------------------------------------------------------------------- /native/src/seal/c/secretkey.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC SecretKey_Create1(void **secret_key); 17 | 18 | SEAL_C_FUNC SecretKey_Create2(void *copy, void **secret_key); 19 | 20 | SEAL_C_FUNC SecretKey_Set(void *thisptr, void *assign); 21 | 22 | SEAL_C_FUNC SecretKey_Data(void *thisptr, void **data); 23 | 24 | SEAL_C_FUNC SecretKey_Destroy(void *thisptr); 25 | 26 | SEAL_C_FUNC SecretKey_ParmsId(void *thisptr, uint64_t *parms_id); 27 | 28 | SEAL_C_FUNC SecretKey_Pool(void *thisptr, void **pool); 29 | 30 | SEAL_C_FUNC SecretKey_SaveSize(void *thisptr, uint8_t compr_mode, int64_t *result); 31 | 32 | SEAL_C_FUNC SecretKey_Save(void *thisptr, uint8_t *outptr, uint64_t size, uint8_t compr_mode, int64_t *out_bytes); 33 | 34 | SEAL_C_FUNC SecretKey_UnsafeLoad(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 35 | 36 | SEAL_C_FUNC SecretKey_Load(void *thisptr, void *context, uint8_t *inptr, uint64_t size, int64_t *in_bytes); 37 | -------------------------------------------------------------------------------- /native/src/seal/c/serialization.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/serialization.h" 6 | #include "seal/c/utilities.h" 7 | 8 | // SEAL 9 | #include "seal/serialization.h" 10 | 11 | using namespace std; 12 | using namespace seal; 13 | using namespace seal::c; 14 | 15 | SEAL_C_FUNC Serialization_SEALMagic(uint16_t *result) 16 | { 17 | IfNullRet(result, E_POINTER); 18 | 19 | *result = Serialization::seal_magic; 20 | return S_OK; 21 | } 22 | 23 | SEAL_C_FUNC Serialization_SEALHeaderSize(uint8_t *result) 24 | { 25 | IfNullRet(result, E_POINTER); 26 | 27 | *result = Serialization::seal_header_size; 28 | return S_OK; 29 | } 30 | 31 | SEAL_C_FUNC Serialization_IsSupportedComprMode(uint8_t compr_mode, bool *result) 32 | { 33 | IfNullRet(result, E_POINTER); 34 | 35 | *result = Serialization::IsSupportedComprMode(compr_mode); 36 | return S_OK; 37 | } 38 | 39 | SEAL_C_FUNC Serialization_ComprModeDefault(uint8_t *result) 40 | { 41 | IfNullRet(result, E_POINTER); 42 | 43 | *result = static_cast<uint8_t>(Serialization::compr_mode_default); 44 | return S_OK; 45 | } 46 | 47 | SEAL_C_FUNC Serialization_IsCompatibleVersion(uint8_t *headerptr, uint64_t size, bool *result) 48 | { 49 | IfNullRet(headerptr, E_POINTER); 50 | IfNullRet(result, E_POINTER); 51 | if (size != static_cast<uint64_t>(sizeof(Serialization::SEALHeader))) 52 | { 53 | *result = false; 54 | } 55 | 56 | Serialization::SEALHeader header; 57 | memcpy( 58 | reinterpret_cast<seal_byte *>(&header), reinterpret_cast<seal_byte *>(headerptr), 59 | sizeof(Serialization::SEALHeader)); 60 | *result = Serialization::IsCompatibleVersion(header); 61 | return S_OK; 62 | } 63 | 64 | SEAL_C_FUNC Serialization_IsValidHeader(uint8_t *headerptr, uint64_t size, bool *result) 65 | { 66 | IfNullRet(headerptr, E_POINTER); 67 | IfNullRet(result, E_POINTER); 68 | if (size != static_cast<uint64_t>(sizeof(Serialization::SEALHeader))) 69 | { 70 | *result = false; 71 | } 72 | 73 | Serialization::SEALHeader header; 74 | memcpy( 75 | reinterpret_cast<seal_byte *>(&header), reinterpret_cast<seal_byte *>(headerptr), 76 | sizeof(Serialization::SEALHeader)); 77 | *result = Serialization::IsValidHeader(header); 78 | return S_OK; 79 | } 80 | -------------------------------------------------------------------------------- /native/src/seal/c/serialization.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Serialization_SEALMagic(uint16_t *result); 17 | 18 | SEAL_C_FUNC Serialization_SEALHeaderSize(uint8_t *result); 19 | 20 | SEAL_C_FUNC Serialization_IsSupportedComprMode(uint8_t compr_mode, bool *result); 21 | 22 | SEAL_C_FUNC Serialization_ComprModeDefault(uint8_t *result); 23 | 24 | SEAL_C_FUNC Serialization_IsCompatibleVersion(uint8_t *headerptr, uint64_t size, bool *result); 25 | 26 | SEAL_C_FUNC Serialization_IsValidHeader(uint8_t *headerptr, uint64_t size, bool *result); 27 | -------------------------------------------------------------------------------- /native/src/seal/c/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/c/stdafx.h" 5 | -------------------------------------------------------------------------------- /native/src/seal/c/stdafx.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // stdafx.h : include file for standard system include files, 5 | // or project specific include files that are used frequently, but 6 | // are changed infrequently 7 | // 8 | 9 | #pragma once 10 | 11 | #ifdef _MSC_VER 12 | #include "seal/c/targetver.h" 13 | 14 | #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers 15 | // Windows Header Files 16 | #include <CorError.h> 17 | #include <Windows.h> 18 | #endif // _MSC_VER 19 | 20 | #define IfNullRet(expr, ret) \ 21 | { \ 22 | if ((expr) == nullptr) \ 23 | { \ 24 | return ret; \ 25 | } \ 26 | } 27 | 28 | #define IfFailRet(expr) \ 29 | { \ 30 | HRESULT __hr__ = (expr); \ 31 | if (FAILED(__hr__)) \ 32 | { \ 33 | return __hr__; \ 34 | } \ 35 | } 36 | -------------------------------------------------------------------------------- /native/src/seal/c/targetver.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | // Including SDKDDKVer.h defines the highest available Windows platform. 7 | 8 | // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and 9 | // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. 10 | 11 | #include <SDKDDKVer.h> 12 | -------------------------------------------------------------------------------- /native/src/seal/c/utilities.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // STD 5 | #include <algorithm> 6 | #include <iterator> 7 | 8 | // SEALNet 9 | #include "seal/c/utilities.h" 10 | 11 | // SEAL 12 | #include "seal/context.h" 13 | #include "seal/encryptionparams.h" 14 | #include "seal/modulus.h" 15 | #include "seal/util/common.h" 16 | #include "seal/util/locks.h" 17 | 18 | using namespace std; 19 | using namespace seal; 20 | using namespace seal::c; 21 | using namespace seal::util; 22 | 23 | unique_ptr<MemoryPoolHandle> seal::c::MemHandleFromVoid(void *voidptr) 24 | { 25 | if (nullptr == voidptr) 26 | { 27 | return make_unique<MemoryPoolHandle>(MemoryManager::GetPool()); 28 | } 29 | 30 | MemoryPoolHandle *handle = reinterpret_cast<MemoryPoolHandle *>(voidptr); 31 | return make_unique<MemoryPoolHandle>(*handle); 32 | } 33 | 34 | void seal::c::BuildModulusPointers(const vector<Modulus> &in_mods, uint64_t *length, void **out_mods) 35 | { 36 | *length = static_cast<uint64_t>(in_mods.size()); 37 | if (out_mods == nullptr) 38 | { 39 | // The caller is only interested in the size 40 | return; 41 | } 42 | 43 | Modulus **mod_ptr_array = reinterpret_cast<Modulus **>(out_mods); 44 | transform(in_mods.begin(), in_mods.end(), mod_ptr_array, [](const auto &mod) { return new Modulus(mod); }); 45 | } 46 | 47 | HRESULT seal::c::ToStringHelper(const string &str, char *outstr, uint64_t *length) 48 | { 49 | *length = static_cast<uint64_t>(str.size()); 50 | 51 | if (nullptr != outstr) 52 | { 53 | memcpy(outstr, str.c_str(), util::add_safe(*length, uint64_t(1))); 54 | } 55 | return S_OK; 56 | } 57 | 58 | HRESULT seal::c::ToStringHelper2(const char *str, char *outstr, uint64_t *length) 59 | { 60 | *length = static_cast<uint64_t>(strlen(str)); 61 | 62 | if (nullptr != outstr) 63 | { 64 | memcpy(outstr, str, util::add_safe(*length, uint64_t(1))); 65 | } 66 | return S_OK; 67 | } 68 | -------------------------------------------------------------------------------- /native/src/seal/c/utilities.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | // STD 7 | #include <algorithm> 8 | #include <memory> 9 | #include <string> 10 | #include <unordered_map> 11 | #include <vector> 12 | 13 | // SEALNet 14 | #include "seal/c/defines.h" 15 | 16 | // SEAL 17 | #include "seal/encryptionparams.h" 18 | 19 | namespace seal 20 | { 21 | class Modulus; 22 | class SEALContext; 23 | class MemoryPoolHandle; 24 | } // namespace seal 25 | 26 | namespace seal 27 | { 28 | namespace c 29 | { 30 | /** 31 | Return a pointer of the given type from a void pointer. 32 | */ 33 | template <class T> 34 | inline T *FromVoid(void *voidptr) 35 | { 36 | T *result = reinterpret_cast<T *>(voidptr); 37 | return result; 38 | } 39 | 40 | /** 41 | Get MemoryPoolHandle from a void pointer. 42 | Returns a default if void pointer is null. 43 | */ 44 | std::unique_ptr<seal::MemoryPoolHandle> MemHandleFromVoid(void *voidptr); 45 | 46 | /** 47 | Build and array of Modulus pointers from a vector 48 | */ 49 | void BuildModulusPointers(const std::vector<seal::Modulus> &in_mods, uint64_t *length, void **out_mods); 50 | 51 | /** 52 | Get a parms_id_type from an uint64_t pointer 53 | */ 54 | inline void CopyParmsId(const uint64_t *src, seal::parms_id_type &dest) 55 | { 56 | if (nullptr != src) 57 | { 58 | std::copy_n(src, dest.size(), std::begin(dest)); 59 | } 60 | } 61 | 62 | /** 63 | Copy parms_id_type to a uint64_t pointer 64 | */ 65 | inline void CopyParmsId(const seal::parms_id_type &src, uint64_t *dest) 66 | { 67 | if (nullptr != dest) 68 | { 69 | std::copy_n(std::cbegin(src), src.size(), dest); 70 | } 71 | } 72 | 73 | /** 74 | Convert std::string to char* with null terminator 75 | */ 76 | HRESULT ToStringHelper(const std::string &str, char *outstr, uint64_t *length); 77 | 78 | /** 79 | Convert const char * to char* with null terminator 80 | */ 81 | HRESULT ToStringHelper2(const char *str, char *outstr, uint64_t *length); 82 | } // namespace c 83 | } // namespace seal 84 | -------------------------------------------------------------------------------- /native/src/seal/c/valcheck.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/utilities.h" 6 | #include "seal/c/valcheck.h" 7 | 8 | // SEAL 9 | #include "seal/valcheck.h" 10 | 11 | using namespace std; 12 | using namespace seal; 13 | using namespace seal::c; 14 | 15 | SEAL_C_FUNC ValCheck_Plaintext_IsValidFor(void *plaintext, void *context, bool *result) 16 | { 17 | const SEALContext *ctx = FromVoid<SEALContext>(context); 18 | IfNullRet(ctx, E_POINTER); 19 | Plaintext *plain = FromVoid<Plaintext>(plaintext); 20 | IfNullRet(plain, E_POINTER); 21 | IfNullRet(result, E_POINTER); 22 | 23 | *result = is_valid_for(*plain, *ctx); 24 | return S_OK; 25 | } 26 | 27 | SEAL_C_FUNC ValCheck_Ciphertext_IsValidFor(void *ciphertext, void *context, bool *result) 28 | { 29 | const SEALContext *ctx = FromVoid<SEALContext>(context); 30 | IfNullRet(ctx, E_POINTER); 31 | Ciphertext *cipher = FromVoid<Ciphertext>(ciphertext); 32 | IfNullRet(cipher, E_POINTER); 33 | IfNullRet(result, E_POINTER); 34 | 35 | *result = is_valid_for(*cipher, *ctx); 36 | return S_OK; 37 | } 38 | 39 | SEAL_C_FUNC ValCheck_SecretKey_IsValidFor(void *secret_key, void *context, bool *result) 40 | { 41 | const SEALContext *ctx = FromVoid<SEALContext>(context); 42 | IfNullRet(ctx, E_POINTER); 43 | SecretKey *skey = FromVoid<SecretKey>(secret_key); 44 | IfNullRet(skey, E_POINTER); 45 | IfNullRet(result, E_POINTER); 46 | 47 | *result = is_valid_for(*skey, *ctx); 48 | return S_OK; 49 | } 50 | 51 | SEAL_C_FUNC ValCheck_PublicKey_IsValidFor(void *public_key, void *context, bool *result) 52 | { 53 | const SEALContext *ctx = FromVoid<SEALContext>(context); 54 | IfNullRet(ctx, E_POINTER); 55 | PublicKey *pkey = FromVoid<PublicKey>(public_key); 56 | IfNullRet(pkey, E_POINTER); 57 | IfNullRet(result, E_POINTER); 58 | 59 | *result = is_valid_for(*pkey, *ctx); 60 | return S_OK; 61 | } 62 | 63 | SEAL_C_FUNC ValCheck_KSwitchKeys_IsValidFor(void *kswitch_keys, void *context, bool *result) 64 | { 65 | const SEALContext *ctx = FromVoid<SEALContext>(context); 66 | IfNullRet(ctx, E_POINTER); 67 | KSwitchKeys *keys = FromVoid<KSwitchKeys>(kswitch_keys); 68 | IfNullRet(keys, E_POINTER); 69 | IfNullRet(result, E_POINTER); 70 | 71 | *result = is_valid_for(*keys, *ctx); 72 | return S_OK; 73 | } 74 | 75 | SEAL_C_FUNC ValCheck_RelinKeys_IsValidFor(void *relin_keys, void *context, bool *result) 76 | { 77 | const SEALContext *ctx = FromVoid<SEALContext>(context); 78 | IfNullRet(ctx, E_POINTER); 79 | RelinKeys *keys = FromVoid<RelinKeys>(relin_keys); 80 | IfNullRet(keys, E_POINTER); 81 | IfNullRet(result, E_POINTER); 82 | 83 | *result = is_valid_for(*keys, *ctx); 84 | return S_OK; 85 | } 86 | 87 | SEAL_C_FUNC ValCheck_GaloisKeys_IsValidFor(void *galois_keys, void *context, bool *result) 88 | { 89 | const SEALContext *ctx = FromVoid<SEALContext>(context); 90 | IfNullRet(ctx, E_POINTER); 91 | GaloisKeys *keys = FromVoid<GaloisKeys>(galois_keys); 92 | IfNullRet(keys, E_POINTER); 93 | IfNullRet(result, E_POINTER); 94 | 95 | *result = is_valid_for(*keys, *ctx); 96 | return S_OK; 97 | } 98 | -------------------------------------------------------------------------------- /native/src/seal/c/valcheck.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC ValCheck_Plaintext_IsValidFor(void *plaintext, void *context, bool *result); 17 | 18 | SEAL_C_FUNC ValCheck_Ciphertext_IsValidFor(void *ciphertext, void *context, bool *result); 19 | 20 | SEAL_C_FUNC ValCheck_SecretKey_IsValidFor(void *secret_key, void *context, bool *result); 21 | 22 | SEAL_C_FUNC ValCheck_PublicKey_IsValidFor(void *public_key, void *context, bool *result); 23 | 24 | SEAL_C_FUNC ValCheck_KSwitchKeys_IsValidFor(void *kswitch_keys, void *context, bool *result); 25 | 26 | SEAL_C_FUNC ValCheck_RelinKeys_IsValidFor(void *relin_keys, void *context, bool *result); 27 | 28 | SEAL_C_FUNC ValCheck_GaloisKeys_IsValidFor(void *galois_keys, void *context, bool *result); 29 | -------------------------------------------------------------------------------- /native/src/seal/c/version.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | // SEALNet 5 | #include "seal/c/utilities.h" 6 | #include "seal/c/version.h" 7 | 8 | // SEAL 9 | #include "seal/util/config.h" 10 | 11 | using namespace std; 12 | using namespace seal::c; 13 | 14 | SEAL_C_FUNC Version_Major(uint8_t *result) 15 | { 16 | IfNullRet(result, E_POINTER); 17 | 18 | *result = (uint8_t)SEAL_VERSION_MAJOR; 19 | return S_OK; 20 | } 21 | 22 | SEAL_C_FUNC Version_Minor(uint8_t *result) 23 | { 24 | IfNullRet(result, E_POINTER); 25 | 26 | *result = (uint8_t)SEAL_VERSION_MINOR; 27 | return S_OK; 28 | } 29 | 30 | SEAL_C_FUNC Version_Patch(uint8_t *result) 31 | { 32 | IfNullRet(result, E_POINTER); 33 | 34 | *result = (uint8_t)SEAL_VERSION_PATCH; 35 | return S_OK; 36 | } 37 | -------------------------------------------------------------------------------- /native/src/seal/c/version.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | /////////////////////////////////////////////////////////////////////////// 7 | // 8 | // This API is provided as a simple interface for Microsoft SEAL library 9 | // that can be PInvoked by .Net code. 10 | // 11 | /////////////////////////////////////////////////////////////////////////// 12 | 13 | #include "seal/c/defines.h" 14 | #include <stdint.h> 15 | 16 | SEAL_C_FUNC Version_Major(uint8_t *result); 17 | 18 | SEAL_C_FUNC Version_Minor(uint8_t *result); 19 | 20 | SEAL_C_FUNC Version_Patch(uint8_t *result); 21 | -------------------------------------------------------------------------------- /native/src/seal/galoiskeys.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/ciphertext.h" 7 | #include "seal/kswitchkeys.h" 8 | #include "seal/memorymanager.h" 9 | #include "seal/util/defines.h" 10 | #include "seal/util/galois.h" 11 | #include <vector> 12 | 13 | namespace seal 14 | { 15 | /** 16 | Class to store Galois keys. 17 | 18 | @par Slot Rotations 19 | Galois keys are certain types of public keys that are needed to perform encrypted 20 | vector rotation operations on batched ciphertexts. Batched ciphertexts encrypt 21 | a 2-by-(N/2) matrix of modular integers in the BFV scheme, or an N/2-dimensional 22 | vector of complex numbers in the CKKS scheme, where N denotes the degree of the 23 | polynomial modulus. In the BFV scheme Galois keys can enable both cyclic rotations 24 | of the encrypted matrix rows, as well as row swaps (column rotations). In the CKKS 25 | scheme Galois keys can enable cyclic vector rotations, as well as a complex 26 | conjugation operation. 27 | 28 | 29 | @par Thread Safety 30 | In general, reading from GaloisKeys is thread-safe as long as no other thread is 31 | concurrently mutating it. This is due to the underlying data structure storing the 32 | Galois keys not being thread-safe. 33 | 34 | @see RelinKeys for the class that stores the relinearization keys. 35 | @see KeyGenerator for the class that generates the Galois keys. 36 | */ 37 | class GaloisKeys : public KSwitchKeys 38 | { 39 | public: 40 | /** 41 | Returns the index of a Galois key in the backing KSwitchKeys instance that 42 | corresponds to the given Galois element, assuming that it exists in the 43 | backing KSwitchKeys. 44 | 45 | @param[in] galois_elt The Galois element 46 | @throws std::invalid_argument if galois_elt is not valid 47 | */ 48 | SEAL_NODISCARD inline static std::size_t get_index(std::uint32_t galois_elt) 49 | { 50 | return util::GaloisTool::GetIndexFromElt(galois_elt); 51 | } 52 | 53 | /** 54 | Returns whether a Galois key corresponding to a given Galois element exists. 55 | 56 | @param[in] galois_elt The Galois element 57 | @throws std::invalid_argument if galois_elt is not valid 58 | */ 59 | SEAL_NODISCARD inline bool has_key(std::uint32_t galois_elt) const 60 | { 61 | std::size_t index = get_index(galois_elt); 62 | return data().size() > index && !data()[index].empty(); 63 | } 64 | 65 | /** 66 | Returns a const reference to a Galois key. The returned Galois key corresponds 67 | to the given Galois element. 68 | 69 | @param[in] galois_elt The Galois element 70 | @throws std::invalid_argument if the key corresponding to galois_elt does not exist 71 | */ 72 | SEAL_NODISCARD inline const auto &key(std::uint32_t galois_elt) const 73 | { 74 | return KSwitchKeys::data(get_index(galois_elt)); 75 | } 76 | }; 77 | } // namespace seal 78 | -------------------------------------------------------------------------------- /native/src/seal/memorymanager.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/memorymanager.h" 5 | 6 | using namespace std; 7 | 8 | namespace seal 9 | { 10 | #ifndef _M_CEE 11 | mutex MemoryManager::switch_mutex_; 12 | #else 13 | #pragma message("WARNING: MemoryManager compiled thread-unsafe and MMProfGuard disabled to support /clr") 14 | #endif 15 | } // namespace seal 16 | -------------------------------------------------------------------------------- /native/src/seal/randomtostd.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/randomgen.h" 7 | #include <cstdint> 8 | #include <limits> 9 | #include <memory> 10 | #include <stdexcept> 11 | 12 | namespace seal 13 | { 14 | /** 15 | A simple wrapper class to implement C++ UniformRandomBitGenerator type properties 16 | for a given polymorphic UniformRandomGenerator instance. The resulting object can 17 | be used as a randomness source in C++ standard random number distribution classes, 18 | such as std::uniform_int_distribution, std::normal_distribution, or any of the 19 | standard RandomNumberEngine classes. 20 | */ 21 | class RandomToStandardAdapter 22 | { 23 | public: 24 | using result_type = std::uint32_t; 25 | 26 | /** 27 | Creates a new RandomToStandardAdapter backed by a given UniformRandomGenerator. 28 | 29 | @param[in] generator A backing UniformRandomGenerator instance 30 | @throws std::invalid_argument if generator is null 31 | */ 32 | RandomToStandardAdapter(std::shared_ptr<UniformRandomGenerator> generator) : generator_(generator) 33 | { 34 | if (!generator_) 35 | { 36 | throw std::invalid_argument("generator cannot be null"); 37 | } 38 | } 39 | 40 | /** 41 | Returns a new random number from the backing UniformRandomGenerator. 42 | */ 43 | SEAL_NODISCARD inline result_type operator()() 44 | { 45 | return generator_->generate(); 46 | } 47 | 48 | /** 49 | Returns the backing UniformRandomGenerator. 50 | */ 51 | SEAL_NODISCARD inline auto generator() const noexcept 52 | { 53 | return generator_; 54 | } 55 | 56 | /** 57 | Returns the smallest possible output value. 58 | */ 59 | SEAL_NODISCARD inline static constexpr result_type min() noexcept 60 | { 61 | return std::numeric_limits<result_type>::min(); 62 | } 63 | 64 | /** 65 | Returns the largest possible output value. 66 | */ 67 | SEAL_NODISCARD static constexpr result_type max() noexcept 68 | { 69 | return std::numeric_limits<result_type>::max(); 70 | } 71 | 72 | private: 73 | std::shared_ptr<UniformRandomGenerator> generator_; 74 | }; 75 | } // namespace seal 76 | -------------------------------------------------------------------------------- /native/src/seal/seal.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/batchencoder.h" 7 | #include "seal/ciphertext.h" 8 | #include "seal/ckks.h" 9 | #include "seal/context.h" 10 | #include "seal/decryptor.h" 11 | #include "seal/dynarray.h" 12 | #include "seal/encryptionparams.h" 13 | #include "seal/encryptor.h" 14 | #include "seal/evaluator.h" 15 | #include "seal/galoiskeys.h" 16 | #include "seal/keygenerator.h" 17 | #include "seal/memorymanager.h" 18 | #include "seal/modulus.h" 19 | #include "seal/plaintext.h" 20 | #include "seal/publickey.h" 21 | #include "seal/randomgen.h" 22 | #include "seal/randomtostd.h" 23 | #include "seal/relinkeys.h" 24 | #include "seal/secretkey.h" 25 | #include "seal/serializable.h" 26 | #include "seal/serialization.h" 27 | #include "seal/valcheck.h" 28 | #include "seal/version.h" 29 | -------------------------------------------------------------------------------- /native/src/seal/util/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Source files in this directory 5 | set(SEAL_SOURCE_FILES ${SEAL_SOURCE_FILES} 6 | ${CMAKE_CURRENT_LIST_DIR}/blake2b.c 7 | ${CMAKE_CURRENT_LIST_DIR}/blake2xb.c 8 | ${CMAKE_CURRENT_LIST_DIR}/clipnormal.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/common.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/croots.cpp 11 | ${CMAKE_CURRENT_LIST_DIR}/fips202.c 12 | ${CMAKE_CURRENT_LIST_DIR}/globals.cpp 13 | ${CMAKE_CURRENT_LIST_DIR}/galois.cpp 14 | ${CMAKE_CURRENT_LIST_DIR}/hash.cpp 15 | ${CMAKE_CURRENT_LIST_DIR}/iterator.cpp 16 | ${CMAKE_CURRENT_LIST_DIR}/mempool.cpp 17 | ${CMAKE_CURRENT_LIST_DIR}/numth.cpp 18 | ${CMAKE_CURRENT_LIST_DIR}/polyarithsmallmod.cpp 19 | ${CMAKE_CURRENT_LIST_DIR}/rlwe.cpp 20 | ${CMAKE_CURRENT_LIST_DIR}/rns.cpp 21 | ${CMAKE_CURRENT_LIST_DIR}/scalingvariant.cpp 22 | ${CMAKE_CURRENT_LIST_DIR}/ntt.cpp 23 | ${CMAKE_CURRENT_LIST_DIR}/streambuf.cpp 24 | ${CMAKE_CURRENT_LIST_DIR}/uintarith.cpp 25 | ${CMAKE_CURRENT_LIST_DIR}/uintarithmod.cpp 26 | ${CMAKE_CURRENT_LIST_DIR}/uintarithsmallmod.cpp 27 | ${CMAKE_CURRENT_LIST_DIR}/uintcore.cpp 28 | ${CMAKE_CURRENT_LIST_DIR}/ztools.cpp 29 | ) 30 | 31 | # Add header files for installation 32 | install( 33 | FILES 34 | ${CMAKE_CURRENT_LIST_DIR}/blake2.h 35 | ${CMAKE_CURRENT_LIST_DIR}/blake2-impl.h 36 | ${CMAKE_CURRENT_LIST_DIR}/clang.h 37 | ${CMAKE_CURRENT_LIST_DIR}/clipnormal.h 38 | ${CMAKE_CURRENT_LIST_DIR}/common.h 39 | ${CMAKE_CURRENT_LIST_DIR}/croots.h 40 | ${CMAKE_CURRENT_LIST_DIR}/defines.h 41 | ${CMAKE_CURRENT_LIST_DIR}/dwthandler.h 42 | ${CMAKE_CURRENT_LIST_DIR}/fips202.h 43 | ${CMAKE_CURRENT_LIST_DIR}/galois.h 44 | ${CMAKE_CURRENT_LIST_DIR}/gcc.h 45 | ${CMAKE_CURRENT_LIST_DIR}/globals.h 46 | ${CMAKE_CURRENT_LIST_DIR}/hash.h 47 | ${CMAKE_CURRENT_LIST_DIR}/hestdparms.h 48 | ${CMAKE_CURRENT_LIST_DIR}/iterator.h 49 | ${CMAKE_CURRENT_LIST_DIR}/locks.h 50 | ${CMAKE_CURRENT_LIST_DIR}/mempool.h 51 | ${CMAKE_CURRENT_LIST_DIR}/msvc.h 52 | ${CMAKE_CURRENT_LIST_DIR}/numth.h 53 | ${CMAKE_CURRENT_LIST_DIR}/pointer.h 54 | ${CMAKE_CURRENT_LIST_DIR}/polyarithsmallmod.h 55 | ${CMAKE_CURRENT_LIST_DIR}/polycore.h 56 | ${CMAKE_CURRENT_LIST_DIR}/rlwe.h 57 | ${CMAKE_CURRENT_LIST_DIR}/rns.h 58 | ${CMAKE_CURRENT_LIST_DIR}/scalingvariant.h 59 | ${CMAKE_CURRENT_LIST_DIR}/ntt.h 60 | ${CMAKE_CURRENT_LIST_DIR}/streambuf.h 61 | ${CMAKE_CURRENT_LIST_DIR}/uintarith.h 62 | ${CMAKE_CURRENT_LIST_DIR}/uintarithmod.h 63 | ${CMAKE_CURRENT_LIST_DIR}/uintarithsmallmod.h 64 | ${CMAKE_CURRENT_LIST_DIR}/uintcore.h 65 | ${CMAKE_CURRENT_LIST_DIR}/ztools.h 66 | DESTINATION 67 | ${SEAL_INCLUDES_INSTALL_DIR}/seal/util 68 | ) 69 | 70 | set(SEAL_SOURCE_FILES ${SEAL_SOURCE_FILES} PARENT_SCOPE) 71 | -------------------------------------------------------------------------------- /native/src/seal/util/cgmanifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/component-detection-manifest.json", 3 | "Registrations": [ 4 | { 5 | "component": { 6 | "type": "git", 7 | "git": { 8 | "repositoryUrl": "https://github.com/BLAKE2/BLAKE2", 9 | "commitHash": "997fa5ba1e14b52c554fb03ce39e579e6f27b90c" 10 | } 11 | } 12 | }, 13 | { 14 | "component": { 15 | "type": "git", 16 | "git": { 17 | "repositoryUrl": "https://github.com/pq-crystals/kyber", 18 | "commitHash": "844057468e69527bd15b17fbe03f4b61f9a22065" 19 | } 20 | } 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /native/src/seal/util/clipnormal.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/util/clipnormal.h" 5 | #include <stdexcept> 6 | 7 | using namespace std; 8 | 9 | namespace seal 10 | { 11 | namespace util 12 | { 13 | ClippedNormalDistribution::ClippedNormalDistribution( 14 | result_type mean, result_type standard_deviation, result_type max_deviation) 15 | : normal_(mean, standard_deviation), max_deviation_(max_deviation) 16 | { 17 | // Verify arguments. 18 | if (standard_deviation < 0) 19 | { 20 | throw invalid_argument("standard_deviation"); 21 | } 22 | if (max_deviation < 0) 23 | { 24 | throw invalid_argument("max_deviation"); 25 | } 26 | } 27 | } // namespace util 28 | } // namespace seal 29 | -------------------------------------------------------------------------------- /native/src/seal/util/clipnormal.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/util/defines.h" 7 | #include <cmath> 8 | #include <random> 9 | 10 | namespace seal 11 | { 12 | namespace util 13 | { 14 | class ClippedNormalDistribution 15 | { 16 | public: 17 | using result_type = double; 18 | 19 | using param_type = ClippedNormalDistribution; 20 | 21 | ClippedNormalDistribution(result_type mean, result_type standard_deviation, result_type max_deviation); 22 | 23 | template <typename RNG> 24 | SEAL_NODISCARD inline result_type operator()(RNG &engine, const param_type &parm) noexcept 25 | { 26 | param(parm); 27 | return operator()(engine); 28 | } 29 | 30 | template <typename RNG> 31 | SEAL_NODISCARD inline result_type operator()(RNG &engine) noexcept 32 | { 33 | result_type mean = normal_.mean(); 34 | while (true) 35 | { 36 | result_type value = normal_(engine); 37 | result_type deviation = std::abs(value - mean); 38 | if (deviation <= max_deviation_) 39 | { 40 | return value; 41 | } 42 | } 43 | } 44 | 45 | SEAL_NODISCARD inline result_type mean() const noexcept 46 | { 47 | return normal_.mean(); 48 | } 49 | 50 | SEAL_NODISCARD inline result_type standard_deviation() const noexcept 51 | { 52 | return normal_.stddev(); 53 | } 54 | 55 | SEAL_NODISCARD inline result_type max_deviation() const noexcept 56 | { 57 | return max_deviation_; 58 | } 59 | 60 | SEAL_NODISCARD inline result_type min() const noexcept 61 | { 62 | return normal_.mean() - max_deviation_; 63 | } 64 | 65 | SEAL_NODISCARD inline result_type max() const noexcept 66 | { 67 | return normal_.mean() + max_deviation_; 68 | } 69 | 70 | SEAL_NODISCARD inline param_type param() const noexcept 71 | { 72 | return *this; 73 | } 74 | 75 | inline void param(const param_type &parm) noexcept 76 | { 77 | *this = parm; 78 | } 79 | 80 | inline void reset() noexcept 81 | { 82 | normal_.reset(); 83 | } 84 | 85 | private: 86 | std::normal_distribution<result_type> normal_; 87 | 88 | result_type max_deviation_; 89 | }; 90 | } // namespace util 91 | } // namespace seal 92 | -------------------------------------------------------------------------------- /native/src/seal/util/common.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #ifndef __STDC_WANT_LIB_EXT1__ 5 | #define __STDC_WANT_LIB_EXT1__ 1 6 | #endif 7 | 8 | #include "seal/util/common.h" 9 | #include <string.h> 10 | 11 | #if (SEAL_SYSTEM == SEAL_SYSTEM_WINDOWS) 12 | #include <Windows.h> 13 | #endif 14 | 15 | using namespace std; 16 | 17 | namespace seal 18 | { 19 | namespace util 20 | { 21 | void seal_memzero(void *data, size_t size) 22 | { 23 | #if (SEAL_SYSTEM == SEAL_SYSTEM_WINDOWS) 24 | SecureZeroMemory(data, size); 25 | #elif defined(SEAL_USE_MEMSET_S) 26 | if (size > 0U && memset_s(data, static_cast<rsize_t>(size), 0, static_cast<rsize_t>(size)) != 0) 27 | { 28 | throw runtime_error("error calling memset_s"); 29 | } 30 | #elif defined(SEAL_USE_EXPLICIT_BZERO) 31 | explicit_bzero(data, size); 32 | #elif defined(SEAL_USE_EXPLICIT_MEMSET) 33 | explicit_memset(data, 0, size); 34 | #else 35 | volatile seal_byte *data_ptr = reinterpret_cast<seal_byte *>(data); 36 | while (size--) 37 | { 38 | *data_ptr++ = seal_byte{}; 39 | } 40 | #endif 41 | } 42 | } // namespace util 43 | } // namespace seal 44 | -------------------------------------------------------------------------------- /native/src/seal/util/config.h.in: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #define SEAL_VERSION "@SEAL_VERSION@" 7 | #define SEAL_VERSION_MAJOR @SEAL_VERSION_MAJOR@ 8 | #define SEAL_VERSION_MINOR @SEAL_VERSION_MINOR@ 9 | #define SEAL_VERSION_PATCH @SEAL_VERSION_PATCH@ 10 | 11 | // Are we in debug mode? 12 | #cmakedefine SEAL_DEBUG 13 | 14 | // C++17 features 15 | #cmakedefine SEAL_USE_STD_BYTE 16 | #cmakedefine SEAL_USE_ALIGNED_ALLOC 17 | #cmakedefine SEAL_USE_SHARED_MUTEX 18 | #cmakedefine SEAL_USE_IF_CONSTEXPR 19 | #cmakedefine SEAL_USE_MAYBE_UNUSED 20 | #cmakedefine SEAL_USE_NODISCARD 21 | #cmakedefine SEAL_USE_STD_FOR_EACH_N 22 | 23 | // Security 24 | #cmakedefine SEAL_THROW_ON_TRANSPARENT_CIPHERTEXT 25 | #cmakedefine SEAL_USE_GAUSSIAN_NOISE 26 | #cmakedefine SEAL_DEFAULT_PRNG @SEAL_DEFAULT_PRNG@ 27 | #cmakedefine SEAL_AVOID_BRANCHING 28 | 29 | // Intrinsics 30 | #cmakedefine SEAL_USE_INTRIN 31 | #cmakedefine SEAL_USE__UMUL128 32 | #cmakedefine SEAL_USE__BITSCANREVERSE64 33 | #cmakedefine SEAL_USE___BUILTIN_CLZLL 34 | #cmakedefine SEAL_USE___INT128 35 | #cmakedefine SEAL_USE__ADDCARRY_U64 36 | #cmakedefine SEAL_USE__SUBBORROW_U64 37 | 38 | // Zero memory functions 39 | #cmakedefine SEAL_USE_EXPLICIT_BZERO 40 | #cmakedefine SEAL_USE_EXPLICIT_MEMSET 41 | #cmakedefine SEAL_USE_MEMSET_S 42 | 43 | // Third-party dependencies 44 | #cmakedefine SEAL_USE_MSGSL 45 | #cmakedefine SEAL_USE_ZLIB 46 | #cmakedefine SEAL_USE_ZSTD 47 | #cmakedefine SEAL_USE_INTEL_HEXL 48 | -------------------------------------------------------------------------------- /native/src/seal/util/croots.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/util/croots.h" 5 | #include <complex> 6 | 7 | using namespace std; 8 | 9 | namespace seal 10 | { 11 | namespace util 12 | { 13 | // Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to 14 | // ensure symbol is created. 15 | constexpr double ComplexRoots::PI_; 16 | 17 | ComplexRoots::ComplexRoots(size_t degree_of_roots, MemoryPoolHandle pool) 18 | : degree_of_roots_(degree_of_roots), pool_(std::move(pool)) 19 | { 20 | #ifdef SEAL_DEBUG 21 | int power = util::get_power_of_two(degree_of_roots_); 22 | if (power < 0) 23 | { 24 | throw invalid_argument("degree_of_roots must be a power of two"); 25 | } 26 | else if (power < 3) 27 | { 28 | throw invalid_argument("degree_of_roots must be at least 8"); 29 | } 30 | #endif 31 | roots_ = allocate<complex<double>>(degree_of_roots_ / 8 + 1, pool_); 32 | 33 | // Generate 1/8 of all roots. 34 | // Alternatively, choose from precomputed high-precision roots in files. 35 | for (size_t i = 0; i <= degree_of_roots_ / 8; i++) 36 | { 37 | roots_[i] = 38 | polar<double>(1.0, 2 * PI_ * static_cast<double>(i) / static_cast<double>(degree_of_roots_)); 39 | } 40 | } 41 | 42 | SEAL_NODISCARD complex<double> ComplexRoots::get_root(size_t index) const 43 | { 44 | index &= degree_of_roots_ - 1; 45 | auto mirror = [](complex<double> a) { 46 | return complex<double>{ a.imag(), a.real() }; 47 | }; 48 | 49 | // This express the 8-fold symmetry of all n-th roots. 50 | if (index <= degree_of_roots_ / 8) 51 | { 52 | return roots_[index]; 53 | } 54 | else if (index <= degree_of_roots_ / 4) 55 | { 56 | return mirror(roots_[degree_of_roots_ / 4 - index]); 57 | } 58 | else if (index <= degree_of_roots_ / 2) 59 | { 60 | return -conj(get_root(degree_of_roots_ / 2 - index)); 61 | } 62 | else if (index <= 3 * degree_of_roots_ / 4) 63 | { 64 | return -get_root(index - degree_of_roots_ / 2); 65 | } 66 | else 67 | { 68 | return conj(get_root(degree_of_roots_ - index)); 69 | } 70 | } 71 | } // namespace util 72 | } // namespace seal 73 | -------------------------------------------------------------------------------- /native/src/seal/util/croots.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/memorymanager.h" 7 | #include "seal/util/defines.h" 8 | #include "seal/util/uintcore.h" 9 | #include <complex> 10 | #include <cstddef> 11 | #include <stdexcept> 12 | 13 | namespace seal 14 | { 15 | namespace util 16 | { 17 | class ComplexRoots 18 | { 19 | public: 20 | ComplexRoots() = delete; 21 | 22 | ComplexRoots(std::size_t degree_of_roots, MemoryPoolHandle pool); 23 | 24 | SEAL_NODISCARD std::complex<double> get_root(std::size_t index) const; 25 | 26 | private: 27 | static constexpr double PI_ = 3.1415926535897932384626433832795028842; 28 | 29 | // Contains 0~(n/8-1)-th powers of the n-th primitive root. 30 | util::Pointer<std::complex<double>> roots_; 31 | 32 | std::size_t degree_of_roots_; 33 | 34 | MemoryPoolHandle pool_; 35 | }; 36 | } // namespace util 37 | } // namespace seal 38 | -------------------------------------------------------------------------------- /native/src/seal/util/fips202.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include <stddef.h> 7 | #include <stdint.h> 8 | 9 | #if defined(__cplusplus) 10 | extern "C" 11 | { 12 | #endif 13 | 14 | void shake256(uint8_t *out, size_t outlen, const uint8_t *in, size_t inlen); 15 | 16 | #if defined(__cplusplus) 17 | } 18 | #endif 19 | -------------------------------------------------------------------------------- /native/src/seal/util/globals.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/util/hestdparms.h" 7 | #include <cstddef> 8 | #include <map> 9 | #include <memory> 10 | #include <vector> 11 | 12 | namespace seal 13 | { 14 | class Modulus; 15 | 16 | namespace util 17 | { 18 | class MemoryPool; 19 | 20 | namespace global_variables 21 | { 22 | extern std::shared_ptr<MemoryPool> const global_memory_pool; 23 | 24 | /* 25 | For .NET Framework wrapper support (C++/CLI) we need to 26 | (1) compile the MemoryManager class as thread-unsafe because C++ 27 | mutexes cannot be brought through C++/CLI layer; 28 | (2) disable thread-safe memory pools. 29 | */ 30 | #ifndef _M_CEE 31 | extern thread_local std::shared_ptr<MemoryPool> const tls_memory_pool; 32 | #endif 33 | /** 34 | Default value for the standard deviation of the noise (error) distribution. 35 | */ 36 | constexpr double noise_standard_deviation = seal_he_std_parms_error_std_dev; 37 | 38 | constexpr double noise_distribution_width_multiplier = 6; 39 | 40 | constexpr double noise_max_deviation = noise_standard_deviation * noise_distribution_width_multiplier; 41 | 42 | /** 43 | This data structure is a key-value storage that maps degrees of the polynomial modulus 44 | to vectors of Modulus elements so that when used with the default value for the 45 | standard deviation of the noise distribution (noise_standard_deviation), the security 46 | level is at least 128 bits according to https://HomomorphicEncryption.org. This makes 47 | it easy for non-expert users to select secure parameters. 48 | */ 49 | const std::map<std::size_t, std::vector<Modulus>> &GetDefaultCoeffModulus128(); 50 | 51 | /** 52 | This data structure is a key-value storage that maps degrees of the polynomial modulus 53 | to vectors of Modulus elements so that when used with the default value for the 54 | standard deviation of the noise distribution (noise_standard_deviation), the security 55 | level is at least 192 bits according to https://HomomorphicEncryption.org. This makes 56 | it easy for non-expert users to select secure parameters. 57 | */ 58 | const std::map<std::size_t, std::vector<Modulus>> &GetDefaultCoeffModulus192(); 59 | 60 | /** 61 | This data structure is a key-value storage that maps degrees of the polynomial modulus 62 | to vectors of Modulus elements so that when used with the default value for the 63 | standard deviation of the noise distribution (noise_standard_deviation), the security 64 | level is at least 256 bits according to https://HomomorphicEncryption.org. This makes 65 | it easy for non-expert users to select secure parameters. 66 | */ 67 | const std::map<std::size_t, std::vector<Modulus>> &GetDefaultCoeffModulus256(); 68 | } // namespace global_variables 69 | } // namespace util 70 | } // namespace seal 71 | -------------------------------------------------------------------------------- /native/src/seal/util/hash.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/util/hash.h" 5 | 6 | using namespace std; 7 | 8 | namespace seal 9 | { 10 | namespace util 11 | { 12 | // Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to 13 | // ensure symbol is created. 14 | constexpr size_t HashFunction::hash_block_uint64_count; 15 | 16 | // Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to 17 | // ensure symbol is created. 18 | constexpr size_t HashFunction::hash_block_byte_count; 19 | 20 | // Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to 21 | // ensure symbol is created. 22 | constexpr HashFunction::hash_block_type HashFunction::hash_zero_block; 23 | } // namespace util 24 | } // namespace seal 25 | -------------------------------------------------------------------------------- /native/src/seal/util/hash.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/util/blake2.h" 7 | #include "seal/util/common.h" 8 | #include "seal/util/defines.h" 9 | #include <array> 10 | #include <cstddef> 11 | #include <cstdint> 12 | 13 | namespace seal 14 | { 15 | namespace util 16 | { 17 | class HashFunction 18 | { 19 | public: 20 | HashFunction() = delete; 21 | 22 | static constexpr std::size_t hash_block_uint64_count = 4; 23 | 24 | static constexpr std::size_t hash_block_byte_count = hash_block_uint64_count * bytes_per_uint64; 25 | 26 | using hash_block_type = std::array<std::uint64_t, hash_block_uint64_count>; 27 | 28 | static constexpr hash_block_type hash_zero_block{ { 0, 0, 0, 0 } }; 29 | 30 | inline static void hash(const std::uint64_t *input, std::size_t uint64_count, hash_block_type &destination) 31 | { 32 | if (blake2b(&destination, hash_block_byte_count, input, uint64_count * bytes_per_uint64, nullptr, 0) != 33 | 0) 34 | { 35 | throw std::runtime_error("blake2b failed"); 36 | } 37 | } 38 | }; 39 | } // namespace util 40 | } // namespace seal 41 | -------------------------------------------------------------------------------- /native/src/seal/util/iterator.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/ciphertext.h" 5 | #include "seal/util/iterator.h" 6 | 7 | namespace seal 8 | { 9 | namespace util 10 | { 11 | PolyIter::PolyIter(Ciphertext &ct) : self_type(ct.data(), ct.poly_modulus_degree(), ct.coeff_modulus_size()) 12 | {} 13 | 14 | ConstPolyIter::ConstPolyIter(const Ciphertext &ct) 15 | : self_type(ct.data(), ct.poly_modulus_degree(), ct.coeff_modulus_size()) 16 | {} 17 | 18 | ConstPolyIter::ConstPolyIter(Ciphertext &ct) 19 | : self_type(ct.data(), ct.poly_modulus_degree(), ct.coeff_modulus_size()) 20 | {} 21 | } // namespace util 22 | } // namespace seal 23 | -------------------------------------------------------------------------------- /native/src/seal/util/msvc.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #if SEAL_COMPILER == SEAL_COMPILER_MSVC 7 | 8 | // Require Visual Studio 2017 version 15.3 or newer 9 | #if (_MSC_VER < 1911) 10 | #error "Microsoft Visual Studio 2017 version 15.3 or newer required" 11 | #endif 12 | 13 | // Read in config.h 14 | #include "seal/util/config.h" 15 | 16 | // In Visual Studio redefine std::byte (seal_byte) 17 | #undef SEAL_USE_STD_BYTE 18 | 19 | // In Visual Studio for now we disable the use of std::shared_mutex 20 | #undef SEAL_USE_SHARED_MUTEX 21 | 22 | // Are we compiling with C++17 or newer 23 | #if (_MSVC_LANG >= 201703L) 24 | 25 | // Use `if constexpr' 26 | #define SEAL_USE_IF_CONSTEXPR 27 | 28 | // Use [[maybe_unused]] 29 | #define SEAL_USE_MAYBE_UNUSED 30 | 31 | // Use [[nodiscard]] 32 | #define SEAL_USE_NODISCARD 33 | 34 | #else 35 | 36 | #ifdef SEAL_USE_IF_CONSTEXPR 37 | #pragma message("Disabling `if constexpr` based on _MSVC_LANG value " SEAL_STRINGIZE( \ 38 | _MSVC_LANG) ": undefining SEAL_USE_IF_CONSTEXPR") 39 | #undef SEAL_USE_IF_CONSTEXPR 40 | #endif 41 | 42 | #ifdef SEAL_USE_MAYBE_UNUSED 43 | #pragma message("Disabling `[[maybe_unused]]` based on _MSVC_LANG value " SEAL_STRINGIZE( \ 44 | _MSVC_LANG) ": undefining SEAL_USE_MAYBE_UNUSED") 45 | #undef SEAL_USE_MAYBE_UNUSED 46 | #endif 47 | 48 | #ifdef SEAL_USE_NODISCARD 49 | #pragma message("Disabling `[[nodiscard]]` based on _MSVC_LANG value " SEAL_STRINGIZE( \ 50 | _MSVC_LANG) ": undefining SEAL_USE_NODISCARD") 51 | #undef SEAL_USE_NODISCARD 52 | #endif 53 | #endif 54 | 55 | #ifdef SEAL_USE_ALIGNED_ALLOC 56 | #define SEAL_MALLOC(size) static_cast<seal_byte *>(_aligned_malloc((size), 64)) 57 | #define SEAL_FREE(ptr) _aligned_free(ptr) 58 | #endif 59 | 60 | // X64 61 | #ifdef _M_X64 62 | 63 | #ifdef SEAL_USE_INTRIN 64 | #include <intrin.h> 65 | 66 | #ifdef SEAL_USE__UMUL128 67 | #pragma intrinsic(_umul128) 68 | #define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) _umul128(operand1, operand2, hw64); 69 | 70 | #define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) result128[0] = _umul128(operand1, operand2, result128 + 1); 71 | #endif 72 | 73 | #ifdef SEAL_USE__BITSCANREVERSE64 74 | #pragma intrinsic(_BitScanReverse64) 75 | #define SEAL_MSB_INDEX_UINT64(result, value) _BitScanReverse64(result, value) 76 | #endif 77 | 78 | #ifdef SEAL_USE__ADDCARRY_U64 79 | #pragma intrinsic(_addcarry_u64) 80 | #define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64(carry, operand1, operand2, result) 81 | #endif 82 | 83 | #ifdef SEAL_USE__SUBBORROW_U64 84 | #pragma intrinsic(_subborrow_u64) 85 | #define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(borrow, operand1, operand2, result) 86 | #endif 87 | 88 | #endif 89 | #else 90 | #undef SEAL_USE_INTRIN 91 | 92 | #endif //_M_X64 93 | 94 | // Force inline 95 | #define SEAL_FORCE_INLINE __forceinline 96 | 97 | #endif 98 | -------------------------------------------------------------------------------- /native/src/seal/util/scalingvariant.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/context.h" 7 | #include "seal/memorymanager.h" 8 | #include "seal/plaintext.h" 9 | #include "seal/util/iterator.h" 10 | #include <cstdint> 11 | 12 | namespace seal 13 | { 14 | namespace util 15 | { 16 | void add_plain_without_scaling_variant( 17 | const Plaintext &plain, const SEALContext::ContextData &context_data, RNSIter destination); 18 | 19 | void sub_plain_without_scaling_variant( 20 | const Plaintext &plain, const SEALContext::ContextData &context_data, RNSIter destination); 21 | 22 | void multiply_add_plain_with_scaling_variant( 23 | const Plaintext &plain, const SEALContext::ContextData &context_data, RNSIter destination); 24 | 25 | void multiply_sub_plain_with_scaling_variant( 26 | const Plaintext &plain, const SEALContext::ContextData &context_data, RNSIter destination); 27 | } // namespace util 28 | } // namespace seal 29 | -------------------------------------------------------------------------------- /native/src/seal/util/ztools.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/util/defines.h" 7 | 8 | #if defined(SEAL_USE_ZLIB) || defined(SEAL_USE_ZSTD) 9 | #include "seal/dynarray.h" 10 | #include "seal/memorymanager.h" 11 | #include <ios> 12 | #include <iostream> 13 | 14 | namespace seal 15 | { 16 | namespace util 17 | { 18 | namespace ztools 19 | { 20 | /** 21 | Compresses data in the given buffer, completes the given SEALHeader by writing in the size of the output and 22 | setting the compression mode to compr_mode_type::zlib and finally writes the SEALHeader followed by the 23 | compressed data in the given stream. 24 | 25 | @param[in] in The buffer to compress 26 | @param[in] in_size The size of the buffer to compress in bytes 27 | @param[out] header A pointer to a SEALHeader instance matching the output of the compression 28 | @param[out] out_stream The stream to write to 29 | @param[in] pool The MemoryPoolHandle pointing to a valid memory pool 30 | @throws std::invalid_argument if pool is uninitialized 31 | @throws std::logic_error if compression failed 32 | */ 33 | void zlib_write_header_deflate_buffer( 34 | DynArray<seal_byte> &in, void *header_ptr, std::ostream &out_stream, MemoryPoolHandle pool); 35 | 36 | int zlib_deflate_array_inplace(DynArray<seal_byte> &in, MemoryPoolHandle pool); 37 | 38 | int zlib_inflate_stream( 39 | std::istream &in_stream, std::streamoff in_size, std::ostream &out_stream, MemoryPoolHandle pool); 40 | 41 | /** 42 | Compresses data in the given buffer, completes the given SEALHeader by writing in the size of the output and 43 | setting the compression mode to compr_mode_type::zstd and finally writes the SEALHeader followed by the 44 | compressed data in the given stream. 45 | 46 | @param[in] in The buffer to compress 47 | @param[in] in_size The size of the buffer to compress in bytes 48 | @param[out] header A pointer to a SEALHeader instance matching the output of the compression 49 | @param[out] out_stream The stream to write to 50 | @param[in] pool The MemoryPoolHandle pointing to a valid memory pool 51 | @throws std::invalid_argument if pool is uninitialized 52 | @throws std::logic_error if compression failed 53 | */ 54 | void zstd_write_header_deflate_buffer( 55 | DynArray<seal_byte> &in, void *header_ptr, std::ostream &out_stream, MemoryPoolHandle pool); 56 | 57 | unsigned zstd_deflate_array_inplace(DynArray<seal_byte> &in, MemoryPoolHandle pool); 58 | 59 | unsigned zstd_inflate_stream( 60 | std::istream &in_stream, std::streamoff in_size, std::ostream &out_stream, MemoryPoolHandle pool); 61 | 62 | template <typename SizeT> 63 | SEAL_NODISCARD SizeT zlib_deflate_size_bound(SizeT in_size) 64 | { 65 | return util::add_safe<SizeT>(in_size, in_size >> 12, in_size >> 14, in_size >> 25, SizeT(17)); 66 | } 67 | 68 | template <typename SizeT> 69 | SEAL_NODISCARD SizeT zstd_deflate_size_bound(SizeT in_size) 70 | { 71 | return util::add_safe<SizeT>( 72 | in_size, in_size >> 8, 73 | (in_size < (SizeT(128) << 10)) ? (((SizeT(128) << 10) - in_size) >> 11) : SizeT(0)); 74 | } 75 | } // namespace ztools 76 | } // namespace util 77 | } // namespace seal 78 | 79 | #endif 80 | -------------------------------------------------------------------------------- /native/src/seal/version.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #pragma once 5 | 6 | #include "seal/util/defines.h" 7 | #include <cstdint> 8 | 9 | namespace seal 10 | { 11 | /** 12 | Holds Microsoft SEAL version information. A SEALVersion contains four values: 13 | 14 | 1. The major version number; 15 | 2. The minor version number; 16 | 3. The patch version number; 17 | 4. The tweak version number. 18 | 19 | Two versions of the library with the same major and minor versions are fully 20 | compatible with each other. They are guaranteed to have the same public API. 21 | Changes in the patch version number indicate totally internal changes, such 22 | as bug fixes that require no changes to the public API. The tweak version 23 | number is currently not used, and is expected to be 0. 24 | */ 25 | struct SEALVersion 26 | { 27 | /** 28 | Holds the major version number. 29 | */ 30 | std::uint8_t major = SEAL_VERSION_MAJOR; 31 | 32 | /** 33 | Holds the minor version number. 34 | */ 35 | std::uint8_t minor = SEAL_VERSION_MINOR; 36 | 37 | /** 38 | Holds the patch version number. 39 | */ 40 | std::uint8_t patch = SEAL_VERSION_PATCH; 41 | 42 | std::uint8_t tweak = 0; 43 | }; 44 | } // namespace seal 45 | -------------------------------------------------------------------------------- /native/tests/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | cmake_minimum_required(VERSION 3.13) 5 | 6 | project(SEALTest VERSION 4.1.2 LANGUAGES CXX C) 7 | 8 | # If not called from root CMakeLists.txt 9 | if(NOT DEFINED SEAL_BUILD_TESTS) 10 | set(SEAL_BUILD_TESTS ON) 11 | 12 | # Import Microsoft SEAL 13 | find_package(SEAL 4.1.2 EXACT REQUIRED) 14 | 15 | # Must define these variables and include macros 16 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${OUTLIB_PATH}) 17 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) 18 | set(SEAL_THIRDPARTY_DIR ${CMAKE_CURRENT_LIST_DIR}/../../thirdparty) 19 | set(THIRDPARTY_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/thirdparty) 20 | include(FetchContent) 21 | mark_as_advanced(FETCHCONTENT_BASE_DIR) 22 | mark_as_advanced(FETCHCONTENT_FULLY_DISCONNECTED) 23 | mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED) 24 | mark_as_advanced(FETCHCONTENT_QUIET) 25 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../cmake) 26 | include(SEALMacros) 27 | else() 28 | set(THIRDPARTY_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/../../thirdparty) 29 | endif() 30 | 31 | if(NOT DEFINED SEAL_BUILD_DEPS) 32 | # [option] SEAL_BUILD_DEPS (default: ON) 33 | # Download and build missing dependencies, throw error if disabled. 34 | set(SEAL_BUILD_DEPS_OPTION_STR "Automatically download and build unmet dependencies") 35 | option(SEAL_BUILD_DEPS ${SEAL_BUILD_DEPS_OPTION_STR} ON) 36 | endif() 37 | 38 | # if SEAL_BUILD_TESTS is ON, use GoogleTest 39 | if(SEAL_BUILD_TESTS) 40 | if(SEAL_BUILD_DEPS) 41 | seal_fetch_thirdparty_content(ExternalGTest) 42 | add_library(GTest::gtest ALIAS gtest) 43 | else() 44 | find_package(GTest 1 CONFIG) 45 | if(NOT GTest_FOUND) 46 | message(FATAL_ERROR "GoogleTest: not found") 47 | else() 48 | message(STATUS "GoogleTest: found") 49 | endif() 50 | endif() 51 | 52 | add_executable(sealtest "") 53 | 54 | add_subdirectory(seal) 55 | 56 | if(TARGET SEAL::seal) 57 | target_link_libraries(sealtest PRIVATE SEAL::seal GTest::gtest) 58 | elseif(TARGET SEAL::seal_shared) 59 | target_link_libraries(sealtest PRIVATE SEAL::seal_shared GTest::gtest) 60 | else() 61 | message(FATAL_ERROR "Cannot find target SEAL::seal or SEAL::seal_shared") 62 | endif() 63 | 64 | # In Debug mode, enable AddressSanitizer (and LeakSanitizer) on Unix-like platforms. 65 | if(SEAL_DEBUG AND UNIX) 66 | # On macOS, only AddressSanitizer is enabled. 67 | # On Linux, LeakSanitizer is enabled by default. 68 | target_compile_options(sealtest PUBLIC -fsanitize=address) 69 | target_link_options(sealtest PUBLIC -fsanitize=address) 70 | if(NOT APPLE) 71 | message(STATUS "Sanitizers enabled: address, leak") 72 | else() 73 | message(STATUS "Sanitizers enabled: address") 74 | endif() 75 | endif() 76 | endif() 77 | -------------------------------------------------------------------------------- /native/tests/seal/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | target_sources(sealtest 5 | PRIVATE 6 | ${CMAKE_CURRENT_LIST_DIR}/ciphertext.cpp 7 | ${CMAKE_CURRENT_LIST_DIR}/ckks.cpp 8 | ${CMAKE_CURRENT_LIST_DIR}/context.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/encryptionparams.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/encryptor.cpp 11 | ${CMAKE_CURRENT_LIST_DIR}/evaluator.cpp 12 | ${CMAKE_CURRENT_LIST_DIR}/galoiskeys.cpp 13 | ${CMAKE_CURRENT_LIST_DIR}/dynarray.cpp 14 | ${CMAKE_CURRENT_LIST_DIR}/keygenerator.cpp 15 | ${CMAKE_CURRENT_LIST_DIR}/memorymanager.cpp 16 | ${CMAKE_CURRENT_LIST_DIR}/modulus.cpp 17 | ${CMAKE_CURRENT_LIST_DIR}/plaintext.cpp 18 | ${CMAKE_CURRENT_LIST_DIR}/publickey.cpp 19 | ${CMAKE_CURRENT_LIST_DIR}/randomgen.cpp 20 | ${CMAKE_CURRENT_LIST_DIR}/randomtostd.cpp 21 | ${CMAKE_CURRENT_LIST_DIR}/relinkeys.cpp 22 | ${CMAKE_CURRENT_LIST_DIR}/secretkey.cpp 23 | ${CMAKE_CURRENT_LIST_DIR}/serialization.cpp 24 | ${CMAKE_CURRENT_LIST_DIR}/testrunner.cpp 25 | ) 26 | 27 | add_subdirectory(util) 28 | -------------------------------------------------------------------------------- /native/tests/seal/memorymanager.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/dynarray.h" 5 | #include "seal/memorymanager.h" 6 | #include "seal/util/pointer.h" 7 | #include "seal/util/uintcore.h" 8 | #include "gtest/gtest.h" 9 | 10 | using namespace seal; 11 | using namespace seal::util; 12 | using namespace std; 13 | 14 | namespace sealtest 15 | { 16 | TEST(MemoryPoolHandleTest, MemoryPoolHandleConstructAssign) 17 | { 18 | MemoryPoolHandle pool; 19 | ASSERT_FALSE(pool); 20 | pool = MemoryPoolHandle::Global(); 21 | ASSERT_TRUE(&static_cast<MemoryPool &>(pool) == global_variables::global_memory_pool.get()); 22 | pool = MemoryPoolHandle::New(); 23 | ASSERT_FALSE(&pool.operator seal::util::MemoryPool &() == global_variables::global_memory_pool.get()); 24 | MemoryPoolHandle pool2 = MemoryPoolHandle::New(); 25 | ASSERT_FALSE(pool == pool2); 26 | 27 | pool = pool2; 28 | ASSERT_TRUE(pool == pool2); 29 | pool = MemoryPoolHandle::Global(); 30 | ASSERT_FALSE(pool == pool2); 31 | pool2 = MemoryPoolHandle::Global(); 32 | ASSERT_TRUE(pool == pool2); 33 | } 34 | 35 | TEST(MemoryPoolHandleTest, MemoryPoolHandleAllocate) 36 | { 37 | MemoryPoolHandle pool = MemoryPoolHandle::New(); 38 | ASSERT_TRUE(0LL == pool.alloc_byte_count()); 39 | { 40 | auto ptr(allocate_uint(5, pool)); 41 | ASSERT_TRUE(5LL * bytes_per_uint64 == pool.alloc_byte_count()); 42 | } 43 | 44 | pool = MemoryPoolHandle::New(); 45 | ASSERT_TRUE(0LL * bytes_per_uint64 == pool.alloc_byte_count()); 46 | { 47 | auto ptr(allocate_uint(5, pool)); 48 | ASSERT_TRUE(5LL * bytes_per_uint64 == pool.alloc_byte_count()); 49 | 50 | ptr = allocate_uint(8, pool); 51 | ASSERT_TRUE(13LL * bytes_per_uint64 == pool.alloc_byte_count()); 52 | 53 | auto ptr2(allocate_uint(2, pool)); 54 | ASSERT_TRUE(15LL * bytes_per_uint64 == pool.alloc_byte_count()); 55 | } 56 | } 57 | 58 | TEST(MemoryPoolHandleTest, UseCount) 59 | { 60 | MemoryPoolHandle pool = MemoryPoolHandle::New(); 61 | ASSERT_EQ(1L, pool.use_count()); 62 | { 63 | DynArray<int> arr(pool); 64 | ASSERT_EQ(2L, pool.use_count()); 65 | DynArray<int> arr2(pool); 66 | ASSERT_EQ(3L, pool.use_count()); 67 | } 68 | ASSERT_EQ(1L, pool.use_count()); 69 | } 70 | } // namespace sealtest 71 | -------------------------------------------------------------------------------- /native/tests/seal/publickey.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/context.h" 5 | #include "seal/keygenerator.h" 6 | #include "seal/modulus.h" 7 | #include "seal/publickey.h" 8 | #include "gtest/gtest.h" 9 | 10 | using namespace seal; 11 | using namespace std; 12 | 13 | namespace sealtest 14 | { 15 | TEST(PublicKeyTest, SaveLoadPublicKey) 16 | { 17 | auto save_load_public_key = [](scheme_type scheme) { 18 | stringstream stream; 19 | { 20 | EncryptionParameters parms(scheme); 21 | parms.set_poly_modulus_degree(64); 22 | parms.set_plain_modulus(1 << 6); 23 | parms.set_coeff_modulus(CoeffModulus::Create(64, { 60 })); 24 | 25 | SEALContext context(parms, false, sec_level_type::none); 26 | KeyGenerator keygen(context); 27 | 28 | PublicKey pk; 29 | keygen.create_public_key(pk); 30 | ASSERT_TRUE(pk.parms_id() == context.key_parms_id()); 31 | pk.save(stream); 32 | 33 | PublicKey pk2; 34 | pk2.load(context, stream); 35 | 36 | ASSERT_EQ(pk.data().dyn_array().size(), pk2.data().dyn_array().size()); 37 | for (size_t i = 0; i < pk.data().dyn_array().size(); i++) 38 | { 39 | ASSERT_EQ(pk.data().data()[i], pk2.data().data()[i]); 40 | } 41 | ASSERT_TRUE(pk.parms_id() == pk2.parms_id()); 42 | } 43 | { 44 | EncryptionParameters parms(scheme); 45 | parms.set_poly_modulus_degree(256); 46 | parms.set_plain_modulus(1 << 20); 47 | parms.set_coeff_modulus(CoeffModulus::Create(256, { 30, 40 })); 48 | 49 | SEALContext context(parms, false, sec_level_type::none); 50 | KeyGenerator keygen(context); 51 | 52 | PublicKey pk; 53 | keygen.create_public_key(pk); 54 | ASSERT_TRUE(pk.parms_id() == context.key_parms_id()); 55 | pk.save(stream); 56 | 57 | PublicKey pk2; 58 | pk2.load(context, stream); 59 | 60 | ASSERT_EQ(pk.data().dyn_array().size(), pk2.data().dyn_array().size()); 61 | for (size_t i = 0; i < pk.data().dyn_array().size(); i++) 62 | { 63 | ASSERT_EQ(pk.data().data()[i], pk2.data().data()[i]); 64 | } 65 | ASSERT_TRUE(pk.parms_id() == pk2.parms_id()); 66 | } 67 | }; 68 | 69 | save_load_public_key(scheme_type::bfv); 70 | save_load_public_key(scheme_type::bgv); 71 | } 72 | } // namespace sealtest 73 | -------------------------------------------------------------------------------- /native/tests/seal/randomtostd.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/randomgen.h" 5 | #include "seal/randomtostd.h" 6 | #include <cstdint> 7 | #include <memory> 8 | #include "gtest/gtest.h" 9 | 10 | using namespace seal; 11 | using namespace std; 12 | 13 | namespace sealtest 14 | { 15 | TEST(RandomToStandard, RandomToStandardGenerate) 16 | { 17 | shared_ptr<UniformRandomGenerator> generator(UniformRandomGeneratorFactory::DefaultFactory()->create()); 18 | RandomToStandardAdapter rand(generator); 19 | ASSERT_TRUE(rand.generator() == generator); 20 | ASSERT_EQ(static_cast<uint32_t>(0), rand.min()); 21 | ASSERT_EQ(static_cast<uint32_t>(UINT32_MAX), rand.max()); 22 | bool lower_half = false; 23 | bool upper_half = false; 24 | bool even = false; 25 | bool odd = false; 26 | for (int i = 0; i < 50; i++) 27 | { 28 | uint32_t value = rand(); 29 | if (value < UINT32_MAX / 2) 30 | { 31 | lower_half = true; 32 | } 33 | else 34 | { 35 | upper_half = true; 36 | } 37 | if ((value % 2) == 0) 38 | { 39 | even = true; 40 | } 41 | else 42 | { 43 | odd = true; 44 | } 45 | } 46 | ASSERT_TRUE(lower_half); 47 | ASSERT_TRUE(upper_half); 48 | ASSERT_TRUE(even); 49 | ASSERT_TRUE(odd); 50 | } 51 | } // namespace sealtest 52 | -------------------------------------------------------------------------------- /native/tests/seal/secretkey.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/context.h" 5 | #include "seal/keygenerator.h" 6 | #include "seal/modulus.h" 7 | #include "seal/secretkey.h" 8 | #include "gtest/gtest.h" 9 | 10 | using namespace seal; 11 | using namespace std; 12 | 13 | namespace sealtest 14 | { 15 | TEST(SecretKeyTest, SaveLoadSecretKey) 16 | { 17 | auto save_load_secret_key = [](scheme_type scheme) { 18 | stringstream stream; 19 | { 20 | EncryptionParameters parms(scheme); 21 | parms.set_poly_modulus_degree(64); 22 | parms.set_plain_modulus(1 << 6); 23 | parms.set_coeff_modulus(CoeffModulus::Create(64, { 60 })); 24 | 25 | SEALContext context(parms, false, sec_level_type::none); 26 | KeyGenerator keygen(context); 27 | 28 | SecretKey sk = keygen.secret_key(); 29 | ASSERT_TRUE(sk.parms_id() == context.key_parms_id()); 30 | sk.save(stream); 31 | 32 | SecretKey sk2; 33 | sk2.load(context, stream); 34 | 35 | ASSERT_TRUE(sk.data() == sk2.data()); 36 | ASSERT_TRUE(sk.parms_id() == sk2.parms_id()); 37 | } 38 | { 39 | EncryptionParameters parms(scheme); 40 | parms.set_poly_modulus_degree(256); 41 | parms.set_plain_modulus(1 << 20); 42 | parms.set_coeff_modulus(CoeffModulus::Create(256, { 30, 40 })); 43 | 44 | SEALContext context(parms, false, sec_level_type::none); 45 | KeyGenerator keygen(context); 46 | 47 | SecretKey sk = keygen.secret_key(); 48 | ASSERT_TRUE(sk.parms_id() == context.key_parms_id()); 49 | sk.save(stream); 50 | 51 | SecretKey sk2; 52 | sk2.load(context, stream); 53 | 54 | ASSERT_TRUE(sk.data() == sk2.data()); 55 | ASSERT_TRUE(sk.parms_id() == sk2.parms_id()); 56 | } 57 | }; 58 | 59 | save_load_secret_key(scheme_type::bfv); 60 | save_load_secret_key(scheme_type::bgv); 61 | } 62 | } // namespace sealtest 63 | -------------------------------------------------------------------------------- /native/tests/seal/testrunner.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "gtest/gtest.h" 5 | 6 | /** 7 | Main entry point for Google Test unit tests. 8 | */ 9 | int main(int argc, char **argv) 10 | { 11 | testing::InitGoogleTest(&argc, argv); 12 | return RUN_ALL_TESTS(); 13 | } 14 | -------------------------------------------------------------------------------- /native/tests/seal/util/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | target_sources(sealtest 5 | PRIVATE 6 | ${CMAKE_CURRENT_LIST_DIR}/clipnormal.cpp 7 | ${CMAKE_CURRENT_LIST_DIR}/common.cpp 8 | ${CMAKE_CURRENT_LIST_DIR}/galois.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/hash.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/iterator.cpp 11 | ${CMAKE_CURRENT_LIST_DIR}/locks.cpp 12 | ${CMAKE_CURRENT_LIST_DIR}/mempool.cpp 13 | ${CMAKE_CURRENT_LIST_DIR}/numth.cpp 14 | ${CMAKE_CURRENT_LIST_DIR}/polyarithsmallmod.cpp 15 | ${CMAKE_CURRENT_LIST_DIR}/polycore.cpp 16 | ${CMAKE_CURRENT_LIST_DIR}/rns.cpp 17 | ${CMAKE_CURRENT_LIST_DIR}/ntt.cpp 18 | ${CMAKE_CURRENT_LIST_DIR}/stringtouint64.cpp 19 | ${CMAKE_CURRENT_LIST_DIR}/uint64tostring.cpp 20 | ${CMAKE_CURRENT_LIST_DIR}/uintarith.cpp 21 | ${CMAKE_CURRENT_LIST_DIR}/uintarithmod.cpp 22 | ${CMAKE_CURRENT_LIST_DIR}/uintarithsmallmod.cpp 23 | ${CMAKE_CURRENT_LIST_DIR}/uintcore.cpp 24 | ) 25 | -------------------------------------------------------------------------------- /native/tests/seal/util/clipnormal.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/randomgen.h" 5 | #include "seal/randomtostd.h" 6 | #include "seal/util/clipnormal.h" 7 | #include <cmath> 8 | #include <memory> 9 | #include "gtest/gtest.h" 10 | 11 | using namespace seal::util; 12 | using namespace seal; 13 | using namespace std; 14 | 15 | namespace sealtest 16 | { 17 | namespace util 18 | { 19 | TEST(ClipNormal, ClipNormalGenerate) 20 | { 21 | shared_ptr<UniformRandomGenerator> generator(UniformRandomGeneratorFactory::DefaultFactory()->create()); 22 | RandomToStandardAdapter rand(generator); 23 | ClippedNormalDistribution dist(50.0, 10.0, 20.0); 24 | 25 | ASSERT_EQ(50.0, dist.mean()); 26 | ASSERT_EQ(10.0, dist.standard_deviation()); 27 | ASSERT_EQ(20.0, dist.max_deviation()); 28 | ASSERT_EQ(30.0, dist.min()); 29 | ASSERT_EQ(70.0, dist.max()); 30 | double average = 0; 31 | double stddev = 0; 32 | for (int i = 0; i < 100; ++i) 33 | { 34 | double value = dist(rand); 35 | average += value; 36 | stddev += (value - 50.0) * (value - 50.0); 37 | ASSERT_TRUE(value >= 30.0 && value <= 70.0); 38 | } 39 | average /= 100; 40 | stddev /= 100; 41 | stddev = sqrt(stddev); 42 | ASSERT_TRUE(average >= 40.0 && average <= 60.0); 43 | ASSERT_TRUE(stddev >= 5.0 && stddev <= 15.0); 44 | } 45 | } // namespace util 46 | } // namespace sealtest 47 | -------------------------------------------------------------------------------- /native/tests/seal/util/hash.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | #include "seal/util/hash.h" 5 | #include <cstdint> 6 | #include "gtest/gtest.h" 7 | 8 | using namespace seal::util; 9 | using namespace std; 10 | 11 | namespace sealtest 12 | { 13 | namespace util 14 | { 15 | namespace 16 | { 17 | void hash(uint64_t value, HashFunction::hash_block_type &destination) 18 | { 19 | HashFunction::hash(&value, 1, destination); 20 | } 21 | } // namespace 22 | 23 | TEST(HashTest, Hash) 24 | { 25 | uint64_t input[3]{ 0, 0, 0 }; 26 | HashFunction::hash_block_type hash1, hash2; 27 | hash(0, hash1); 28 | 29 | HashFunction::hash(input, 0, hash2); 30 | ASSERT_TRUE(hash1 != hash2); 31 | 32 | HashFunction::hash(input, 1, hash2); 33 | ASSERT_TRUE(hash1 == hash2); 34 | 35 | HashFunction::hash(input, 2, hash2); 36 | ASSERT_TRUE(hash1 != hash2); 37 | 38 | hash(0x123456, hash1); 39 | hash(0x023456, hash2); 40 | ASSERT_TRUE(hash1 != hash2); 41 | 42 | input[0] = 0x123456; 43 | input[1] = 1; 44 | hash(0x123456, hash1); 45 | HashFunction::hash(input, 2, hash2); 46 | ASSERT_TRUE(hash1 != hash2); 47 | } 48 | } // namespace util 49 | } // namespace sealtest 50 | -------------------------------------------------------------------------------- /pipelines/android.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - task: JavaToolInstaller@0 3 | displayName: Use Java 11 4 | inputs: 5 | versionSpec: '11' 6 | jdkArchitectureOption: 'x64' 7 | jdkSourceOption: 'PreInstalled' 8 | 9 | - task: PowerShell@2 10 | displayName: Install CMake 3.18.6 11 | inputs: 12 | targetType: 'inline' 13 | script: | 14 | # Download specific version of CMake 15 | $ToolsDirectory = Join-Path -Path $Env:BUILD_SOURCESDIRECTORY -ChildPath tools 16 | $CMakeZipFile = Join-Path $ToolsDirectory -ChildPath cmake.zip 17 | 18 | Invoke-WebRequest -Uri "https://cmake.org/files/v3.18/cmake-3.18.6-win64-x64.zip" -OutFile $CMakeZipFile 19 | New-Item -Path $ToolsDirectory -Name "cmake" -ItemType "directory" 20 | Expand-Archive -Path $CMakeZipFile -DestinationPath $ToolsDirectory/cmake 21 | Copy-Item -Path $ToolsDirectory/cmake/cmake-3.18.6-win64-x64/* -Destination "c:/Program Files/CMake" -Recurse -Force 22 | 23 | - task: CMake@1 24 | displayName: Verify CMake version 25 | inputs: 26 | workingDirectory: '$(Build.SourcesDirectory)' 27 | cmakeArgs: '--version' 28 | 29 | - task: PowerShell@2 30 | displayName: Download Ninja 31 | inputs: 32 | targetType: 'inline' 33 | script: | 34 | # Download Ninja 35 | $ToolsDirectory = Join-Path -Path $Env:BUILD_SOURCESDIRECTORY -ChildPath tools 36 | $NinjaZipFile = Join-Path $ToolsDirectory -ChildPath ninja.zip 37 | $NinjaExeFile = Join-Path $ToolsDirectory -ChildPath ninja.exe 38 | 39 | Invoke-WebRequest -Uri "https://github.com/ninja-build/ninja/releases/download/v1.10.0/ninja-win.zip" -OutFile $NinjaZipFile 40 | Expand-Archive -Path $NinjaZipFile -DestinationPath $ToolsDirectory 41 | Copy-Item -Path $NinjaExeFile -Destination "c:/Program Files/CMake/bin" 42 | 43 | - task: Gradle@2 44 | displayName: Compile Android Native Libraries 45 | inputs: 46 | workingDirectory: '$(Build.SourcesDirectory)/android' 47 | gradleWrapperFile: '$(Build.SourcesDirectory)/android/gradlew' 48 | gradleOptions: '' 49 | options: '--stacktrace --no-parallel' 50 | publishJUnitResults: false 51 | testResultsFiles: '**/TEST-*.xml' 52 | tasks: 'compileReleaseSources' 53 | 54 | - task: PowerShell@2 55 | displayName: Copy binary files to staging directory 56 | inputs: 57 | targetType: 'inline' 58 | script: | 59 | # Directories 60 | $AndroidFilesDirectory = Join-Path -Path $Env:BUILD_SOURCESDIRECTORY -ChildPath android/app/.cxx 61 | $TargetDirectoryArm64 = Join-Path -Path $Env:BUILD_ARTIFACTSTAGINGDIRECTORY -ChildPath lib/arm64-v8a 62 | $TargetDirectoryX64 = Join-Path -Path $Env:BUILD_ARTIFACTSTAGINGDIRECTORY -ChildPath lib/x86_64 63 | 64 | # Create directory if necessary 65 | mkdir -ErrorAction Ignore $TargetDirectoryArm64 66 | mkdir -ErrorAction Ignore $TargetDirectoryX64 67 | 68 | Get-ChildItem -Path $AndroidFilesDirectory -Recurse | Where {$_.Fullname -match 'RelWithDebInfo\\.*\\arm64-v8a\\lib\\arm64-v8a\\libsealc.so'} | Copy-Item -Destination $TargetDirectoryArm64 69 | Get-ChildItem -Path $AndroidFilesDirectory -Recurse | Where {$_.Fullname -match 'RelWithDebInfo\\.*\\x86_64\\lib\\x86_64\\libsealc.so'} | Copy-Item -Destination $TargetDirectoryX64 70 | 71 | - task: PublishBuildArtifacts@1 72 | displayName: Publish build artifacts 73 | inputs: 74 | PathtoPublish: '$(Build.ArtifactStagingDirectory)' 75 | ArtifactName: ${{ parameters.artifactName }} 76 | -------------------------------------------------------------------------------- /pipelines/ios.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - task: CMake@1 3 | displayName: 'CMake SEAL' 4 | inputs: 5 | workingDirectory: '$(Build.SourcesDirectory)' 6 | cmakeArgs: '-GXcode -DSEAL_BUILD_SEAL_C=ON -DSEAL_BUILD_STATIC_SEAL_C=ON -DCMAKE_SYSTEM_NAME=iOS "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" -C cmake/functions.iOS.cmake .' 7 | 8 | - script: | 9 | cd $BUILD_SOURCESDIRECTORY 10 | xcodebuild -project SEAL.xcodeproj -sdk iphonesimulator -arch x86_64 -configuration ${{ parameters.configuration }} clean build 11 | mkdir -p $BUILD_SOURCESDIRECTORY/lib/x86_64 12 | cp $BUILD_SOURCESDIRECTORY/lib/${{ parameters.configuration }}/libseal*.a $BUILD_SOURCESDIRECTORY/lib/x86_64 13 | 14 | xcodebuild -project SEAL.xcodeproj -sdk iphoneos -arch arm64 -configuration ${{ parameters.configuration }} clean build 15 | mkdir -p $BUILD_SOURCESDIRECTORY/lib/arm64 16 | cp $BUILD_SOURCESDIRECTORY/lib/${{ parameters.configuration }}/libseal*.a $BUILD_SOURCESDIRECTORY/lib/arm64 17 | 18 | cd $BUILD_SOURCESDIRECTORY/lib 19 | echo Creating fat libraries 20 | lipo -create -output libseal.a x86_64/libseal-*.a arm64/libseal-*.a 21 | lipo -create -output libsealc.a x86_64/libsealc-*.a arm64/libsealc-*.a 22 | 23 | echo Architectures for libseal.a 24 | lipo -info libseal.a 25 | 26 | echo Architectures for libsealc.a 27 | lipo -info libsealc.a 28 | displayName: 'Build SEAL' 29 | 30 | - task: CopyFiles@2 31 | displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)' 32 | inputs: 33 | SourceFolder: '$(Build.SourcesDirectory)/lib' 34 | Contents: 'libseal*' 35 | TargetFolder: '$(Build.ArtifactStagingDirectory)/lib' 36 | 37 | - task: PublishBuildArtifacts@1 38 | displayName: 'Publish Artifact: drop' 39 | inputs: 40 | PathtoPublish: '$(Build.ArtifactStagingDirectory)' 41 | artifactName: ${{ parameters.artifactName }} 42 | -------------------------------------------------------------------------------- /pipelines/jobs.yml: -------------------------------------------------------------------------------- 1 | # This file selects the correct job definition based on system and buildType. 2 | 3 | parameters: 4 | debug: 'false' 5 | 6 | jobs: 7 | 8 | - ${{ if eq(parameters.name, 'Windows') }}: 9 | - job: ${{ parameters.name }} 10 | displayName: ${{ parameters.name }} 11 | ${{ if eq(parameters.debug, 'false') }}: 12 | timeoutInMinutes: 0 13 | pool: 14 | vmImage: 'windows-2022' 15 | steps: 16 | - template: windows.yml 17 | parameters: 18 | nuget_version: '6.1.0' 19 | ${{ if eq(parameters.debug, 'true') }}: 20 | configuration: 'Debug' 21 | ${{ if eq(parameters.debug, 'false') }}: 22 | configuration: 'Release' 23 | 24 | - ${{ if eq(parameters.name, 'Linux') }}: 25 | - job: ${{ parameters.name }} 26 | displayName: ${{ parameters.name }} 27 | pool: 28 | vmImage: 'ubuntu-latest' 29 | steps: 30 | - template: nix.yml 31 | parameters: 32 | artifactName: linux-drop 33 | ${{ if eq(parameters.debug, 'true') }}: 34 | configuration: 'Debug' 35 | ${{ if eq(parameters.debug, 'false') }}: 36 | configuration: 'Release' 37 | 38 | - ${{ if eq(parameters.name, 'macOS') }}: 39 | - job: ${{ parameters.name }} 40 | displayName: ${{ parameters.name }} 41 | pool: 42 | vmImage: 'macos-latest' 43 | steps: 44 | - template: nix.yml 45 | parameters: 46 | artifactName: macos-drop 47 | ${{ if eq(parameters.debug, 'true') }}: 48 | configuration: 'Debug' 49 | ${{ if eq(parameters.debug, 'false') }}: 50 | configuration: 'Release' 51 | 52 | - ${{ if eq(parameters.name, 'iOS') }}: 53 | - job: ${{ parameters.name }} 54 | displayName: ${{ parameters.name }} 55 | pool: 56 | vmImage: 'macos-latest' 57 | steps: 58 | - template: ios.yml 59 | parameters: 60 | artifactName: ios-drop 61 | ${{ if eq(parameters.debug, 'true') }}: 62 | configuration: 'Debug' 63 | ${{ if eq(parameters.debug, 'false') }}: 64 | configuration: 'Release' 65 | 66 | - ${{ if eq(parameters.name, 'Android') }}: 67 | - job: ${{ parameters.name }} 68 | displayName: ${{ parameters.name }} 69 | pool: 70 | vmImage: 'windows-2022' 71 | steps: 72 | - template: android.yml 73 | parameters: 74 | artifactName: android-drop 75 | ${{ if eq(parameters.debug, 'true') }}: 76 | configuration: 'Debug' 77 | ${{ if eq(parameters.debug, 'false') }}: 78 | configuration: 'Release' 79 | 80 | - ${{ if eq(parameters.name, 'NuGet') }}: 81 | - job: ${{ parameters.name }} 82 | displayName: ${{ parameters.name }} 83 | dependsOn: [Windows, Linux, macOS, Android] 84 | pool: 85 | vmImage: 'windows-2022' 86 | steps: 87 | - template: nuget.yml 88 | parameters: 89 | nuget_version: '6.1.0' 90 | -------------------------------------------------------------------------------- /pipelines/nix.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - task: CMake@1 3 | displayName: 'CMake SEAL' 4 | inputs: 5 | workingDirectory: '$(Build.SourcesDirectory)' 6 | cmakeArgs: '-DCMAKE_BUILD_TYPE=${{ parameters.configuration }} -DSEAL_BUILD_TESTS=ON -DSEAL_BUILD_SEAL_C=ON -DSEAL_BUILD_EXAMPLES=ON .' 7 | 8 | - script: | 9 | cd $BUILD_SOURCESDIRECTORY 10 | make 11 | displayName: 'Build SEAL' 12 | 13 | - script: | 14 | cd $BUILD_SOURCESDIRECTORY 15 | ./bin/sealtest 16 | displayName: 'Run unit tests' 17 | 18 | - task: UseDotNet@2 19 | displayName: 'Get .NET Core 6.0 SDK' 20 | inputs: 21 | packageType: 'sdk' 22 | version: '6.0.x' 23 | 24 | - task: DotNetCoreCLI@2 25 | displayName: 'Run dotnet unit tests' 26 | inputs: 27 | command: test 28 | projects: '**/SEALNetTest.csproj' 29 | arguments: '--configuration ${{ parameters.configuration }} --verbosity detailed' 30 | 31 | - task: CopyFiles@2 32 | displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)' 33 | inputs: 34 | SourceFolder: '$(Build.SourcesDirectory)/lib' 35 | Contents: 'libsealc.*' 36 | TargetFolder: '$(Build.ArtifactStagingDirectory)/lib' 37 | 38 | - task: PublishBuildArtifacts@1 39 | displayName: 'Publish Artifact: drop' 40 | inputs: 41 | PathtoPublish: '$(Build.ArtifactStagingDirectory)' 42 | artifactName: ${{ parameters.artifactName }} 43 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Debug-Android.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Linux in Debug mode. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - master 8 | paths: 9 | exclude: 10 | - 'tools/*' 11 | - LICENSE 12 | - NOTICE 13 | - CHANGES.md 14 | - CODE_OF_CONDUCT.md 15 | - CONTRIBUTING.md 16 | - ISSUES.md 17 | - README.md 18 | - SECURITY.md 19 | 20 | stages: 21 | - stage: build 22 | displayName: Build 23 | jobs: 24 | - template: jobs.yml 25 | parameters: 26 | debug: true 27 | name: Android 28 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Debug-Linux.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Linux in Debug mode. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - master 8 | paths: 9 | exclude: 10 | - 'tools/*' 11 | - LICENSE 12 | - NOTICE 13 | - CHANGES.md 14 | - CODE_OF_CONDUCT.md 15 | - CONTRIBUTING.md 16 | - ISSUES.md 17 | - README.md 18 | - SECURITY.md 19 | 20 | stages: 21 | - stage: build 22 | displayName: Build 23 | jobs: 24 | - template: jobs.yml 25 | parameters: 26 | debug: true 27 | name: Linux 28 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Debug-Windows.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Windows in Debug mode. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - master 8 | paths: 9 | exclude: 10 | - 'tools/*' 11 | - LICENSE 12 | - NOTICE 13 | - CHANGES.md 14 | - CODE_OF_CONDUCT.md 15 | - CONTRIBUTING.md 16 | - ISSUES.md 17 | - README.md 18 | - SECURITY.md 19 | 20 | stages: 21 | - stage: build 22 | displayName: Build 23 | jobs: 24 | - template: jobs.yml 25 | parameters: 26 | debug: true 27 | name: Windows 28 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Debug-iOS.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Mac. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - master 8 | paths: 9 | exclude: 10 | - 'tools/*' 11 | - LICENSE 12 | - NOTICE 13 | - CHANGES.md 14 | - CODE_OF_CONDUCT.md 15 | - CONTRIBUTING.md 16 | - ISSUES.md 17 | - README.md 18 | - SECURITY.md 19 | 20 | stages: 21 | - stage: build 22 | displayName: Build 23 | jobs: 24 | - template: jobs.yml 25 | parameters: 26 | debug: true 27 | name: iOS 28 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Debug-macOS.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on macOS in Debug mode. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - master 8 | paths: 9 | exclude: 10 | - 'tools/*' 11 | - LICENSE 12 | - NOTICE 13 | - CHANGES.md 14 | - CODE_OF_CONDUCT.md 15 | - CONTRIBUTING.md 16 | - ISSUES.md 17 | - README.md 18 | - SECURITY.md 19 | 20 | stages: 21 | - stage: build 22 | displayName: Build 23 | jobs: 24 | - template: jobs.yml 25 | parameters: 26 | debug: true 27 | name: macOS 28 | -------------------------------------------------------------------------------- /pipelines/pipeline-CI-Release-All.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Windows, Linux, and macOS in Release mode. 2 | 3 | trigger: none 4 | 5 | stages: 6 | - stage: build 7 | displayName: Build 8 | jobs: 9 | - template: jobs.yml 10 | parameters: 11 | debug: false 12 | name: Windows 13 | - template: jobs.yml 14 | parameters: 15 | debug: false 16 | name: Linux 17 | - template: jobs.yml 18 | parameters: 19 | debug: false 20 | name: macOS 21 | - template: jobs.yml 22 | parameters: 23 | debug: false 24 | name: Android 25 | - template: jobs.yml 26 | parameters: 27 | debug: false 28 | name: iOS 29 | - template: jobs.yml 30 | parameters: 31 | debug: false 32 | name: NuGet 33 | -------------------------------------------------------------------------------- /pipelines/pipeline-PR-Debug-All.yml: -------------------------------------------------------------------------------- 1 | # This defines a pipeline to build on Windows, Linux, and macOS in Debug mode. 2 | 3 | pr: 4 | branches: 5 | include: 6 | - contrib 7 | paths: 8 | exclude: 9 | - 'tools/*' 10 | - LICENSE 11 | - NOTICE 12 | - CHANGES.md 13 | - CODE_OF_CONDUCT.md 14 | - CONTRIBUTING.md 15 | - ISSUES.md 16 | - README.md 17 | - SECURITY.md 18 | 19 | stages: 20 | - stage: build 21 | displayName: Build 22 | jobs: 23 | - template: jobs.yml 24 | parameters: 25 | debug: true 26 | name: Windows 27 | - template: jobs.yml 28 | parameters: 29 | debug: true 30 | name: Linux 31 | - template: jobs.yml 32 | parameters: 33 | debug: true 34 | name: macOS 35 | - template: jobs.yml 36 | parameters: 37 | debug: true 38 | name: Android 39 | - template: jobs.yml 40 | parameters: 41 | debug: true 42 | name: iOS 43 | -------------------------------------------------------------------------------- /pkgconfig/seal.pc.in: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | prefix=@CMAKE_INSTALL_PREFIX@ 5 | libdir=${prefix}/lib 6 | includedir=${prefix}/@SEAL_INCLUDES_INSTALL_DIR@ 7 | 8 | Name: Microsoft SEAL 9 | Version: @SEAL_VERSION@ 10 | Description: An easy-to-use homomorphic encryption library 11 | 12 | Requires: @SEAL_PKGCONFIG_MSGSL_REQUIRES_STRING@ 13 | Requires: @SEAL_PKGCONFIG_ZLIB_REQUIRES_STRING@ 14 | Requires: @SEAL_PKGCONFIG_ZSTD_REQUIRES_STRING@ 15 | Requires: @SEAL_PKGCONFIG_INTEL_HEXL_REQUIRES_STRING@ 16 | 17 | Libs: -L${libdir} -lseal-@SEAL_VERSION_MAJOR@.@SEAL_VERSION_MINOR@ 18 | Cflags: @SEAL_LANG_FLAG@ -I${includedir} 19 | -------------------------------------------------------------------------------- /pkgconfig/seal_msgsl.pc.in: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | Name: Microsoft GSL for Microsoft SEAL 5 | Version: @Microsoft.GSL_VERSION@ 6 | Description: Guidelines Support Library 7 | 8 | Cflags: -I@SEAL_PKGCONFIG_MSGSL_INCLUDE_DIR@ 9 | -------------------------------------------------------------------------------- /pkgconfig/seal_shared.pc.in: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | prefix=@CMAKE_INSTALL_PREFIX@ 5 | libdir=${prefix}/lib 6 | includedir=${prefix}/@SEAL_INCLUDES_INSTALL_DIR@ 7 | 8 | Name: Microsoft SEAL 9 | Version: @SEAL_VERSION_MAJOR@.@SEAL_VERSION_MINOR@ 10 | Description: An easy-to-use homomorphic encryption library 11 | 12 | Requires: @SEAL_PKGCONFIG_MSGSL_REQUIRES_STRING@ 13 | Requires: @SEAL_PKGCONFIG_ZLIB_REQUIRES_STRING@ 14 | Requires: @SEAL_PKGCONFIG_ZSTD_REQUIRES_STRING@ 15 | Requires: @SEAL_PKGCONFIG_INTEL_HEXL_REQUIRES_STRING@ 16 | 17 | Libs: -L${libdir} -lseal 18 | Cflags: @SEAL_LANG_FLAG@ -I${includedir} 19 | -------------------------------------------------------------------------------- /tools/Makefile: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | SHELL=/bin/bash 5 | COMPR_SYSTEM_INFO_ARCHIVE=../system_info.tar.gz 6 | 7 | .PHONY: system_info clean 8 | 9 | system_info: clean $(COMPR_SYSTEM_INFO_ARCHIVE) 10 | 11 | $(COMPR_SYSTEM_INFO_ARCHIVE): scripts/collect_system_info.sh 12 | @$(SHELL) scripts/collect_system_info.sh 13 | 14 | clean: 15 | @rm -f $(COMPR_SYSTEM_INFO_ARCHIVE) 16 | -------------------------------------------------------------------------------- /tools/config/packages.config: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <packages> 3 | <package id="GoogleTestAdapter" version="0.18.0" /> 4 | </packages> 5 | -------------------------------------------------------------------------------- /tools/scripts/clang-format-all.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (c) Microsoft Corporation. All rights reserved. 4 | # Licensed under the MIT license. 5 | 6 | BASE_DIR=$(dirname "$0") 7 | SEAL_ROOT_DIR=$BASE_DIR/../../ 8 | shopt -s globstar 9 | clang-format -i $SEAL_ROOT_DIR/native/**/*.h 10 | clang-format -i $SEAL_ROOT_DIR/native/**/*.cpp 11 | -------------------------------------------------------------------------------- /tools/scripts/collect_system_info.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (c) Microsoft Corporation. All rights reserved. 4 | # Licensed under the MIT license. 5 | 6 | CMAKE_CXX_COMPILER=cxx_compiler.out 7 | CMAKE_ENV=cmake_env.out 8 | CMAKE_SYSTEM_INFO=system_information.out 9 | SEALDIR=.. 10 | 11 | CMAKE_CXX_COMPILER_CMD=`cmake -LA $SEALDIR|sed -n 's/^CMAKE_CXX_COMPILER:FILEPATH=\(.*\)$/\1/p'` 12 | 13 | echo "Extracting: cmake -LA $SEALDIR > $CMAKE_ENV" 14 | cmake -LA $SEALDIR > $CMAKE_ENV 15 | echo "Extracting: cmake --system-information > $CMAKE_SYSTEM_INFO" 16 | cmake --system-information > $CMAKE_SYSTEM_INFO 17 | echo "Extracting: $CMAKE_CXX_COMPILER_CMD -v > $CMAKE_CXX_COMPILER 2>&1" 18 | $CMAKE_CXX_COMPILER_CMD -v 2> $CMAKE_CXX_COMPILER 19 | 20 | ARCHIVE_NAME=../system_info.tar 21 | FILES=( 22 | "$SEALDIR/native/src/seal/util/config.h" 23 | "$SEALDIR/CMakeCache.txt" 24 | "$SEALDIR/CMakeFiles/CMakeOutput.log" 25 | "$SEALDIR/CMakeFiles/CMakeError.log" 26 | "/proc/cpuinfo" 27 | "$CMAKE_ENV" 28 | "$CMAKE_SYSTEM_INFO" 29 | "$CMAKE_CXX_COMPILER" 30 | ) 31 | 32 | print_collecting_filename() { 33 | echo -e "\033[0mCollecting \033[1;32m$1\033[0m" 34 | } 35 | 36 | print_skipping_filename() { 37 | echo -e "\033[0mSkipping \033[1;31m$1\033[0m" 38 | } 39 | 40 | add_to_archive() { 41 | BASENAME=`basename $1` 42 | cp -f $1 $BASENAME 2>/dev/null 43 | if [ -s $ARCHIVE_NAME ] 44 | then 45 | tar -rf $ARCHIVE_NAME ./$BASENAME 46 | else 47 | tar -cf $ARCHIVE_NAME ./$BASENAME 48 | fi 49 | rm -f ./$BASENAME 50 | } 51 | 52 | rm -f "$ARCHIVE_NAME.gz" 53 | 54 | for i in ${FILES[@]} 55 | do 56 | if [ -r $i ] 57 | then 58 | print_collecting_filename $i 59 | add_to_archive $i 60 | else 61 | print_skipping_filename $i 62 | fi 63 | done 64 | 65 | gzip $ARCHIVE_NAME 66 | if [ $? -eq 0 ] 67 | then 68 | echo "Created `realpath $ARCHIVE_NAME.gz`" 69 | else 70 | echo "Could not create `realpath $ARCHIVE_NAME.gz`" 71 | rm -f $ARCHIVE_NAME.gz 72 | fi 73 | 74 | echo -n "Cleaning up ... " 75 | rm -f $CMAKE_ENV 76 | rm -f $CMAKE_SYSTEM_INFO 77 | rm -f $CMAKE_CXX_COMPILER 78 | echo done. 79 | --------------------------------------------------------------------------------