├── .gitignore ├── misc └── sfe.png ├── include ├── she.hpp └── she │ ├── defs.hpp │ ├── exceptions.hpp │ ├── serializations.hpp │ ├── random.hpp │ ├── plaintext.hpp │ ├── key.hpp │ └── ciphertext.hpp ├── tests ├── test_exceptions.cpp ├── serialization_formats.hpp ├── test_serializations.cpp ├── test_workflow.cpp ├── test_plaintext.cpp ├── test_random.cpp ├── test_key.cpp ├── test_ciphertext.cpp └── test_homomorphic_operations.cpp ├── .travis.yml ├── benchmarks ├── utils.hpp └── pir.cpp ├── src ├── plaintext.cpp ├── random.cpp ├── key.cpp └── ciphertext.cpp ├── Makefile ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /misc/sfe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bogdan-kulynych/libshe/HEAD/misc/sfe.png -------------------------------------------------------------------------------- /include/she.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "she/plaintext.hpp" 4 | #include "she/ciphertext.hpp" 5 | #include "she/key.hpp" -------------------------------------------------------------------------------- /include/she/defs.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | 6 | namespace she 7 | { 8 | 9 | const unsigned int INTEGER_SERIALIZATION_BASE = 62; 10 | const std::string RANDOM_DEVICE = "/dev/urandom"; 11 | 12 | } // namespace she 13 | -------------------------------------------------------------------------------- /tests/test_exceptions.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE ExceptionsModule 3 | #include 4 | #include 5 | 6 | #include "she/exceptions.hpp" 7 | 8 | using she::precondition_not_satisfied; 9 | 10 | 11 | BOOST_AUTO_TEST_SUITE(ExceptionsSuite) 12 | 13 | BOOST_AUTO_TEST_CASE(precondition_not_satisfied_construction_and_accessors) 14 | { 15 | try { 16 | ASSERT(true == false, "Obviously not."); 17 | } catch (const precondition_not_satisfied & e) { 18 | BOOST_CHECK_EQUAL(e.what(), "Obviously not. (true == false)"); 19 | } 20 | } 21 | 22 | BOOST_AUTO_TEST_SUITE_END() 23 | 24 | -------------------------------------------------------------------------------- /include/she/exceptions.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | namespace she 9 | { 10 | 11 | class precondition_not_satisfied : public std::exception 12 | { 13 | public: 14 | precondition_not_satisfied(const std::string & msg) noexcept : _msg(msg) {}; 15 | const char * what() const noexcept { return _msg.c_str(); } 16 | 17 | private: 18 | std::string _msg; 19 | }; 20 | 21 | } // namespace she 22 | 23 | 24 | #define ASSERT( condition, msg ) { \ 25 | if (!(condition)) { \ 26 | std::stringstream ss; \ 27 | ss << msg << " (" << #condition << ")"; \ 28 | throw she::precondition_not_satisfied(ss.str()); \ 29 | } } 30 | -------------------------------------------------------------------------------- /tests/serialization_formats.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using boost::archive::xml_oarchive; 9 | using boost::archive::xml_iarchive; 10 | using boost::archive::text_oarchive; 11 | using boost::archive::text_iarchive; 12 | 13 | 14 | template 15 | struct Format { 16 | using iarchive = InputArchive; 17 | using oarchive = OutputArchive; 18 | }; 19 | 20 | using Formats = boost::mpl::list< Format, 21 | Format >; 22 | -------------------------------------------------------------------------------- /tests/test_serializations.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE SerializationsModule 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include "she/serializations.hpp" 9 | #include "serialization_formats.hpp" 10 | 11 | using std::stringstream; 12 | 13 | 14 | BOOST_AUTO_TEST_SUITE(SerializationsSuite) 15 | 16 | BOOST_AUTO_TEST_CASE_TEMPLATE(mpz_class_serialization, Format, Formats) 17 | { 18 | mpz_class z = mpz_class(1) << 10000; 19 | mpz_class restored_z; 20 | 21 | stringstream ss; 22 | { 23 | typename Format::oarchive oa(ss); 24 | oa << BOOST_SERIALIZATION_NVP(z); 25 | } 26 | { 27 | typename Format::iarchive ia(ss); 28 | ia >> BOOST_SERIALIZATION_NVP(restored_z); 29 | } 30 | 31 | BOOST_CHECK(z == restored_z); 32 | } 33 | 34 | BOOST_AUTO_TEST_SUITE_END() -------------------------------------------------------------------------------- /include/she/serializations.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #include "defs.hpp" 12 | 13 | 14 | namespace boost { namespace serialization { 15 | 16 | template 17 | void save(Archive & ar, const mpz_class & value, const unsigned int version) 18 | { 19 | std::string repr = value.get_str(she::INTEGER_SERIALIZATION_BASE); 20 | ar & BOOST_SERIALIZATION_NVP(repr); 21 | } 22 | 23 | template 24 | void load(Archive & ar, mpz_class & value, const unsigned int version) 25 | { 26 | std::string repr; 27 | ar & BOOST_SERIALIZATION_NVP(repr); 28 | value.set_str(repr, she::INTEGER_SERIALIZATION_BASE); 29 | } 30 | 31 | }} // namespace boost::serialization 32 | 33 | BOOST_SERIALIZATION_SPLIT_FREE(mpz_class) 34 | -------------------------------------------------------------------------------- /include/she/random.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | 11 | namespace she 12 | { 13 | 14 | class CSPRNG 15 | { 16 | public: 17 | CSPRNG() noexcept; 18 | 19 | mpz_class get_bits(unsigned int bits) const noexcept; 20 | mpz_class get_range_bits(unsigned int bits) const noexcept; 21 | mpz_class get_range(const mpz_class & upper_bound) const noexcept; 22 | 23 | private: 24 | mutable gmp_randclass _generator; 25 | }; 26 | 27 | 28 | class PseudoRandomStream 29 | { 30 | public: 31 | PseudoRandomStream(unsigned int size, unsigned int seed); 32 | 33 | const mpz_class & next() const noexcept; 34 | const void reset() const noexcept; 35 | static void reset_cache() noexcept { cached_values.clear(); } 36 | 37 | private: 38 | unsigned int _size; 39 | unsigned int _seed; 40 | mutable gmp_randclass _generator; 41 | 42 | mutable size_t _current_value; 43 | 44 | using keys_t = std::pair; 45 | using values_t = std::vector; 46 | 47 | static std::map cached_values; 48 | }; 49 | 50 | } // namespace she 51 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | 3 | compiler: 4 | - g++ 5 | 6 | env: 7 | global: 8 | secure: UCL6P2+jglTd/qzlnx2gZ/mlS5W7AAtC8W5vePE+SmXVuVJLDEA96PJmKCi2t5MuYUhimJFZ4UsbTkQ7yZU7SjHeDN1YhOcK1dih0hPU9ml+Wcuplj4P3jL0UBFQmXbglup2VO3xjoxdEHCTlhQTm5WGg0M1n+Lx/P+n8vvixCk= 9 | 10 | before_install: 11 | - sudo add-apt-repository -y ppa:boost-latest/ppa 12 | - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test 13 | - sudo apt-get update -qq 14 | 15 | install: 16 | # GCC 4.9 17 | - sudo apt-get install -qq g++-4.9 libstdc++-4.9-dev 18 | - export CC="gcc-4.9" 19 | - export CXX="g++-4.9" 20 | - export GCOV="gcov-4.9" 21 | 22 | # lcov 1.11 23 | - wget http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.11.orig.tar.gz 24 | - tar xf lcov_1.11.orig.tar.gz 25 | - sudo make -C lcov-1.11/ install 26 | 27 | # Boost, GMP 28 | - sudo apt-get install -qq boost1.55 libgmp-dev 29 | 30 | # Coveralls 31 | - gem install coveralls-lcov 32 | 33 | script: 34 | - make tests 35 | - make 36 | 37 | after_success: 38 | - ${GCOV} --version 39 | - lcov --version 40 | - make coverage GCOV=${GCOV} 41 | - coveralls-lcov --repo-token ${COVERALLSTOKEN} build/coverage.info 42 | 43 | cache: 44 | - apt 45 | 46 | notifications: 47 | email: 48 | on_failure: change 49 | 50 | webhooks: 51 | urls: 52 | - https://webhooks.gitter.im/e/08d9936d9d017472517e 53 | on_success: change 54 | on_failure: always 55 | on_start: false 56 | -------------------------------------------------------------------------------- /benchmarks/utils.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | using chrono_t = std::chrono::duration; 9 | std::map _timer_global; 10 | 11 | 12 | #define START_TIMER( section, group ) \ 13 | _timer_global.emplace(std::pair(group, {})); \ 14 | std::string _timer_group = group; \ 15 | std::cout << "> " << section << std::endl; \ 16 | std::chrono::time_point _timer_start, _timer_end; \ 17 | _timer_start = std::chrono::system_clock::now(); 18 | 19 | #define END_TIMER() \ 20 | _timer_end = std::chrono::system_clock::now(); \ 21 | chrono_t elapsed_seconds = _timer_end - _timer_start; \ 22 | _timer_global[_timer_group] += elapsed_seconds; \ 23 | std::cout << "< Seconds: " << elapsed_seconds.count() << std::endl; \ 24 | std::cout << std::endl; 25 | 26 | #define TIMER_STATS() \ 27 | chrono_t _total_seconds {}; \ 28 | for (const auto & entry : _timer_global) { \ 29 | const auto & group = entry.first; \ 30 | const auto & elapsed_seconds = entry.second; \ 31 | std::cout << "Group " << group << ". "; \ 32 | std::cout << "Seconds: " << elapsed_seconds.count() << std::endl; \ 33 | _total_seconds += elapsed_seconds; \ 34 | } \ 35 | std::cout << "-----" << std::endl; \ 36 | std::cout << "Total seconds: " << _total_seconds.count() << std::endl; \ 37 | std::cout << std::endl; -------------------------------------------------------------------------------- /src/plaintext.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "she.hpp" 4 | #include "she/exceptions.hpp" 5 | 6 | using std::min; 7 | using std::max; 8 | using std::vector; 9 | 10 | 11 | namespace she 12 | { 13 | 14 | PlaintextArray & PlaintextArray::operator^=(const PlaintextArray & other) noexcept 15 | { 16 | const size_t n = min(_elements.size(), other._elements.size()); 17 | 18 | // Do bit-wise XOR 19 | for (size_t i = 0; i < n; ++i) { 20 | _elements[i] = _elements[i] ^ other._elements[i]; 21 | } 22 | 23 | // If sizes don't match pad with zeros from the right 24 | for (size_t i = n; i < other._elements.size(); ++i) { 25 | _elements.push_back(other._elements[i]); 26 | } 27 | 28 | return *this; 29 | } 30 | 31 | PlaintextArray & PlaintextArray::operator&=(const PlaintextArray & other) noexcept 32 | { 33 | const size_t n = min(_elements.size(), other._elements.size()); 34 | 35 | // Do bit-wise AND 36 | for (size_t i = 0; i < n; ++i) { 37 | _elements[i] = _elements[i] & other._elements[i]; 38 | } 39 | 40 | // If sizes don't match pad with ones from the right 41 | for (size_t i = n; i < other._elements.size(); ++i) { 42 | _elements.push_back(other._elements[i]); 43 | } 44 | 45 | return *this; 46 | } 47 | 48 | PlaintextArray & PlaintextArray::extend(const PlaintextArray & other) noexcept 49 | { 50 | for (const auto & element : other._elements) { 51 | _elements.push_back(element); 52 | } 53 | 54 | return *this; 55 | } 56 | 57 | bool PlaintextArray::operator==(const PlaintextArray & other) const noexcept 58 | { 59 | return _elements == other._elements; 60 | } 61 | 62 | } // namespace she -------------------------------------------------------------------------------- /src/random.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "she/random.hpp" 4 | #include "she/defs.hpp" 5 | 6 | using std::out_of_range; 7 | using std::random_device; 8 | using std::make_pair; 9 | using std::map; 10 | using std::pair; 11 | using std::vector; 12 | 13 | 14 | namespace she 15 | { 16 | 17 | CSPRNG::CSPRNG() noexcept : _generator(gmp_randinit_default) 18 | { 19 | // Generate 64-bit seed 20 | random_device dev(RANDOM_DEVICE); 21 | mpz_class seed32 = dev(); 22 | _generator.seed(seed32 << 32 | dev()); 23 | } 24 | 25 | mpz_class 26 | CSPRNG::get_bits(unsigned int bits) const noexcept 27 | { 28 | return _generator.get_z_bits(bits); 29 | } 30 | 31 | mpz_class 32 | CSPRNG::get_range_bits(unsigned int bits) const noexcept 33 | { 34 | return _generator.get_z_range(mpz_class(1) << bits);; 35 | } 36 | 37 | mpz_class 38 | CSPRNG::get_range(const mpz_class & upper_bound) const noexcept 39 | { 40 | return _generator.get_z_range(upper_bound); 41 | } 42 | 43 | 44 | PseudoRandomStream::PseudoRandomStream(unsigned int size, unsigned int seed) : 45 | _size(size), 46 | _seed(seed), 47 | _generator(gmp_randinit_default), 48 | _current_value(0) 49 | { 50 | _generator.seed(seed); 51 | } 52 | 53 | map PseudoRandomStream::cached_values = {}; 54 | 55 | const mpz_class & PseudoRandomStream::next() const noexcept 56 | { 57 | keys_t context{_size, _seed}; 58 | auto it = PseudoRandomStream::cached_values.find(context); 59 | 60 | if (it != cached_values.end()) { 61 | if (it->second.size() <= _current_value) { 62 | it->second.push_back(_generator.get_z_bits(_size)); 63 | } 64 | } else { 65 | cached_values[context] = vector{_generator.get_z_bits(_size)}; 66 | } 67 | 68 | return cached_values[context][_current_value++]; 69 | } 70 | 71 | const void PseudoRandomStream::reset() const noexcept 72 | { 73 | _current_value = 0; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /tests/test_workflow.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE WorkflowModule 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | #include "she.hpp" 13 | 14 | using std::vector; 15 | using std::stringstream; 16 | 17 | using boost::archive::text_oarchive; 18 | using boost::archive::text_iarchive; 19 | 20 | using she::ParameterSet; 21 | using she::PrivateKey; 22 | using she::CompressedCiphertext; 23 | using she::EncryptedArray; 24 | using she::PlaintextArray; 25 | 26 | 27 | BOOST_AUTO_TEST_SUITE(WorkflowSuite) 28 | 29 | BOOST_AUTO_TEST_CASE(sfe_simulation) 30 | { 31 | stringstream ss1; 32 | stringstream ss2; 33 | 34 | PrivateKey * sk; 35 | 36 | // ----------- CLIENT ---------------------------------------------- 37 | { 38 | const auto params = ParameterSet::generate_parameter_set(22, 1, 42); 39 | 40 | // Generate private key 41 | sk = new PrivateKey(params); 42 | 43 | // Encrypt plaintext 44 | const vector plaintext = {1, 0, 1, 0}; 45 | const auto compressed_ciphertext = sk->encrypt(plaintext); 46 | 47 | text_oarchive oa1(ss1); 48 | oa1 << compressed_ciphertext; 49 | } 50 | 51 | // ----------- SERVER ---------------------------------------------- 52 | 53 | { 54 | CompressedCiphertext received_compressed_ciphertext; 55 | text_iarchive ia1(ss1); 56 | ia1 >> received_compressed_ciphertext; 57 | 58 | // Expand the ciphertext to perform operations 59 | const auto ciphertext = received_compressed_ciphertext.expand(); 60 | 61 | // Execute some algorithm 62 | const vector another_plaintext = {1, 1, 1, 1}; 63 | const auto response = ciphertext ^ PlaintextArray(another_plaintext); 64 | 65 | // Serialize result 66 | text_oarchive oa2(ss2); 67 | oa2 << response; 68 | } 69 | 70 | // ----------- CLIENT ---------------------------------------------- 71 | 72 | { 73 | EncryptedArray received_response; 74 | text_iarchive ia2(ss2); 75 | ia2 >> received_response; 76 | 77 | const auto decrypted_response = sk->decrypt(received_response); 78 | const vector expected_result = {0, 1, 0, 1}; 79 | 80 | BOOST_CHECK(decrypted_response == expected_result); 81 | } 82 | } 83 | 84 | BOOST_AUTO_TEST_SUITE_END() 85 | -------------------------------------------------------------------------------- /include/she/plaintext.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "serializations.hpp" 13 | 14 | 15 | namespace she 16 | { 17 | 18 | class EncryptedArray; 19 | 20 | class PlaintextArray : boost::equality_comparable > > 24 | { 25 | friend class EncryptedArray; 26 | public: 27 | // Construct from plaintext 28 | PlaintextArray(const std::vector & plaintext) noexcept : _elements(plaintext) {} 29 | 30 | // Empty ctor for deserialization purposes 31 | PlaintextArray() noexcept {}; 32 | 33 | // Convert to bits 34 | operator const std::vector() const { return _elements; }; 35 | operator std::vector() { return _elements; }; 36 | 37 | // Element-wise addition (XOR) 38 | PlaintextArray & operator^=(const PlaintextArray &) noexcept; 39 | 40 | // Element-wise multiplication (AND) 41 | PlaintextArray & operator&=(const PlaintextArray &) noexcept; 42 | 43 | // Homomorphic equality comparison 44 | const PlaintextArray equal(const std::vector &) const noexcept; 45 | const EncryptedArray equal(const std::vector &) const noexcept; 46 | 47 | // Homomorphic select function 48 | const PlaintextArray select(const std::vector &) const noexcept; 49 | const EncryptedArray select(const std::vector &) const noexcept; 50 | 51 | // Extend array 52 | PlaintextArray & extend(const PlaintextArray & other) noexcept; 53 | 54 | // EncryptedArray compatibility 55 | unsigned int degree() const noexcept { return 0; } 56 | unsigned int max_degree() const noexcept { return 0; } 57 | 58 | // Ciphertext size 59 | size_t size() const noexcept { return _elements.size(); } 60 | 61 | // Encrypted bits 62 | const std::vector& elements() const noexcept { return _elements; } 63 | std::vector& elements() noexcept { return _elements; } 64 | 65 | // Representation comparison 66 | bool operator==(const PlaintextArray &) const noexcept; 67 | 68 | private: 69 | friend class boost::serialization::access; 70 | 71 | std::vector _elements; 72 | 73 | template 74 | void serialize(Archive & ar, unsigned int const version) const 75 | { 76 | ar & BOOST_SERIALIZATION_NVP(_elements); 77 | } 78 | }; 79 | 80 | } // namespace she -------------------------------------------------------------------------------- /tests/test_plaintext.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE PlaintextModule 3 | #include 4 | #include 5 | 6 | #include "she.hpp" 7 | #include "serialization_formats.hpp" 8 | 9 | using std::stringstream; 10 | using std::vector; 11 | 12 | using she::PlaintextArray; 13 | 14 | 15 | BOOST_AUTO_TEST_SUITE(PlaintextArraySuite) 16 | 17 | BOOST_AUTO_TEST_CASE(plaintext_array_construction_accessors_and_comparison) 18 | { 19 | const vector raw_plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 20 | 21 | const PlaintextArray a1(raw_plaintext); 22 | 23 | BOOST_CHECK_EQUAL(a1.degree(), 0); 24 | BOOST_CHECK_EQUAL(a1.size(), raw_plaintext.size()); 25 | 26 | const PlaintextArray a2(raw_plaintext); 27 | 28 | BOOST_CHECK_EQUAL(a2.degree(), 0); 29 | 30 | BOOST_CHECK(a1 == a2); 31 | BOOST_CHECK(!(a1 != a2)); 32 | } 33 | 34 | BOOST_AUTO_TEST_CASE(plaintext_array_implicit_conversions) 35 | { 36 | vector raw_plaintext = { 1, 0, 1, 0 }; 37 | 38 | const PlaintextArray array = raw_plaintext; 39 | BOOST_CHECK(array == raw_plaintext); 40 | } 41 | 42 | // FIXME: The commented code doesn't compile, but it should 43 | BOOST_AUTO_TEST_CASE_TEMPLATE(plaintext_array_serialization, Format, Formats) 44 | { 45 | const vector plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 46 | const PlaintextArray array(plaintext); 47 | 48 | PlaintextArray restored_array; 49 | 50 | // stringstream ss; 51 | // { 52 | // typename Format::oarchive oa(ss); 53 | // oa << BOOST_SERIALIZATION_NVP(array); 54 | // } 55 | // { 56 | // typename Format::iarchive ia(ss); 57 | // ia >> BOOST_SERIALIZATION_NVP(restored_array); 58 | // } 59 | 60 | // BOOST_CHECK(array == restored_array); 61 | } 62 | 63 | BOOST_AUTO_TEST_CASE(plaintext_arrays_extend_empty) 64 | { 65 | PlaintextArray array; 66 | const auto plaintext = PlaintextArray({1, 1, 1, 1}); 67 | array.extend(plaintext); 68 | 69 | BOOST_CHECK(array.elements() == plaintext.elements()); 70 | } 71 | 72 | BOOST_AUTO_TEST_CASE(plaintext_arrays_extend) 73 | { 74 | const auto expected_result = PlaintextArray({1, 1, 0, 0, 0, 0, 1, 1}); 75 | 76 | PlaintextArray array({1, 1, 0, 0}); 77 | const auto plaintext = PlaintextArray({0, 0, 1, 1}); 78 | array.extend(plaintext); 79 | 80 | BOOST_CHECK(array.elements() == expected_result.elements()); 81 | } 82 | 83 | BOOST_AUTO_TEST_CASE(plaintext_arrays_concat) 84 | { 85 | const vector< vector> raw_plaintext_inputs = { 86 | {0, 1, 0, 1}, 87 | {1, 0, 1, 0}, 88 | {0, 0, 0, 0}, 89 | {1, 1, 1, 1} 90 | }; 91 | 92 | vector plaintext_inputs; 93 | for (const auto & raw_plaintext_input : raw_plaintext_inputs) { 94 | plaintext_inputs.push_back(PlaintextArray(raw_plaintext_input)); 95 | } 96 | 97 | const auto expected_result = PlaintextArray({0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1}); 98 | 99 | BOOST_CHECK(concat(plaintext_inputs) == expected_result); 100 | } 101 | 102 | BOOST_AUTO_TEST_SUITE_END() -------------------------------------------------------------------------------- /tests/test_random.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE RandomModule 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include "she/random.hpp" 9 | 10 | using std::vector; 11 | using std::abs; 12 | 13 | using she::CSPRNG; 14 | using she::PseudoRandomStream; 15 | 16 | 17 | BOOST_AUTO_TEST_SUITE(CSPRNG_Suite) 18 | 19 | BOOST_AUTO_TEST_CASE(generator_construction) 20 | { 21 | const CSPRNG generator; 22 | } 23 | 24 | BOOST_AUTO_TEST_CASE(generator_get_bits) 25 | { 26 | const CSPRNG generator; 27 | 28 | const size_t iterations = 15; 29 | const int bits = 100; 30 | 31 | for (size_t i = 0; i < iterations; ++i) { 32 | const auto output = generator.get_bits(bits); 33 | const auto output_bits = static_cast(mpz_sizeinbase(output.get_mpz_t(), 2)); 34 | // BOOST_CHECK_EQUAL(output_bits, bits); 35 | } 36 | } 37 | 38 | BOOST_AUTO_TEST_CASE(generator_get_range_bits) 39 | { 40 | const CSPRNG generator; 41 | 42 | const size_t iterations = 30; 43 | const int bits = 100; 44 | 45 | for (size_t i = 0; i < iterations; ++i) { 46 | const auto output = generator.get_range_bits(bits); 47 | const auto output_bits = static_cast(mpz_sizeinbase(output.get_mpz_t(), 2)); 48 | BOOST_CHECK_LT(output_bits, bits + 1); 49 | } 50 | } 51 | 52 | BOOST_AUTO_TEST_CASE(generator_get_range) 53 | { 54 | const CSPRNG generator; 55 | 56 | const size_t iterations = 15; 57 | const int bits = 100; 58 | mpz_class upper_bound = mpz_class(1) << bits; 59 | 60 | for (size_t i = 0; i < iterations; ++i) { 61 | mpz_class output = generator.get_range(upper_bound); 62 | BOOST_CHECK(output <= upper_bound); 63 | } 64 | } 65 | 66 | BOOST_AUTO_TEST_SUITE_END() 67 | 68 | 69 | BOOST_AUTO_TEST_SUITE(PseudoRandomStreamSuite) 70 | 71 | BOOST_AUTO_TEST_CASE(prf_stream_construction) 72 | { 73 | const PseudoRandomStream prf_stream(100, 42); 74 | } 75 | 76 | BOOST_AUTO_TEST_CASE(prf_stream_output_generation) 77 | { 78 | const int bits = 100; 79 | const unsigned int seed = 42; 80 | const PseudoRandomStream prf_stream(bits, seed); 81 | const auto prf_stream_outputs = { prf_stream.next(), prf_stream.next(), prf_stream.next() }; 82 | 83 | for (const auto & prf_stream_output : prf_stream_outputs) 84 | { 85 | const auto output_bits = static_cast(mpz_sizeinbase(prf_stream_output.get_mpz_t(), 2)); 86 | // BOOST_CHECK_EQUAL(output_bits, bits); 87 | } 88 | } 89 | 90 | BOOST_AUTO_TEST_CASE(prf_stream_determinism) 91 | { 92 | const int bits = 100; 93 | const unsigned int seed = 42; 94 | const PseudoRandomStream nostradamus(bits, seed), pythia(bits, seed), paul_the_octopus(bits, seed + 1); 95 | 96 | const size_t iterations = 5; 97 | 98 | for (size_t i = 0; i < iterations; ++i) { 99 | const auto pythia_output = pythia.next(); 100 | BOOST_CHECK(nostradamus.next() == pythia_output); 101 | BOOST_CHECK(pythia_output != paul_the_octopus.next()); 102 | } 103 | } 104 | 105 | BOOST_AUTO_TEST_CASE(prf_stream_cache_reset) 106 | { 107 | const PseudoRandomStream nostradamus(10, 10), pythia(10, 10); 108 | 109 | const mpz_class & nostradamus_output_reference = nostradamus.next(); 110 | const mpz_class nostradamus_output_copy = mpz_class(nostradamus_output_reference); 111 | 112 | const mpz_class pythia_output = mpz_class(pythia.next()); 113 | 114 | BOOST_CHECK(nostradamus_output_reference == pythia_output); 115 | BOOST_CHECK(nostradamus_output_copy == pythia_output); 116 | 117 | PseudoRandomStream::reset_cache(); 118 | 119 | BOOST_CHECK(nostradamus_output_reference != pythia_output); 120 | BOOST_CHECK(nostradamus_output_copy == pythia_output); 121 | } 122 | 123 | BOOST_AUTO_TEST_SUITE_END() 124 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | 3 | BOOSTDIR := /usr/local/lib 4 | PREFIX := /usr/local 5 | 6 | CXXFLAGS := -Wall -fPIC -std=c++11 -pedantic 7 | 8 | INCDIR := include 9 | SRCDIR := src 10 | BUILDDIR := build 11 | TESTDIR := tests 12 | BENCHDIR := benchmarks 13 | 14 | LIBS := -L$(BOOSTDIR) -lboost_serialization -lstdc++ -lgmp 15 | TESTLIBS := -L$(BOOSTDIR) -lboost_unit_test_framework 16 | INC := -I$(INCDIR) 17 | 18 | LIBSOURCES := $(wildcard $(SRCDIR)/*.cpp) 19 | TESTSOURCES := $(wildcard $(TESTDIR)/*.cpp) 20 | BENCHSOURCES := $(wildcard $(BENCHDIR)/*.cpp) 21 | LIBOBJECTS := $(patsubst %.cpp,$(BUILDDIR)/%.o, $(LIBSOURCES)) 22 | TESTOBJECTS := $(patsubst %.cpp,$(BUILDDIR)/%.o, $(TESTSOURCES)) 23 | BENCHOBJECTS := $(patsubst %.cpp,$(BUILDDIR)/%.o, $(BENCHSOURCES)) 24 | TESTTARGETS := $(patsubst %.cpp,$(BUILDDIR)/%, $(TESTSOURCES)) 25 | BENCHTARGETS := $(patsubst %.cpp,$(BUILDDIR)/%, $(BENCHSOURCES)) 26 | 27 | LIBTARGET := $(BUILDDIR)/libshe.so 28 | 29 | TESTOPTS := --log_level=test_suite 30 | COVERAGEFILE := $(BUILDDIR)/coverage.info 31 | GCOV := gcov 32 | 33 | 34 | define \n 35 | 36 | 37 | endef 38 | 39 | # Messages 40 | 41 | LINK := > Link 42 | COMPILE := > Cmpl 43 | EXEC := > Exec 44 | 45 | .PHONY: all 46 | all: library 47 | 48 | # Library 49 | 50 | .PHONY: library 51 | library: CXXFLAGS += -O3 52 | library: $(LIBTARGET) 53 | 54 | $(LIBTARGET): $(LIBOBJECTS) 55 | @echo "$(LINK): $^" 56 | @$(CXX) $(LDFLAGS) -shared $^ $(LIBS) -o $@ 57 | 58 | $(LIBOBJECTS): $(BUILDDIR)/%.o: %.cpp 59 | @echo "$(COMPILE): $^" 60 | @mkdir -p $(BUILDDIR)/$(SRCDIR) 61 | @$(CXX) $(CXXFLAGS) $(INC) -c $^ -o $@ 62 | 63 | # Tests 64 | 65 | .PHONY: tests 66 | tests: CXXFLAGS += -O0 -DDEBUG -g --coverage 67 | tests: LDFLAGS = --coverage 68 | tests: $(LIBSOURCES) 69 | tests: $(TESTSOURCES) 70 | tests: $(TESTTARGETS) 71 | 72 | $(TESTTARGETS): $(LIBOBJECTS) 73 | $(TESTTARGETS): $(BUILDDIR)/%: $(BUILDDIR)/%.o 74 | @echo "$(LINK): $^" 75 | @$(CXX) $(LDFLAGS) $^ $(TESTLIBS) $(LIBS) -o $@ 76 | $(foreach exe,$@,@echo "$(EXEC): $(exe)" && ./$(exe) $(TESTOPTS)${\n}) 77 | 78 | $(TESTOBJECTS): $(BUILDDIR)/%.o: %.cpp 79 | @echo "$(COMPILE): $^" 80 | @mkdir -p $(BUILDDIR)/$(TESTDIR) 81 | @$(CXX) $(CXXFLAGS) $(INC) -c $^ -o $@ 82 | 83 | # Coverage report 84 | 85 | .PHONY: coverage 86 | coverage: 87 | @lcov --gcov-tool $(GCOV) --directory . --capture --output-file $(COVERAGEFILE) 88 | @lcov --gcov-tool $(GCOV) --remove $(COVERAGEFILE) 'tests/*' '/usr/*' --output-file $(COVERAGEFILE) 2> /dev/null 89 | @lcov --gcov-tool $(GCOV) --list $(COVERAGEFILE) 90 | @genhtml $(COVERAGEFILE) --output-directory $(BUILDDIR)/coverage 91 | 92 | # Benchmarks 93 | 94 | .PHONY: benchmarks 95 | benchmarks: $(LIBSOURCES) 96 | benchmarks: $(BENCHSOURCES) 97 | benchmarks: $(BENCHTARGETS) 98 | $(foreach exe,$<,@echo "$(EXEC): $(exe)" && ./$(exe) $(TESTOPTS)${\n}) 99 | 100 | $(BENCHTARGETS): $(LIBOBJECTS) 101 | $(BENCHTARGETS): $(BUILDDIR)/%: $(BUILDDIR)/%.o 102 | @echo "$(LINK): $^" 103 | @$(CXX) $(LDFLAGS) $^ $(LIBS) -o $@ 104 | 105 | $(BENCHOBJECTS): $(BUILDDIR)/%.o: %.cpp 106 | @echo "$(COMPILE): $^" 107 | @mkdir -p $(BUILDDIR)/$(BENCHDIR) 108 | @$(CXX) $(CXXFLAGS) $(INC) -c $^ -o $@ 109 | 110 | # Installation 111 | 112 | .PHONY: install 113 | install: $(BUILDDIR)/$(LIBTARGET) 114 | @mkdir -p $(PREFIX)/include 115 | @mkdir -p $(PREFIX)/lib 116 | cp -rf $(INCDIR) -t $(PREFIX) 117 | cp -f $(BUILDDIR)/$(LIBTARGET) -t $(PREFIX)/lib/ 118 | ldconfig 119 | 120 | .PHONY: uninstall 121 | uninstall: 122 | rm $(PREFIX)/lib/$(LIBTARGET) 123 | $(foreach header,$(shell ls -1 $(INCDIR)),rm -r $(PREFIX)/include/$(header)${\n}) 124 | ldconfig 125 | 126 | .PHONY: clean 127 | clean: 128 | rm -rf $(BUILDDIR) 129 | -------------------------------------------------------------------------------- /include/she/key.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | 14 | #include "random.hpp" 15 | #include "serializations.hpp" 16 | 17 | 18 | namespace she 19 | { 20 | 21 | class ParameterSet : boost::equality_comparable 22 | { 23 | public: 24 | ParameterSet(unsigned int security, 25 | unsigned int noise_size_bits, 26 | unsigned int private_key_size_bits, 27 | unsigned int ciphertext_size_bits, 28 | unsigned int prf_seed); 29 | 30 | ParameterSet() noexcept; 31 | 32 | unsigned int security; 33 | unsigned int noise_size_bits; 34 | unsigned int private_key_size_bits; 35 | unsigned int ciphertext_size_bits; 36 | unsigned int prf_seed; 37 | 38 | // Generate parameter set for given `security`, random prf `seed`, that allows to perform at least 39 | // `circuit_mult_size homomorphic multiplications on ciphertexts 40 | static const ParameterSet 41 | generate_parameter_set(unsigned int security, unsigned int circuit_mult_size, unsigned int seed); 42 | 43 | // Approximate number of homomorphic multiplications that can be performed 44 | unsigned int degree() const noexcept { return private_key_size_bits / noise_size_bits; } 45 | 46 | bool operator==(const ParameterSet &) const noexcept; 47 | 48 | private: 49 | friend class boost::serialization::access; 50 | 51 | template 52 | void serialize(Archive & ar, unsigned int const version) 53 | { 54 | ar & BOOST_SERIALIZATION_NVP(security); 55 | ar & BOOST_SERIALIZATION_NVP(noise_size_bits); 56 | ar & BOOST_SERIALIZATION_NVP(private_key_size_bits); 57 | ar & BOOST_SERIALIZATION_NVP(ciphertext_size_bits); 58 | ar & BOOST_SERIALIZATION_NVP(prf_seed); 59 | } 60 | }; 61 | 62 | 63 | class CompressedCiphertext; 64 | class EncryptedArray; 65 | 66 | class PrivateKey : boost::equality_comparable 67 | { 68 | public: 69 | // Constuct private from parameter set 70 | PrivateKey(const ParameterSet &) noexcept; 71 | 72 | // Empty ctor for deserialization purposes 73 | PrivateKey() noexcept {}; 74 | 75 | // Produce a compressed ciphertext from a plaintext 76 | CompressedCiphertext encrypt(const std::vector & bits) const noexcept; 77 | 78 | // Decrypt an expanded ciphertext 79 | std::vector decrypt(const EncryptedArray &) const noexcept; 80 | 81 | const ParameterSet & parameter_set() const noexcept { return _parameter_set; }; 82 | const mpz_class & private_element() const noexcept { return _private_element; } 83 | 84 | bool operator==(const PrivateKey &) const noexcept; 85 | 86 | private: 87 | ParameterSet _parameter_set; 88 | 89 | void initialize_random_generators() const noexcept; 90 | mutable std::unique_ptr _generator; 91 | mutable std::unique_ptr _prf_stream; 92 | 93 | PrivateKey& generate_values() noexcept; 94 | mpz_class _private_element; 95 | 96 | private: 97 | friend class boost::serialization::access; 98 | 99 | template 100 | void save(Archive & ar, unsigned int const version) const 101 | { 102 | ar & BOOST_SERIALIZATION_NVP(_parameter_set); 103 | ar & BOOST_SERIALIZATION_NVP(_private_element); 104 | } 105 | 106 | template 107 | void load(Archive & ar, unsigned int const version) 108 | { 109 | ar & BOOST_SERIALIZATION_NVP(_parameter_set); 110 | ar & BOOST_SERIALIZATION_NVP(_private_element); 111 | 112 | initialize_random_generators(); 113 | } 114 | 115 | BOOST_SERIALIZATION_SPLIT_MEMBER() 116 | }; 117 | 118 | 119 | } // namespace she 120 | -------------------------------------------------------------------------------- /src/key.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | using std::cout; 6 | using std::endl; 7 | 8 | #include "she.hpp" 9 | #include "she/defs.hpp" 10 | #include "she/exceptions.hpp" 11 | 12 | using std::random_device; 13 | using std::vector; 14 | 15 | 16 | namespace she 17 | { 18 | ParameterSet::ParameterSet(unsigned int lambda, 19 | unsigned int rho, 20 | unsigned int eta, 21 | unsigned int gamma, 22 | unsigned int seed) : 23 | security(lambda), 24 | noise_size_bits(rho), 25 | private_key_size_bits(eta), 26 | ciphertext_size_bits(gamma), 27 | prf_seed(seed) 28 | { 29 | ASSERT((gamma >= eta) && (eta >= rho) && (rho > 0), "Bad parameters"); 30 | } 31 | 32 | ParameterSet::ParameterSet() noexcept : 33 | security(1), 34 | noise_size_bits(1), 35 | private_key_size_bits(1), 36 | ciphertext_size_bits(1), 37 | prf_seed(1) 38 | {} 39 | 40 | const ParameterSet 41 | ParameterSet::generate_parameter_set(unsigned int security, unsigned int circuit_mult_size, unsigned int seed) 42 | { 43 | ASSERT(security > 0, "Security parameter should be greater than 0"); 44 | ASSERT(circuit_mult_size > 0, "Multiplicative circuit size should be greater than 0"); 45 | 46 | unsigned int rho = 2 * security, 47 | eta = security * security + security * circuit_mult_size, 48 | gamma = eta * eta * circuit_mult_size; 49 | 50 | return { security, rho, eta, gamma, seed }; 51 | } 52 | 53 | bool ParameterSet::operator==(const ParameterSet& other) const 54 | noexcept 55 | { 56 | return (security == other.security) 57 | && (noise_size_bits == other.noise_size_bits) 58 | && (private_key_size_bits == other.private_key_size_bits) 59 | && (ciphertext_size_bits == other.ciphertext_size_bits) 60 | && (prf_seed == other.prf_seed); 61 | } 62 | 63 | 64 | PrivateKey::PrivateKey(const ParameterSet & parameter_set) noexcept : 65 | _parameter_set(parameter_set) 66 | { 67 | initialize_random_generators(); 68 | generate_values(); 69 | } 70 | 71 | bool PrivateKey::operator==(const PrivateKey & other) const noexcept 72 | { 73 | return (_parameter_set == other._parameter_set) 74 | && (_private_element == other._private_element); 75 | } 76 | 77 | PrivateKey& PrivateKey::generate_values() noexcept 78 | { 79 | // Generate odd eta-bit integer 80 | do { 81 | _private_element = _generator->get_bits(_parameter_set.private_key_size_bits); 82 | } while (_private_element % 2 == 0); 83 | 84 | // Generate random odd q from [1, 2^gamma / p) 85 | const mpz_class q_upper_bound = (mpz_class(1) << _parameter_set.ciphertext_size_bits) 86 | / _private_element; 87 | mpz_class q; 88 | do { 89 | q = _generator->get_range(q_upper_bound); 90 | } while (q % 2 == 0); 91 | 92 | return *this; 93 | } 94 | 95 | void PrivateKey::initialize_random_generators() const noexcept 96 | { 97 | _generator.reset(new CSPRNG); 98 | _prf_stream.reset( 99 | new PseudoRandomStream{_parameter_set.ciphertext_size_bits, _parameter_set.prf_seed}); 100 | } 101 | 102 | CompressedCiphertext PrivateKey::encrypt(const std::vector & bits) const noexcept 103 | { 104 | _prf_stream->reset(); 105 | 106 | CompressedCiphertext result(_parameter_set); 107 | 108 | // Generate compressed public element 109 | const mpz_class & prf_output = _prf_stream->next(); 110 | result._public_element_delta = prf_output % _private_element; 111 | 112 | for (const bool m : bits) 113 | { 114 | // Choose random noise 115 | const mpz_class r = _generator->get_range_bits(_parameter_set.noise_size_bits) + 1; 116 | 117 | // Random PRF output 118 | const mpz_class & prf_output = _prf_stream->next(); 119 | 120 | // Add compressed ciphertext deltas 121 | result._elements_deltas.push_back((prf_output - 2*r - m) % _private_element); 122 | } 123 | 124 | return result; 125 | } 126 | 127 | vector PrivateKey::decrypt(const EncryptedArray & array) const noexcept 128 | { 129 | _prf_stream->reset(); 130 | 131 | vector result; 132 | for (const mpz_class & element : array.elements()) 133 | { 134 | const mpz_class m = element % _private_element % 2; 135 | result.push_back(static_cast(m.get_si())); 136 | } 137 | return result; 138 | } 139 | 140 | } // namespace she 141 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libshe 2 | 3 | [![Build Status](https://travis-ci.org/bogdan-kulynych/libshe.svg?branch=master)](https://travis-ci.org/bogdan-kulynych/libshe) [![Coverage Status](https://coveralls.io/repos/bogdan-kulynych/libshe/badge.svg?branch=master)](https://coveralls.io/r/bogdan-kulynych/libshe?branch=master) 4 | 5 | Symmetric somewhat homomorphic encryption library based on DGHV scheme. 6 | 7 | 8 | ## Introduction 9 | 10 | Homomorphic encryption is a kind of encryption that allows to execute functions over the ciphertexts without decrypting them. This library implements a symmetric variant of originally asymmetric somewhat homomorphic encryption scheme over the integers by van Dijk et al. [DGHV10][DGHV10] using ciphertext compression techniques from [CNT11][CNT11]. The symmetricity of the scheme means that only the private key is used to encrypt and decrypt ciphertexts. A relatively small public element, however, is used in homomorphic operations, but it is not a real public key. 11 | 12 | Such scheme is useful in secure function evaluation setting, where a client encrypts an input to an algorithm using their private key, sends it to a server which executes an algorithm homorphically, and sends the output back to the client. The client then obtains the output of the algorithm by decrypting server response using the private key. 13 | 14 | See the following diagram for visual explanation. 15 | 16 | - Let _f_ be an algorithm to be evaluated on a server. 17 | - Let _a[1], a[2], ... a[n]_ be inputs of _f_ that client provides to the server. 18 | - Let _b[1], b[2], ... b[n]_ be inputs of _f_ that server possesses. 19 | - Let _p_ be the client's private key, and _x[0]_ be the corresponding public element 20 | 21 | ![SFE](misc/sfe.png) 22 | 23 | 24 | ## Status 25 | 26 | _Warning_. This is experimental software. **It is not to be used in mission-critical applications.** Since the time this software was written, parameters of the underlying scheme were broken many times. 27 | 28 | ## Installation 29 | 30 | You can consult the `.travis.yml` for concrete installation commands on Debian-based systems. 31 | 32 | ### Requirements 33 | 34 | - gcc >= 4.8 35 | - [boost](http://www.boost.org/) >= 1.55 36 | - [GMP](https://gmplib.org/) >= 6.0.0 37 | - [lcov](http://ltp.sourceforge.net/coverage/lcov/readme.php) >= 1.11 (optional) 38 | 39 | ### Building and installation 40 | 41 | Build and install `libshe.so` library and headers: 42 | 43 | ``` 44 | make 45 | sudo make install 46 | ``` 47 | 48 | You can also uninstall with 49 | 50 | ``` 51 | sudo make uninstall 52 | ``` 53 | 54 | ## Usage 55 | 56 | ### Tests and benchmarks 57 | 58 | Run tests: 59 | 60 | ``` 61 | make tests 62 | ``` 63 | 64 | _Note_. Running tests will compile sources with debug options. Do `make clean` before installing if tests were run previously. 65 | 66 | Run benchmarks: 67 | 68 | ``` 69 | make benchmarks 70 | ``` 71 | 72 | ### Building your program 73 | 74 | Use C++11 and link against _GMP_ and _Boost Serialization_ when building your program: 75 | 76 | ``` 77 | -std=c++11 -lgmp -lboost_serialization -lshe 78 | ``` 79 | 80 | Include libshe in your sources: 81 | 82 | ```cpp 83 | #include 84 | 85 | using she::ParameterSet; 86 | using she::PrivateKey; 87 | // ... 88 | ``` 89 | 90 | ### Example 91 | 92 | The following example assumes a client and a server that are engaged in a two-party secure function evaluation protocol. 93 | 94 | Client generates a parameter set: 95 | 96 | ```cpp 97 | const ParameterSet params = ParameterSet::generate_parameter_set(62, 1, 42); 98 | ``` 99 | 100 | Given these parameters, the encryption scheme exhibits following properties: 101 | 102 | - Security level is **(62-bit)** 103 | - At least 1 multiplication can be evaluated on every bit in the ciphertext 104 | - The non-secure random number generator used in ciphertext compression is seeded with number 42 105 | 106 | Client then constructs a private key object from generated parameters: 107 | 108 | ```cpp 109 | const PrivateKey sk(params); 110 | ``` 111 | 112 | Encrypts the plaintext: 113 | 114 | ```cpp 115 | const vector plaintext = {1, 0, 1, 0, 1, 0, 1, 0}; 116 | const auto compressed_ciphertext = sk.encrypt(plaintext); 117 | ``` 118 | 119 | Serializes and sends compressed ciphertext to server. 120 | 121 | Upon obtaining the compressed ciphertext, Server expands it to perform operations: 122 | 123 | ```cpp 124 | const auto ciphertext = compressed_ciphertext.expand(); 125 | ``` 126 | 127 | Executes the algorithm (here negation of an 8-bit input) 128 | 129 | ```cpp 130 | const vector another_plaintext = {1, 1, 1, 1, 1, 1, 1, 1}; 131 | const auto response = ciphertext ^ another_plaintext; 132 | ``` 133 | 134 | Serializes the output and sends it back to the client. 135 | 136 | Client decrypts the response and obtains the algorithm output in plaintext: 137 | 138 | ```cpp 139 | const auto decrypted_response = sk.decrypt(response); 140 | const vector expected_result = {0, 1, 0, 1, 0, 1, 0, 1}; 141 | assert(decrypted_response == expected_result); 142 | ``` 143 | 144 | Note that ciphertext can be compressed only during encryption on the client side, so cost for Server → Client communication is significantly higher than that of Client → Server communication. 145 | 146 | ### Available homomorphic operations 147 | 148 | - Bitwise addition (XOR): `c1 ^ c2` 149 | - Bitwise multiplication (AND): `c1 & c2` 150 | - Equality comparison: `c0.equal({c1, c2, ..., cn})`.. 151 | - Selection of _i_-th ciphertext: `c0.select({c1, c2, ..., cn})`. 152 | 153 | ## License 154 | 155 | The code is released under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.html). 156 | 157 | Copyright © 2015 Bogdan Kulynych. `hello [at] bogdankulynych.me` 158 | 159 | 160 | 161 | [DGHV10]: http://eprint.iacr.org/2009/616.pdf 162 | [CNT11]: http://eprint.iacr.org/2011/440.pdf 163 | -------------------------------------------------------------------------------- /tests/test_key.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE KeyModule 3 | #include 4 | #include 5 | 6 | #include "she.hpp" 7 | #include "she/exceptions.hpp" 8 | #include "serialization_formats.hpp" 9 | 10 | using std::abs; 11 | using std::stringstream; 12 | using std::vector; 13 | 14 | using she::precondition_not_satisfied; 15 | using she::ParameterSet; 16 | using she::PrivateKey; 17 | 18 | 19 | BOOST_AUTO_TEST_SUITE(ParameterSetSuite) 20 | 21 | 22 | BOOST_AUTO_TEST_CASE(parameter_set_construction) 23 | { 24 | { 25 | BOOST_CHECK_THROW(ParameterSet(42, 1000, 100, 10000, 5), precondition_not_satisfied); 26 | BOOST_CHECK_THROW(ParameterSet(42, 100, 1000, 999, 5), precondition_not_satisfied); 27 | BOOST_CHECK_THROW(ParameterSet(42, 0, 1, 2, 5), precondition_not_satisfied); 28 | } 29 | 30 | { 31 | const ParameterSet params { 42, 100, 1000, 100000, 5 }; 32 | BOOST_CHECK_EQUAL(params.security, 42); 33 | BOOST_CHECK_EQUAL(params.noise_size_bits, 100); 34 | BOOST_CHECK_EQUAL(params.private_key_size_bits, 1000); 35 | BOOST_CHECK_EQUAL(params.ciphertext_size_bits, 100000); 36 | BOOST_CHECK_EQUAL(params.prf_seed, 5); 37 | } 38 | } 39 | 40 | BOOST_AUTO_TEST_CASE(parameter_set_generation) 41 | { 42 | { 43 | BOOST_CHECK_THROW(ParameterSet::generate_parameter_set(0, 0, 42), 44 | precondition_not_satisfied); 45 | BOOST_CHECK_THROW(ParameterSet::generate_parameter_set(0, 1, 42), 46 | precondition_not_satisfied); 47 | BOOST_CHECK_THROW(ParameterSet::generate_parameter_set(1, 0, 42), 48 | precondition_not_satisfied); 49 | } 50 | 51 | { 52 | const unsigned int security = 42; 53 | const unsigned int circuit_mult_size = 20; 54 | const ParameterSet params = ParameterSet::generate_parameter_set(security, circuit_mult_size, 42); 55 | 56 | BOOST_CHECK_EQUAL( 57 | params.security, 58 | security 59 | ); 60 | 61 | BOOST_CHECK_EQUAL( 62 | params.noise_size_bits, 63 | 2 * security 64 | ); 65 | 66 | BOOST_CHECK_EQUAL( 67 | params.private_key_size_bits, 68 | security * security + security * circuit_mult_size 69 | ); 70 | 71 | BOOST_CHECK_EQUAL( 72 | params.ciphertext_size_bits, 73 | params.private_key_size_bits * params.private_key_size_bits * circuit_mult_size 74 | ); 75 | 76 | BOOST_CHECK_GT( 77 | params.degree() - 1, 78 | circuit_mult_size 79 | ); 80 | } 81 | } 82 | 83 | BOOST_AUTO_TEST_CASE(parameter_set_equality_comparison) 84 | { 85 | const ParameterSet a { 42, 100, 1000, 100000, 5 }; 86 | const ParameterSet b { 42, 100, 1000, 100000, 5 }; 87 | const ParameterSet c { 72, 100, 1000, 100000, 5 }; 88 | 89 | BOOST_CHECK(a == b); 90 | BOOST_CHECK(b != c); 91 | BOOST_CHECK(c != a); 92 | } 93 | 94 | BOOST_AUTO_TEST_CASE_TEMPLATE(parameter_set_serialization, Format, Formats) 95 | { 96 | const ParameterSet params { 42, 100, 1000, 100000, 5 }; 97 | ParameterSet restored_params {}; 98 | 99 | stringstream ss; 100 | { 101 | typename Format::oarchive oa(ss); 102 | oa << BOOST_SERIALIZATION_NVP(params); 103 | } 104 | { 105 | typename Format::iarchive ia(ss); 106 | ia >> BOOST_SERIALIZATION_NVP(restored_params); 107 | } 108 | 109 | BOOST_CHECK(params == restored_params); 110 | } 111 | 112 | BOOST_AUTO_TEST_SUITE_END() 113 | 114 | 115 | BOOST_AUTO_TEST_SUITE(PrivateKeySuite) 116 | 117 | BOOST_AUTO_TEST_CASE(private_key_construction_accessors_and_comparison) 118 | { 119 | const auto params = ParameterSet::generate_parameter_set(42, 10, 42); 120 | const PrivateKey sk(params); 121 | 122 | BOOST_CHECK(sk.parameter_set() == params); 123 | const auto private_element_size = mpz_sizeinbase(sk.private_element().get_mpz_t(), 2); 124 | // BOOST_CHECK_EQUAL(private_element_size, params.private_key_size_bits); 125 | 126 | // These should not be the same, because new private key elements are generated every time 127 | const PrivateKey other_sk(params); 128 | BOOST_CHECK(sk != other_sk); 129 | BOOST_CHECK(!(sk == other_sk)); 130 | } 131 | 132 | BOOST_AUTO_TEST_CASE(private_key_encryption) 133 | { 134 | const auto params = ParameterSet::generate_parameter_set(42, 5, 42); 135 | const PrivateKey sk(params); 136 | 137 | { 138 | sk.encrypt({}); 139 | } 140 | 141 | { 142 | sk.encrypt({1, 0, 0, 0}); 143 | } 144 | } 145 | 146 | BOOST_AUTO_TEST_CASE(private_key_encryption_decryption) 147 | { 148 | const auto params = ParameterSet::generate_parameter_set(42, 5, 42); 149 | const PrivateKey sk(params); 150 | 151 | const size_t iterations = 15; 152 | 153 | const vector plaintext = {1, 0, 1, 0, 1, 1, 1, 0}; 154 | unsigned int successful_recoveries = 0; 155 | for (size_t i = 0; i < iterations; ++i) 156 | { 157 | const auto ciphertext = sk.encrypt(plaintext); 158 | const auto restored_plaintext = sk.decrypt(ciphertext.expand()); 159 | if(restored_plaintext == plaintext) { 160 | ++successful_recoveries; 161 | } 162 | } 163 | 164 | BOOST_CHECK_EQUAL(successful_recoveries, iterations); 165 | } 166 | 167 | BOOST_AUTO_TEST_CASE_TEMPLATE(private_key_serialization, Format, Formats) 168 | { 169 | const auto params = ParameterSet::generate_parameter_set(42, 5, 42); 170 | const PrivateKey sk(params); 171 | PrivateKey restored_sk; 172 | 173 | stringstream ss; 174 | { 175 | typename Format::oarchive oa(ss); 176 | oa << BOOST_SERIALIZATION_NVP(sk); 177 | } 178 | { 179 | typename Format::iarchive ia(ss); 180 | ia >> BOOST_SERIALIZATION_NVP(restored_sk); 181 | } 182 | 183 | BOOST_CHECK(sk == restored_sk); 184 | } 185 | 186 | BOOST_AUTO_TEST_SUITE_END() 187 | -------------------------------------------------------------------------------- /benchmarks/pir.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "she.hpp" 8 | #include "utils.hpp" 9 | 10 | using std::cout; 11 | using std::endl; 12 | using std::boolalpha; 13 | using std::vector; 14 | using std::unique_ptr; 15 | using std::move; 16 | 17 | using she::PrivateKey; 18 | using she::ParameterSet; 19 | using she::CompressedCiphertext; 20 | using she::EncryptedArray; 21 | using she::PlaintextArray; 22 | 23 | 24 | vector dec_to_bits(unsigned int num, unsigned int bit_size) 25 | { 26 | vector result; 27 | for (int i = bit_size - 1; i >= 0; --i) { 28 | result.push_back((num >> i) & 1); 29 | } 30 | return result; 31 | } 32 | 33 | vector random_bits(unsigned int bit_size) 34 | { 35 | vector result {}; 36 | for (unsigned int i = 0; i < bit_size; ++i) { 37 | bool random_bit = rand() % 2; 38 | result.push_back(random_bit); 39 | } 40 | 41 | return result; 42 | } 43 | 44 | void 45 | randomly_populate_database( vector * database 46 | , unsigned int database_size 47 | , unsigned int record_size) 48 | { 49 | for (unsigned int i = 0; i < database_size; ++i) { 50 | database->push_back(PlaintextArray(random_bits(record_size))); 51 | } 52 | } 53 | 54 | void build_database_indexes( vector * database_indexes 55 | , unsigned int database_size 56 | , unsigned int index_size) 57 | { 58 | for (unsigned int i = 0; i < database_size; ++i) { 59 | database_indexes->push_back(dec_to_bits(i, index_size)); 60 | } 61 | } 62 | 63 | PrivateKey generate_key( unsigned int security 64 | , unsigned int record_size) 65 | { 66 | START_TIMER("KEY GENERATION", "CLIENT"); 67 | 68 | const auto params = ParameterSet::generate_parameter_set(security, record_size, 42); 69 | auto result = PrivateKey(params); 70 | 71 | END_TIMER(); 72 | 73 | return result; 74 | } 75 | 76 | CompressedCiphertext 77 | generate_query( const PrivateKey & sk 78 | , const vector & index_bits) 79 | { 80 | START_TIMER("QUERY GENERATION", "CLIENT"); 81 | 82 | auto result = sk.encrypt(index_bits); 83 | 84 | END_TIMER(); 85 | return result; 86 | } 87 | 88 | EncryptedArray expand_ciphertext(const CompressedCiphertext & ctxt) 89 | { 90 | START_TIMER("QUERY CIPHERTEXT EXPANSION", "SERVER"); 91 | 92 | auto result = ctxt.expand(); 93 | 94 | END_TIMER(); 95 | return result; 96 | } 97 | 98 | EncryptedArray 99 | calculate_selection_vector( const EncryptedArray & query 100 | , const vector & database_indexes) 101 | { 102 | START_TIMER("SELECTION VECTOR HOMOMORPHIC CALCULATION", "SERVER"); 103 | 104 | auto result = query.equal(database_indexes); 105 | 106 | END_TIMER(); 107 | return result; 108 | } 109 | 110 | EncryptedArray 111 | calculate_response( const EncryptedArray & sv 112 | , const vector & database) 113 | { 114 | START_TIMER("RESPONSE HOMOMORPHIC CALCULATION", "SERVER"); 115 | 116 | auto result = sv.select(database); 117 | 118 | END_TIMER(); 119 | return result; 120 | } 121 | 122 | PlaintextArray 123 | decrypt_response( const PrivateKey & sk 124 | , const EncryptedArray & response) 125 | { 126 | START_TIMER("RESPONSE DECRYPTION", "CLIENT"); 127 | 128 | auto result = sk.decrypt(response); 129 | 130 | END_TIMER(); 131 | return result; 132 | } 133 | 134 | 135 | int main() 136 | { 137 | srand (time(NULL)); 138 | 139 | // Security level. 62 for 62-bit security 140 | unsigned int security = 62; 141 | 142 | // Number of records in a database 143 | unsigned int database_size = 16; 144 | 145 | // Size of every record in bits (note that in general sizes can vary) 146 | unsigned int record_size = 64; 147 | 148 | // Size of database index in bits. 149 | // To avoid problems should be equal to floor(log2(database_size) + 1 150 | unsigned int index_size = 4; 151 | 152 | cout << "Security: " << security << endl; 153 | cout << "Database size: " << database_size << endl; 154 | cout << "Record size: " << record_size << endl; 155 | cout << "Index size: " << index_size << endl << endl; 156 | 157 | // Preparation: Generate random database 158 | vector database; 159 | randomly_populate_database(&database, database_size, record_size); 160 | 161 | // Preparation: Generate database indexes 162 | vector database_indexes; 163 | build_database_indexes(&database_indexes, database_size, index_size); 164 | 165 | // Generate key 166 | const auto sk = move(generate_key(security, index_size)); 167 | 168 | // Pick random index and generate compressed query ciphertext 169 | // This is the slowest part. Should consider options to move it to client side. 170 | const auto index = rand() % database_size; 171 | const auto compressed_ciphertext = move(generate_query(sk, dec_to_bits(index, index_size))); 172 | 173 | // Expand the compressed ciphertext 174 | const auto encrypted_query = move(expand_ciphertext(compressed_ciphertext)); 175 | 176 | // Calculate homomorphic selection vector 177 | const auto selector = move(calculate_selection_vector(encrypted_query, database_indexes)); 178 | 179 | // Homomorphically calculate response 180 | const auto encrypted_response = move(calculate_response(selector, database)); 181 | 182 | // Decrypt response 183 | std::vector response = move(decrypt_response(sk, encrypted_response)); 184 | 185 | TIMER_STATS(); 186 | 187 | // Show response if it is small enough 188 | if (record_size < 80) { 189 | cout << "Queried database index:" << endl; 190 | for (const auto & bit : database[index].elements()) { 191 | cout << bit; 192 | } 193 | cout << endl; 194 | 195 | cout << "Obtained result:" << endl; 196 | for (const auto & bit : response) { 197 | cout << bit; 198 | } 199 | cout << endl; 200 | } 201 | 202 | cout << "Correct result? " << boolalpha << (database[index] == response) << endl; 203 | 204 | return 0; 205 | } -------------------------------------------------------------------------------- /include/she/ciphertext.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | #include "key.hpp" 17 | #include "random.hpp" 18 | #include "serializations.hpp" 19 | 20 | 21 | namespace she 22 | { 23 | 24 | class PrivateKey; 25 | class PlaintextArray; 26 | 27 | class EncryptedArray : boost::equality_comparable > > > > 33 | { 34 | friend class PlaintextArray; 35 | friend class CompressedCiphertext; 36 | public: 37 | // Construct empty ciphertext with given public element 38 | EncryptedArray(const mpz_class & x, unsigned int max_degree, unsigned int degree=1) noexcept; 39 | 40 | // Empty ctor for deserialization purposes 41 | EncryptedArray() noexcept {}; 42 | 43 | // Homomorphic element-wise addition (XOR) 44 | EncryptedArray & operator^=(const PlaintextArray &) noexcept; 45 | EncryptedArray & operator^=(const EncryptedArray &) noexcept; 46 | 47 | // Homomorphic element-wise multiplication (AND) 48 | EncryptedArray & operator&=(const PlaintextArray &) noexcept; 49 | EncryptedArray & operator&=(const EncryptedArray &) noexcept; 50 | 51 | // Homomorphic equality comparison 52 | const EncryptedArray equal(const std::vector &) const noexcept; 53 | const EncryptedArray equal(const std::vector &) const noexcept; 54 | 55 | // Homomorphic select function 56 | const EncryptedArray select(const std::vector &) const noexcept; 57 | const EncryptedArray select(const std::vector &) const noexcept; 58 | 59 | // Extend array 60 | EncryptedArray & extend(const EncryptedArray & other) noexcept; 61 | 62 | // Reflects how noisy the ciphertexts, equals the number of homomorphic multiplications performed since encryption 63 | unsigned int degree() const noexcept { return _degree; } 64 | 65 | // Approximate maximum number of homomorphic multiplications 66 | unsigned int max_degree() const noexcept { return _max_degree; } 67 | 68 | // Ciphertext size 69 | size_t size() const noexcept { return _elements.size(); } 70 | 71 | // Encrypted bits 72 | const std::vector& elements() const noexcept { return _elements; } 73 | std::vector& elements() noexcept { return _elements; } 74 | 75 | // Public element used in homomorphic operations 76 | const mpz_class & public_element() const noexcept; 77 | 78 | // Representation comparison (non-homomorphic) 79 | bool operator==(const EncryptedArray &) const noexcept; 80 | 81 | private: 82 | unsigned int _degree; 83 | unsigned int _max_degree; 84 | 85 | std::vector _elements; 86 | 87 | void set_public_element(const mpz_class & x) noexcept; 88 | static std::set public_elements; 89 | typename std::set::const_iterator _public_element_ptr; 90 | 91 | bool _initialized; 92 | 93 | private: 94 | friend class boost::serialization::access; 95 | 96 | template 97 | void save(Archive & ar, unsigned int const version) const 98 | { 99 | ar & BOOST_SERIALIZATION_NVP(_degree); 100 | ar & BOOST_SERIALIZATION_NVP(_max_degree); 101 | ar & BOOST_SERIALIZATION_NVP(_elements); 102 | ar & boost::serialization::make_nvp("_public_element", *_public_element_ptr); 103 | } 104 | 105 | template 106 | void load(Archive & ar, unsigned int const version) 107 | { 108 | 109 | ar & BOOST_SERIALIZATION_NVP(_degree); 110 | ar & BOOST_SERIALIZATION_NVP(_max_degree); 111 | ar & BOOST_SERIALIZATION_NVP(_elements); 112 | 113 | mpz_class x; 114 | ar & boost::serialization::make_nvp("_public_element", x); 115 | set_public_element(x); 116 | } 117 | 118 | BOOST_SERIALIZATION_SPLIT_MEMBER() 119 | }; 120 | 121 | 122 | class CompressedCiphertext : boost::equality_comparable 123 | { 124 | friend class PrivateKey; 125 | public: 126 | // Empty ctor for deserialization purposes 127 | CompressedCiphertext() noexcept {}; 128 | 129 | // Expand ciphertext 130 | EncryptedArray expand() const noexcept; 131 | 132 | // Ciphertext size 133 | size_t size() const noexcept { return _elements_deltas.size(); } 134 | 135 | // Compressions of encrypted bits 136 | const std::vector & elements_deltas() const noexcept { return _elements_deltas; } 137 | const mpz_class & public_element_delta() const noexcept { return _public_element_delta; } 138 | 139 | // Representation comparison 140 | bool operator== (const CompressedCiphertext &) const noexcept; 141 | 142 | private: 143 | CompressedCiphertext(const ParameterSet & params) noexcept; 144 | 145 | ParameterSet _parameter_set; 146 | 147 | void initialize_prf_stream() const noexcept; 148 | mutable std::unique_ptr _prf_stream; 149 | 150 | std::vector _elements_deltas; 151 | mpz_class _public_element_delta; 152 | 153 | private: 154 | friend class boost::serialization::access; 155 | 156 | template 157 | void save(Archive & ar, unsigned int const version) const 158 | { 159 | ar & BOOST_SERIALIZATION_NVP(_parameter_set); 160 | ar & BOOST_SERIALIZATION_NVP(_elements_deltas); 161 | ar & BOOST_SERIALIZATION_NVP(_public_element_delta); 162 | } 163 | 164 | template 165 | void load(Archive & ar, unsigned int const version) 166 | { 167 | ar & BOOST_SERIALIZATION_NVP(_parameter_set); 168 | ar & BOOST_SERIALIZATION_NVP(_elements_deltas); 169 | ar & BOOST_SERIALIZATION_NVP(_public_element_delta); 170 | 171 | initialize_prf_stream(); 172 | } 173 | 174 | BOOST_SERIALIZATION_SPLIT_MEMBER() 175 | }; 176 | 177 | 178 | // Homomorphic addition (XOR) 179 | PlaintextArray sum(const std::vector &) noexcept; 180 | EncryptedArray sum(const std::vector &) noexcept; 181 | 182 | // Homomorphic multiplication (AND) 183 | PlaintextArray product(const std::vector &) noexcept; 184 | EncryptedArray product(const std::vector &) noexcept; 185 | 186 | // Arrays concatenation 187 | PlaintextArray concat(const std::vector &) noexcept; 188 | EncryptedArray concat(const std::vector &) noexcept; 189 | 190 | 191 | } // namespace she 192 | -------------------------------------------------------------------------------- /tests/test_ciphertext.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE CiphertextModule 3 | #include 4 | #include 5 | 6 | #include "she.hpp" 7 | #include "serialization_formats.hpp" 8 | 9 | using std::stringstream; 10 | using std::vector; 11 | 12 | using she::PrivateKey; 13 | using she::ParameterSet; 14 | using she::CompressedCiphertext; 15 | using she::PlaintextArray; 16 | using she::EncryptedArray; 17 | 18 | 19 | BOOST_AUTO_TEST_SUITE(CompressedCiphertextSuite) 20 | 21 | BOOST_AUTO_TEST_CASE(compressed_ciphertext_construction_accessors_and_comparison) 22 | { 23 | const PrivateKey sk(ParameterSet::generate_parameter_set(42, 10, 42)); 24 | vector plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 25 | 26 | { 27 | const auto compressed_ciphertext = sk.encrypt(plaintext); 28 | 29 | BOOST_CHECK_EQUAL(compressed_ciphertext.size(), plaintext.size()); 30 | BOOST_CHECK_EQUAL(compressed_ciphertext.elements_deltas().size(), plaintext.size()); 31 | BOOST_CHECK(compressed_ciphertext.public_element_delta() < sk.private_element()); 32 | } 33 | 34 | { 35 | // These should be different, because new noises are generated on every encryption 36 | const auto c1 = sk.encrypt(plaintext); 37 | const auto c2 = sk.encrypt(plaintext); 38 | BOOST_CHECK(c1 != c2); 39 | BOOST_CHECK(!(c1 == c2)); 40 | } 41 | } 42 | 43 | BOOST_AUTO_TEST_CASE(compressed_ciphertext_correct_expansion) 44 | { 45 | const PrivateKey sk(ParameterSet::generate_parameter_set(42, 5, 42)); 46 | const vector plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 47 | const auto compressed_ciphertext = sk.encrypt(plaintext); 48 | const auto expanded_ciphertext = compressed_ciphertext.expand(); 49 | const auto restored_plaintext = sk.decrypt(expanded_ciphertext); 50 | 51 | BOOST_CHECK(expanded_ciphertext.public_element() % sk.private_element() == 0); 52 | BOOST_CHECK_EQUAL(restored_plaintext.size(), plaintext.size()); 53 | } 54 | 55 | BOOST_AUTO_TEST_CASE_TEMPLATE(compressed_ciphertext_serialization, Format, Formats) 56 | { 57 | const PrivateKey sk(ParameterSet::generate_parameter_set(42, 10, 42)); 58 | const auto ciphertext = sk.encrypt({1, 0, 1, 0, 1, 1, 1, 1}); 59 | 60 | CompressedCiphertext restored_ciphertext; 61 | 62 | stringstream ss; 63 | { 64 | typename Format::oarchive oa(ss); 65 | oa << BOOST_SERIALIZATION_NVP(ciphertext); 66 | } 67 | { 68 | typename Format::iarchive ia(ss); 69 | ia >> BOOST_SERIALIZATION_NVP(restored_ciphertext); 70 | } 71 | 72 | BOOST_CHECK(ciphertext == restored_ciphertext); 73 | } 74 | 75 | BOOST_AUTO_TEST_SUITE_END() 76 | 77 | 78 | BOOST_AUTO_TEST_SUITE(EncryptedArraySuite) 79 | 80 | BOOST_AUTO_TEST_CASE(encrypted_array_construction_from_encryption) 81 | { 82 | const vector plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 83 | 84 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 10, 42)); 85 | 86 | const auto compressed_ciphertext = sk.encrypt(plaintext); 87 | const auto a1 = compressed_ciphertext.expand(); 88 | 89 | BOOST_CHECK_EQUAL(a1.size(), plaintext.size()); 90 | BOOST_CHECK_EQUAL(a1.elements().size(), plaintext.size()); 91 | BOOST_CHECK_EQUAL(a1.degree(), 1); 92 | BOOST_CHECK_EQUAL(a1.max_degree(), sk.parameter_set().degree()); 93 | BOOST_CHECK(a1.public_element() % sk.private_element() == 0); 94 | } 95 | 96 | BOOST_AUTO_TEST_CASE(encrypted_array_comparison) 97 | { 98 | const vector plaintext = {1, 0, 1, 0, 1, 1, 1, 1}; 99 | 100 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 10, 42)); 101 | 102 | const auto c1 = sk.encrypt(plaintext); 103 | const auto c2 = sk.encrypt(plaintext); 104 | const auto a1 = c1.expand(); 105 | const auto a2 = c2.expand(); 106 | 107 | BOOST_CHECK_EQUAL(a1.size(), a2.size()); 108 | BOOST_CHECK_EQUAL(a1.elements().size(), a2.elements().size()); 109 | BOOST_CHECK_EQUAL(a1.degree(), a2.degree()); 110 | BOOST_CHECK_EQUAL(a1.max_degree(), a2.max_degree()); 111 | BOOST_CHECK(a1.public_element() % sk.private_element() == 0); 112 | BOOST_CHECK(a2.public_element() % sk.private_element() == 0); 113 | 114 | BOOST_CHECK(a1 != a2); 115 | BOOST_CHECK(!(a1 == a2)); 116 | } 117 | 118 | BOOST_AUTO_TEST_CASE(encrypted_array_empty_construction) 119 | { 120 | const mpz_class x = 42; 121 | const EncryptedArray a1(x, 10); 122 | 123 | BOOST_CHECK_EQUAL(a1.size(), 0); 124 | BOOST_CHECK_EQUAL(a1.elements().size(), 0); 125 | BOOST_CHECK_EQUAL(a1.degree(), 1); 126 | BOOST_CHECK(a1.public_element() == x); 127 | 128 | const EncryptedArray a2(x, 10); 129 | BOOST_CHECK(a1 == a2); 130 | BOOST_CHECK(!(a1 != a2)); 131 | } 132 | 133 | BOOST_AUTO_TEST_CASE_TEMPLATE(encrypted_array_serialization, Format, Formats) 134 | { 135 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 136 | const auto array = sk.encrypt({1, 0, 1, 0, 1, 1, 1, 1}).expand(); 137 | 138 | EncryptedArray restored_array; 139 | 140 | stringstream ss; 141 | { 142 | typename Format::oarchive oa(ss); 143 | oa << BOOST_SERIALIZATION_NVP(array); 144 | } 145 | { 146 | typename Format::iarchive ia(ss); 147 | ia >> BOOST_SERIALIZATION_NVP(restored_array); 148 | } 149 | 150 | BOOST_CHECK(array == restored_array); 151 | } 152 | 153 | BOOST_AUTO_TEST_CASE(encrypted_arrays_extend_empty) 154 | { 155 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 156 | 157 | auto array = sk.encrypt({}).expand(); 158 | const auto plaintext = PlaintextArray({1, 1, 1, 1}); 159 | const auto ciphertext = sk.encrypt(plaintext).expand(); 160 | array.extend(ciphertext); 161 | 162 | BOOST_CHECK(sk.decrypt(array) == plaintext.elements()); 163 | } 164 | 165 | BOOST_AUTO_TEST_CASE(encrypted_arrays_concatenation_empty) 166 | { 167 | const auto expected_result = PlaintextArray({1, 1, 0, 0, 0, 0, 1, 1}); 168 | 169 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 10, 42)); 170 | 171 | auto array = sk.encrypt({1, 1, 0, 0}).expand(); 172 | const auto ciphertext = sk.encrypt({0, 0, 1, 1}).expand(); 173 | array.extend(ciphertext); 174 | 175 | BOOST_CHECK(sk.decrypt(array) == expected_result.elements()); 176 | } 177 | 178 | BOOST_AUTO_TEST_CASE(encrypted_arrays_concat) 179 | { 180 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 181 | 182 | const vector< vector> raw_plaintext_inputs = { 183 | {0, 1, 0, 1}, 184 | {1, 0, 1, 0}, 185 | {0, 0, 0, 0}, 186 | {1, 1, 1, 1} 187 | }; 188 | 189 | vector encrypted_inputs; 190 | for (const auto & raw_plaintext_input : raw_plaintext_inputs) { 191 | encrypted_inputs.push_back(sk.encrypt(raw_plaintext_input).expand()); 192 | } 193 | 194 | const auto expected_result = PlaintextArray({0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1}); 195 | auto concatenated = concat(encrypted_inputs); 196 | 197 | BOOST_CHECK(sk.decrypt(concatenated) == expected_result.elements()); 198 | } 199 | 200 | BOOST_AUTO_TEST_SUITE_END() -------------------------------------------------------------------------------- /tests/test_homomorphic_operations.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE HomomorphicOperationsModule 3 | #include 4 | #include 5 | 6 | #include "she.hpp" 7 | #include "serialization_formats.hpp" 8 | 9 | using std::vector; 10 | 11 | using she::PrivateKey; 12 | using she::ParameterSet; 13 | using she::CompressedCiphertext; 14 | using she::PlaintextArray; 15 | using she::EncryptedArray; 16 | 17 | using she::sum; 18 | using she::product; 19 | 20 | 21 | BOOST_AUTO_TEST_SUITE(HomomorphicOperationsSuite) 22 | 23 | BOOST_AUTO_TEST_CASE(bitwise_xor) 24 | { 25 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 26 | 27 | struct Input { 28 | vector p1; 29 | vector p2; 30 | vector p1_xor_p2; 31 | }; 32 | 33 | const auto inputs = { 34 | Input{ 35 | {1, 0, 1, 0, 1, 1, 1, 1}, 36 | {1, 0, 1, 0, 1, 1, 1, 1}, 37 | {0, 0, 0, 0, 0, 0, 0, 0} 38 | }, 39 | 40 | Input{ 41 | {1, 0, 1, 0, 1, 0, 1, 0}, 42 | {1, 0, 1, 0, 1, 1, 1, 1}, 43 | {0, 0, 0, 0, 0, 1, 0, 1} 44 | }, 45 | 46 | Input{ 47 | {1, 0, 1, 0, 1, 1, 1, 1}, 48 | {0, 1, 0, 1, 0, 0, 0, 0}, 49 | {1, 1, 1, 1, 1, 1, 1, 1} 50 | }, 51 | }; 52 | 53 | for (const auto & input : inputs) { 54 | 55 | { 56 | const auto c1 = sk.encrypt(input.p1).expand(); 57 | const auto c2 = sk.encrypt(input.p2).expand(); 58 | 59 | const auto c1_xor_c2 = c1 ^ c2; 60 | 61 | BOOST_CHECK_EQUAL(c1_xor_c2.degree(), 1); 62 | BOOST_CHECK(sk.decrypt(c1_xor_c2) == input.p1_xor_p2); 63 | } 64 | 65 | { 66 | const auto c1 = sk.encrypt(input.p1).expand(); 67 | 68 | const auto c1_xor_p2 = c1 ^ PlaintextArray(input.p2); 69 | 70 | BOOST_CHECK_EQUAL(c1_xor_p2.degree(), 1); 71 | BOOST_CHECK(sk.decrypt(c1_xor_p2) == input.p1_xor_p2); 72 | } 73 | 74 | { 75 | const auto c1 = sk.encrypt(input.p1).expand(); 76 | 77 | const auto c1_xor_p2 = PlaintextArray(input.p2) ^ c1; 78 | 79 | BOOST_CHECK_EQUAL(c1_xor_p2.degree(), 1); 80 | BOOST_CHECK(sk.decrypt(c1_xor_p2) == input.p1_xor_p2); 81 | } 82 | 83 | { 84 | const auto c2 = sk.encrypt(input.p2).expand(); 85 | 86 | const auto c2_xor_p1 = c2 ^ PlaintextArray(input.p1); 87 | 88 | BOOST_CHECK_EQUAL(c2_xor_p1.degree(), 1); 89 | BOOST_CHECK(sk.decrypt(c2_xor_p1) == input.p1_xor_p2); 90 | } 91 | 92 | { 93 | const auto c2 = sk.encrypt(input.p2).expand(); 94 | 95 | const auto c2_xor_p1 = PlaintextArray(input.p1) ^ c2; 96 | 97 | BOOST_CHECK_EQUAL(c2_xor_p1.degree(), 1); 98 | BOOST_CHECK(sk.decrypt(c2_xor_p1) == input.p1_xor_p2); 99 | } 100 | 101 | { 102 | const auto p1_xor_p2 = PlaintextArray(input.p1) ^ PlaintextArray(input.p2); 103 | BOOST_CHECK(p1_xor_p2.elements() == input.p1_xor_p2); 104 | } 105 | } 106 | } 107 | 108 | BOOST_AUTO_TEST_CASE(multiple_arrays_sum) 109 | { 110 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 111 | 112 | vector > inputs = { 113 | {1, 1, 1, 1, 0, 0, 1, 1}, 114 | {0, 0, 0, 1, 0, 1, 0, 1}, 115 | {}, 116 | {1, 1, 1, 1, 0, 0}, 117 | {1, 1, 0, 0, 0, 1, 0, 1}, 118 | {1, 0, 0, 0, 0, 1, 1, 0}, 119 | }; 120 | 121 | vector expected_result = 122 | {0, 1, 0, 1, 0, 1, 0, 1}; 123 | 124 | { 125 | vector encrypted_inputs; 126 | for (const auto & input : inputs) { 127 | encrypted_inputs.push_back(sk.encrypt(input).expand()); 128 | } 129 | 130 | const auto result = sum(encrypted_inputs); 131 | const auto decrypted_result = sk.decrypt(result); 132 | 133 | BOOST_CHECK_EQUAL(result.degree(), 1); 134 | BOOST_CHECK(decrypted_result == expected_result); 135 | } 136 | 137 | { 138 | vector plaintext_inputs; 139 | for (const auto & input : inputs) { 140 | plaintext_inputs.push_back(PlaintextArray(input)); 141 | } 142 | 143 | const auto result = sum(plaintext_inputs); 144 | BOOST_CHECK(result.elements() == expected_result); 145 | } 146 | } 147 | 148 | BOOST_AUTO_TEST_CASE(bitwise_and) 149 | { 150 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 151 | 152 | struct Input { 153 | vector p1; 154 | vector p2; 155 | vector p1_and_p2; 156 | }; 157 | 158 | const auto inputs = { 159 | Input{ 160 | {1, 0, 1, 0, 1, 1, 1, 1}, 161 | {1, 0, 1, 0, 1, 1, 1, 1}, 162 | {1, 0, 1, 0, 1, 1, 1, 1} 163 | }, 164 | 165 | Input{ 166 | {1, 0, 1, 0, 1, 0, 1, 0}, 167 | {1, 0, 1, 0, 1, 1, 1, 1}, 168 | {1, 0, 1, 0, 1, 0, 1, 0} 169 | }, 170 | 171 | Input{ 172 | {1, 0, 1, 0, 1, 1, 1, 1}, 173 | {0, 1, 0, 1, 0, 0, 0, 0}, 174 | {0, 0, 0, 0, 0, 0, 0, 0} 175 | }, 176 | }; 177 | 178 | for (const auto & input : inputs) { 179 | 180 | { 181 | const auto c1 = sk.encrypt(input.p1).expand(); 182 | const auto c2 = sk.encrypt(input.p2).expand(); 183 | 184 | const auto c1_and_c2 = c1 & c2; 185 | 186 | BOOST_CHECK_EQUAL(c1_and_c2.degree(), 2); 187 | BOOST_CHECK(sk.decrypt(c1_and_c2) == input.p1_and_p2); 188 | } 189 | 190 | { 191 | const auto c1 = sk.encrypt(input.p1).expand(); 192 | 193 | const auto c1_and_p2 = c1 & PlaintextArray(input.p2); 194 | 195 | BOOST_CHECK_EQUAL(c1_and_p2.degree(), 1); 196 | BOOST_CHECK(sk.decrypt(c1_and_p2) == input.p1_and_p2); 197 | } 198 | 199 | { 200 | const auto c1 = sk.encrypt(input.p1).expand(); 201 | 202 | const auto c1_and_p2 = PlaintextArray(input.p2) & c1; 203 | 204 | BOOST_CHECK_EQUAL(c1_and_p2.degree(), 1); 205 | BOOST_CHECK(sk.decrypt(c1_and_p2) == input.p1_and_p2); 206 | } 207 | 208 | { 209 | const auto c2 = sk.encrypt(input.p2).expand(); 210 | 211 | const auto c2_and_p1 = c2 & PlaintextArray(input.p1); 212 | 213 | BOOST_CHECK_EQUAL(c2_and_p1.degree(), 1); 214 | BOOST_CHECK(sk.decrypt(c2_and_p1) == input.p1_and_p2); 215 | } 216 | 217 | { 218 | const auto c2 = sk.encrypt(input.p2).expand(); 219 | 220 | const auto c2_and_p1 = PlaintextArray(input.p1) & c2; 221 | 222 | BOOST_CHECK_EQUAL(c2_and_p1.degree(), 1); 223 | BOOST_CHECK(sk.decrypt(c2_and_p1) == input.p1_and_p2); 224 | } 225 | 226 | { 227 | const auto p1_and_p2 = PlaintextArray(input.p1) & PlaintextArray(input.p2); 228 | 229 | BOOST_CHECK(p1_and_p2.elements() == input.p1_and_p2); 230 | } 231 | } 232 | } 233 | 234 | BOOST_AUTO_TEST_CASE(multiple_arrays_product) 235 | { 236 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 5, 42)); 237 | 238 | vector > inputs = { 239 | {1, 1, 1, 1, 0, 0, 1, 1}, 240 | {0, 0, 0, 1, 0, 1}, 241 | {1, 1, 1, 1, 0, 0, 0, 1}, 242 | {}, 243 | {1, 1, 0, 1, 0, 1, 0, 1}, 244 | {1, 0, 0, 1, 0, 1, 1, 1}, 245 | }; 246 | 247 | vector expected_result = 248 | {0, 0, 0, 1, 0, 0, 0, 1}; 249 | 250 | { 251 | vector encrypted_inputs; 252 | for (const auto & input : inputs) { 253 | encrypted_inputs.push_back(sk.encrypt(input).expand()); 254 | } 255 | 256 | const auto result = product(encrypted_inputs); 257 | const auto decrypted_result = sk.decrypt(result); 258 | 259 | BOOST_CHECK_EQUAL(result.degree(), inputs.size()); 260 | BOOST_CHECK(decrypted_result == expected_result); 261 | } 262 | 263 | { 264 | vector plaintext_inputs; 265 | for (const auto & input : inputs) { 266 | plaintext_inputs.push_back(PlaintextArray(input)); 267 | } 268 | 269 | const auto result = product(plaintext_inputs); 270 | BOOST_CHECK(result.elements() == expected_result); 271 | } 272 | } 273 | 274 | BOOST_AUTO_TEST_CASE(array_select) 275 | { 276 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 4, 42)); 277 | const vector > raw_plaintext_arrays = { 278 | {1, 1, 1, 1}, 279 | {0, 1, 0, 1}, 280 | {1, 0, 1, 0}, 281 | {0, 0, 0, 0}, 282 | }; 283 | 284 | vector plaintext_arrays; 285 | for (const auto & raw_plaintext_array : raw_plaintext_arrays) { 286 | plaintext_arrays.push_back(PlaintextArray(raw_plaintext_array)); 287 | } 288 | 289 | vector encrypted_arrays; 290 | for (const auto & raw_plaintext_array : raw_plaintext_arrays) { 291 | encrypted_arrays.push_back(sk.encrypt(raw_plaintext_array).expand()); 292 | } 293 | 294 | vector > raw_plaintext_selections = { 295 | {1, 0, 0, 0}, 296 | {0, 1, 0, 0}, 297 | {0, 0, 1, 0}, 298 | {0, 0, 0, 1}, 299 | }; 300 | 301 | vector encrypted_selections; 302 | for (const auto & raw_plaintext_selection : raw_plaintext_selections) { 303 | encrypted_selections.push_back(sk.encrypt(raw_plaintext_selection).expand()); 304 | } 305 | 306 | vector plaintext_selections; 307 | for (const auto & raw_plaintext_selection : raw_plaintext_selections) { 308 | plaintext_selections.push_back(PlaintextArray(raw_plaintext_selection)); 309 | } 310 | 311 | { 312 | for (size_t i = 0; i < encrypted_selections.size(); ++i) { 313 | const auto result = encrypted_selections[i].select(encrypted_arrays); 314 | const vector decrypted_result = sk.decrypt(result); 315 | 316 | BOOST_CHECK_EQUAL(result.degree(), 2); 317 | BOOST_CHECK(decrypted_result == plaintext_arrays[i].elements()); 318 | } 319 | } 320 | 321 | { 322 | for (size_t i = 0; i < encrypted_selections.size(); ++i) { 323 | const auto result = encrypted_selections[i].select(plaintext_arrays); 324 | const vector decrypted_result = sk.decrypt(result); 325 | 326 | BOOST_CHECK_EQUAL(result.degree(), 1); 327 | BOOST_CHECK(decrypted_result == plaintext_arrays[i].elements()); 328 | } 329 | } 330 | 331 | { 332 | for (size_t i = 0; i < plaintext_selections.size(); ++i) { 333 | const auto result = plaintext_selections[i].select(encrypted_arrays); 334 | const vector decrypted_result = sk.decrypt(result); 335 | 336 | BOOST_CHECK_EQUAL(result.degree(), 1); 337 | BOOST_CHECK(decrypted_result == plaintext_arrays[i].elements()); 338 | } 339 | } 340 | 341 | { 342 | for (size_t i = 0; i < plaintext_selections.size(); ++i) { 343 | const auto result = plaintext_selections[i].select(plaintext_arrays); 344 | BOOST_CHECK(result.elements() == plaintext_arrays[i].elements()); 345 | } 346 | } 347 | } 348 | 349 | BOOST_AUTO_TEST_CASE(array_equal) 350 | { 351 | const PrivateKey sk(ParameterSet::generate_parameter_set(22, 4, 42)); 352 | const vector > raw_plaintext_arrays = { 353 | vector{1, 1, 1, 1}, 354 | vector{0, 1, 0, 1}, 355 | vector{1, 0, 1, 0}, 356 | vector{0, 1, 0, 1}, 357 | }; 358 | 359 | vector plaintext_arrays; 360 | for (const auto & raw_plaintext_array : raw_plaintext_arrays) { 361 | plaintext_arrays.push_back(PlaintextArray(raw_plaintext_array)); 362 | } 363 | 364 | vector encrypted_arrays; 365 | for (const auto & raw_plaintext_array : raw_plaintext_arrays) { 366 | encrypted_arrays.push_back(sk.encrypt(raw_plaintext_array).expand()); 367 | } 368 | 369 | const vector > raw_plaintext_inputs = { 370 | vector{1, 1, 0, 0}, 371 | vector{1, 1, 1, 1}, 372 | vector{0, 1, 0, 1}, 373 | vector{1, 0, 1, 0}, 374 | }; 375 | 376 | vector plaintext_inputs; 377 | for (const auto & raw_plaintext_input : raw_plaintext_inputs) { 378 | plaintext_inputs.push_back(PlaintextArray(raw_plaintext_input)); 379 | } 380 | 381 | vector encrypted_inputs; 382 | for (const auto & raw_plaintext_input : raw_plaintext_inputs) { 383 | encrypted_inputs.push_back(sk.encrypt(raw_plaintext_input).expand()); 384 | } 385 | 386 | const vector > expected_results = { 387 | {0, 0, 0, 0}, 388 | {1, 0, 0, 0}, 389 | {0, 1, 0, 1}, 390 | {0, 0, 1, 0} 391 | }; 392 | 393 | { 394 | for (size_t i = 0; i < encrypted_inputs.size(); ++i) { 395 | const auto result = encrypted_inputs[i].equal(encrypted_arrays); 396 | const vector decrypted_result = sk.decrypt(result); 397 | 398 | BOOST_CHECK_EQUAL(result.degree(), 4); 399 | BOOST_CHECK(decrypted_result == expected_results[i]); 400 | } 401 | } 402 | 403 | { 404 | 405 | for (size_t i = 0; i < plaintext_inputs.size(); ++i) { 406 | const auto result = plaintext_inputs[i].equal(encrypted_arrays); 407 | const vector decrypted_result = sk.decrypt(result); 408 | 409 | BOOST_CHECK_EQUAL(result.degree(), 4); 410 | BOOST_CHECK(decrypted_result == expected_results[i]); 411 | } 412 | } 413 | 414 | { 415 | for (size_t i = 0; i < encrypted_inputs.size(); ++i) { 416 | const auto result = encrypted_inputs[i].equal(plaintext_arrays); 417 | const vector decrypted_result = sk.decrypt(result); 418 | 419 | BOOST_CHECK_EQUAL(result.degree(), 1); 420 | BOOST_CHECK(decrypted_result == expected_results[i]); 421 | } 422 | } 423 | 424 | { 425 | for (size_t i = 0; i < plaintext_inputs.size(); ++i) { 426 | const auto result = plaintext_inputs[i].equal(plaintext_arrays); 427 | BOOST_CHECK(result.elements() == expected_results[i]); 428 | } 429 | } 430 | } 431 | 432 | BOOST_AUTO_TEST_SUITE_END() 433 | -------------------------------------------------------------------------------- /src/ciphertext.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "she.hpp" 4 | #include "she/exceptions.hpp" 5 | 6 | using std::min; 7 | using std::max; 8 | using std::set; 9 | using std::vector; 10 | 11 | 12 | namespace she 13 | { 14 | 15 | std::set EncryptedArray::public_elements = {}; 16 | 17 | EncryptedArray::EncryptedArray(const mpz_class & x, unsigned int max_degree, unsigned int degree) noexcept : 18 | _degree(degree), 19 | _max_degree(max_degree) 20 | { 21 | // ASSERT(degree >= 1, "Degree must be at least 1"); 22 | 23 | set_public_element(x); 24 | } 25 | 26 | bool EncryptedArray::operator==(const EncryptedArray & other) const noexcept 27 | { 28 | return (_elements == other._elements) 29 | && (*_public_element_ptr == *other._public_element_ptr); 30 | } 31 | 32 | void EncryptedArray::set_public_element(const mpz_class & x) noexcept 33 | { 34 | auto result = public_elements.emplace(x); 35 | _public_element_ptr = result.first; 36 | _initialized = true; 37 | } 38 | 39 | EncryptedArray & 40 | EncryptedArray::operator^=(const PlaintextArray & other) noexcept 41 | { 42 | ASSERT(_initialized, "EncryptedArray must be initialized"); 43 | 44 | const auto & public_element = *_public_element_ptr; 45 | 46 | const size_t n = min(_elements.size(), other._elements.size()); 47 | 48 | // Do natural arithmetic operation modulo public element 49 | for (size_t i = 0; i < n; ++i) { 50 | _elements[i] += other._elements[i]; 51 | _elements[i] %= public_element; 52 | } 53 | 54 | // If sizes don't match pad with zeros from the right 55 | for (size_t i = n; i < other._elements.size(); ++i) { 56 | _elements.push_back(other._elements[i]); 57 | } 58 | 59 | return *this; 60 | } 61 | 62 | EncryptedArray & 63 | EncryptedArray::operator^=(const EncryptedArray & other) noexcept 64 | { 65 | ASSERT(_initialized, "EncryptedArray must be initialized"); 66 | 67 | const auto & public_element = *_public_element_ptr; 68 | 69 | _degree = max(_degree, other._degree); 70 | 71 | const size_t n = min(_elements.size(), other._elements.size()); 72 | 73 | // Do natural arithmetic operation modulo public element 74 | for (size_t i = 0; i < n; ++i) { 75 | _elements[i] += other._elements[i]; 76 | _elements[i] %= public_element; 77 | } 78 | 79 | // If sizes don't match pad with zeros from the right 80 | for (size_t i = n; i < other._elements.size(); ++i) { 81 | _elements.push_back(other._elements[i]); 82 | } 83 | 84 | return *this; 85 | } 86 | 87 | EncryptedArray & 88 | EncryptedArray::operator&=(const PlaintextArray & other) noexcept 89 | { 90 | ASSERT(_initialized, "EncryptedArray must be initialized"); 91 | 92 | const auto & public_element = *_public_element_ptr; 93 | 94 | const size_t n = min(_elements.size(), other._elements.size()); 95 | 96 | // Do natural arithmetic operation modulo public element 97 | for (size_t i = 0; i < n; ++i) { 98 | _elements[i] *= other._elements[i]; 99 | _elements[i] %= public_element; 100 | } 101 | 102 | // If sizes don't match pad with ones from the right 103 | for (size_t i = n; i < other._elements.size(); ++i) { 104 | _elements.push_back(other._elements[i]); 105 | } 106 | 107 | return *this; 108 | } 109 | 110 | EncryptedArray & 111 | EncryptedArray::operator&=(const EncryptedArray & other) noexcept 112 | { 113 | ASSERT(_initialized, "EncryptedArray must be initialized"); 114 | 115 | const auto & public_element = *_public_element_ptr; 116 | 117 | _degree = _degree + other._degree; 118 | 119 | const size_t n = min(_elements.size(), other._elements.size()); 120 | 121 | // Do natural arithmetic operation modulo public element 122 | for (size_t i = 0; i < n; ++i) { 123 | _elements[i] *= other._elements[i]; 124 | _elements[i] %= public_element; 125 | } 126 | 127 | // If sizes don't match pad with ones from the right 128 | for (size_t i = n; i < other._elements.size(); ++i) { 129 | _elements.push_back(other._elements[i]); 130 | } 131 | 132 | return *this; 133 | } 134 | 135 | 136 | const PlaintextArray 137 | PlaintextArray::equal(const std::vector & arrays) const noexcept 138 | { 139 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 140 | 141 | PlaintextArray result {}; 142 | 143 | for (const auto & array : arrays) { 144 | 145 | // Find difference (xor) between this and array 146 | const auto difference = *this ^ array; 147 | 148 | // Multiply (and) all elements of the difference array + 1 149 | // The result will decrypt to 1 iff all elements of this and array are equal 150 | bool all = 1; 151 | for (const auto & element : difference._elements) 152 | { 153 | all &= (element ^ 1); 154 | } 155 | 156 | result._elements.push_back(all); 157 | } 158 | 159 | return result; 160 | } 161 | 162 | const EncryptedArray 163 | PlaintextArray::equal(const std::vector & arrays) const noexcept 164 | { 165 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 166 | 167 | const auto & public_element = arrays.front().public_element(); 168 | 169 | EncryptedArray result( arrays.front().public_element() 170 | , arrays.front().max_degree() 171 | , arrays.front().degree() 172 | ); 173 | 174 | for (const auto & array : arrays) { 175 | 176 | // Find difference (xor) between this and array 177 | const auto difference = array ^ *this; 178 | 179 | // Multiply (and) all elements of the difference array + 1 180 | // The result will decrypt to 1 iff all elements of this and array are equal 181 | mpz_class all = 1; 182 | for (const auto & element : difference._elements) 183 | { 184 | all *= (element + 1); 185 | all %= public_element; 186 | } 187 | 188 | result._elements.push_back(all); 189 | 190 | // Set result degree to maximum degree of arrays 191 | auto current_degree = difference._degree * difference._elements.size(); 192 | if (current_degree > result._degree) { 193 | result._degree = current_degree; 194 | } 195 | } 196 | 197 | return result; 198 | } 199 | 200 | const EncryptedArray 201 | EncryptedArray::equal(const std::vector & arrays) const noexcept 202 | { 203 | ASSERT(_initialized, "EncryptedArray must be initialized"); 204 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 205 | 206 | const auto & public_element = *_public_element_ptr; 207 | 208 | EncryptedArray result(public_element, _max_degree, _degree); 209 | 210 | for (const auto & array : arrays) { 211 | 212 | // Find difference (xor) between this and array 213 | const auto difference = *this ^ array; 214 | 215 | // Multiply (and) all elements of the difference array + 1 216 | // The result will decrypt to 1 iff all elements of this and array are equal 217 | mpz_class all = 1; 218 | for (const auto & element : difference._elements) 219 | { 220 | all *= (element + 1); 221 | all %= public_element; 222 | } 223 | 224 | result._elements.push_back(all); 225 | } 226 | 227 | return result; 228 | } 229 | 230 | 231 | const EncryptedArray 232 | EncryptedArray::equal(const std::vector & arrays) const noexcept 233 | { 234 | ASSERT(_initialized, "EncryptedArray must be initialized"); 235 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 236 | 237 | const auto & public_element = *_public_element_ptr; 238 | 239 | EncryptedArray result(public_element, _max_degree); 240 | 241 | for (const auto & array : arrays) { 242 | 243 | // Find difference (xor) between this and array 244 | const auto difference = *this ^ array; 245 | 246 | // Multiply (and) all elements of the difference array + 1 247 | // The result will decrypt to 1 iff all elements of this and array are equal 248 | mpz_class all = 1; 249 | for (const auto & element : difference._elements) 250 | { 251 | all *= (element + 1); 252 | all %= public_element; 253 | } 254 | 255 | result._elements.push_back(all); 256 | 257 | // Set result degree to maximum degree of arrays 258 | auto current_degree = difference._degree * difference._elements.size(); 259 | if (current_degree > result._degree) { 260 | result._degree = current_degree; 261 | } 262 | } 263 | 264 | return result; 265 | } 266 | 267 | const PlaintextArray 268 | PlaintextArray::select(const std::vector & arrays) const noexcept 269 | { 270 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 271 | 272 | PlaintextArray result {}; 273 | 274 | for (size_t i = 0; i < min(_elements.size(), arrays.size()); ++i) { 275 | 276 | PlaintextArray selected {}; 277 | 278 | // Multiply i-th element of this by all of the elements in array 279 | // The result will be decrypted to either original array or to array of zeros 280 | for (const auto & selected_element : arrays[i]._elements) { 281 | selected._elements.push_back(selected_element & _elements[i]); 282 | } 283 | 284 | result ^= selected; 285 | } 286 | 287 | return result; 288 | } 289 | 290 | const EncryptedArray 291 | PlaintextArray::select(const std::vector & arrays) const noexcept 292 | { 293 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 294 | 295 | const auto & public_element = arrays.front().public_element(); 296 | 297 | EncryptedArray result( arrays.front().public_element() 298 | , arrays.front().max_degree() 299 | , arrays.front().degree() 300 | ); 301 | 302 | for (size_t i = 0; i < min(_elements.size(), arrays.size()); ++i) { 303 | 304 | EncryptedArray selected(public_element, result._max_degree, arrays[i]._degree); 305 | 306 | // Multiply i-th element of this by all of the elements in array 307 | // The result will be decrypted to either original array or to array of zeros 308 | for (const auto & selected_element : arrays[i]._elements) { 309 | selected._elements.push_back((selected_element * _elements[i]) % public_element); 310 | } 311 | 312 | result ^= selected; 313 | } 314 | 315 | return result; 316 | } 317 | 318 | const EncryptedArray 319 | EncryptedArray::select(const std::vector & arrays) const noexcept 320 | { 321 | ASSERT(_initialized, "EncryptedArray must be initialized"); 322 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 323 | 324 | const auto & public_element = *_public_element_ptr; 325 | 326 | EncryptedArray result(public_element, _max_degree, _degree); 327 | 328 | for (size_t i = 0; i < min(_elements.size(), arrays.size()); ++i) { 329 | 330 | EncryptedArray selected(public_element, _max_degree, _degree); 331 | 332 | // Multiply i-th element of this by all of the elements in array 333 | // The result will be decrypted to either original array or to array of zeros 334 | for (const auto & selected_element : arrays[i]._elements) { 335 | selected._elements.push_back(selected_element * _elements[i]); 336 | } 337 | 338 | result ^= selected; 339 | } 340 | 341 | return result; 342 | } 343 | 344 | const EncryptedArray 345 | EncryptedArray::select(const std::vector & arrays) const noexcept 346 | { 347 | ASSERT(_initialized, "EncryptedArray must be initialized"); 348 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 349 | 350 | const auto & public_element = *_public_element_ptr; 351 | 352 | EncryptedArray result(public_element, _max_degree); 353 | 354 | for (size_t i = 0; i < min(_elements.size(), arrays.size()); ++i) { 355 | 356 | EncryptedArray selected(public_element, _max_degree); 357 | 358 | // Multiply i-th element of this by all of the elements in array 359 | // The result will be decrypted to either original array or to array of zeros 360 | for (const auto & selected_element : arrays[i]._elements) { 361 | selected._elements.push_back((selected_element * _elements[i]) % public_element); 362 | } 363 | 364 | selected._degree = _degree + arrays[i]._degree; 365 | 366 | result ^= selected; 367 | } 368 | 369 | return result; 370 | } 371 | 372 | EncryptedArray & 373 | EncryptedArray::extend(const EncryptedArray & other) noexcept 374 | { 375 | ASSERT(_initialized, "EncryptedArray must be initialized"); 376 | 377 | for (const auto & element : other._elements) { 378 | _elements.push_back(element); 379 | } 380 | 381 | _degree = max(_degree, other._degree); 382 | 383 | return *this; 384 | } 385 | 386 | const mpz_class & 387 | EncryptedArray::public_element() const noexcept 388 | { 389 | ASSERT(_initialized, "EncryptedArray must be initialized"); 390 | 391 | return *_public_element_ptr; 392 | } 393 | 394 | PlaintextArray 395 | sum(const vector & arrays) noexcept 396 | { 397 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 398 | 399 | PlaintextArray result {}; 400 | 401 | for (const auto & array : arrays) { 402 | result ^= array; 403 | } 404 | 405 | return result; 406 | } 407 | 408 | EncryptedArray 409 | sum(const vector & arrays) noexcept 410 | { 411 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 412 | 413 | EncryptedArray result( arrays.front().public_element() 414 | , arrays.front().max_degree() 415 | , arrays.front().degree() 416 | ); 417 | 418 | for (const auto & array : arrays) { 419 | result ^= array; 420 | } 421 | 422 | return result; 423 | } 424 | 425 | PlaintextArray 426 | product(const vector & arrays) noexcept 427 | { 428 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 429 | 430 | PlaintextArray result {}; 431 | 432 | for (const auto & array : arrays) { 433 | result &= array; 434 | } 435 | 436 | return result; 437 | } 438 | 439 | EncryptedArray 440 | product(const vector & arrays) noexcept 441 | { 442 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 443 | 444 | EncryptedArray result( arrays.front().public_element() 445 | , arrays.front().max_degree() 446 | , 0); 447 | 448 | for (const auto & array : arrays) { 449 | result &= array; 450 | } 451 | 452 | return result; 453 | } 454 | 455 | PlaintextArray 456 | concat(const vector & arrays) noexcept 457 | { 458 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 459 | 460 | PlaintextArray result {}; 461 | 462 | for (const auto & array : arrays) { 463 | result.extend(array); 464 | } 465 | 466 | return result; 467 | } 468 | 469 | EncryptedArray 470 | concat(const vector & arrays) noexcept 471 | { 472 | ASSERT(arrays.size() > 0, "Input array must not be empty"); 473 | 474 | EncryptedArray result( arrays.front().public_element() 475 | , arrays.front().max_degree() 476 | , arrays.front().degree() 477 | ); 478 | 479 | for (const auto & array : arrays) { 480 | result.extend(array); 481 | } 482 | 483 | return result; 484 | } 485 | 486 | CompressedCiphertext::CompressedCiphertext(const ParameterSet & params) noexcept : 487 | _parameter_set(params) 488 | { 489 | initialize_prf_stream(); 490 | } 491 | 492 | void CompressedCiphertext::initialize_prf_stream() const noexcept 493 | { 494 | _prf_stream.reset( 495 | new PseudoRandomStream{_parameter_set.ciphertext_size_bits, _parameter_set.prf_seed}); 496 | } 497 | 498 | bool CompressedCiphertext::operator==(const CompressedCiphertext & other) const noexcept 499 | { 500 | return (_parameter_set == other._parameter_set) 501 | && (_public_element_delta == other._public_element_delta) 502 | && (_elements_deltas == other._elements_deltas); 503 | } 504 | 505 | EncryptedArray CompressedCiphertext::expand() const noexcept 506 | { 507 | _prf_stream->reset(); 508 | 509 | // Restore public element 510 | const auto & prf_output = _prf_stream->next(); 511 | const auto public_element = prf_output - _public_element_delta; 512 | 513 | EncryptedArray result(public_element, _parameter_set.degree()); 514 | 515 | // Restore ciphertext elements 516 | for (const auto & delta : _elements_deltas) { 517 | const auto & prf_output = _prf_stream->next(); 518 | result._elements.push_back(prf_output - delta); 519 | } 520 | 521 | return result; 522 | } 523 | 524 | } // namespace she 525 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | libshe Copyright (C) 2015 Bogdan Kulynych 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------