├── .gitignore
├── INSTALL.sh
├── LICENSE
├── Makefile
├── README.md
├── cdbclient.sh
├── cdbserver.sh
├── crypto
├── BasicCrypto.cc
├── BasicCrypto.hh
├── ECJoin.cc
├── ECJoin.hh
├── Makefrag
├── SWPSearch.cc
├── SWPSearch.hh
├── aes.hh
├── all
├── arc4.cc
├── arc4.hh
├── blowfish.hh
├── bn.hh
├── cbc.hh
├── cbcmac.hh
├── cmc.hh
├── dj.hh
├── ec.hh
├── ecjoin.cc
├── ecjoin.hh
├── ffx.cc
├── ffx.hh
├── gfe.hh
├── hgd.cc
├── hgd.hh
├── hmac.hh
├── mont.cc
├── mont.hh
├── online_ope.cc
├── online_ope.hh
├── ope-exp.cc
├── ope.cc
├── ope.hh
├── padding.hh
├── paillier.cc
├── paillier.hh
├── pbkdf2.cc
├── pbkdf2.hh
├── prng.cc
├── prng.hh
├── search.cc
├── search.hh
├── sha.hh
├── skip32.cc
├── skip32.hh
└── urandom.cc
├── debug
├── Makefrag
├── hello.cc
├── local_client.cc
├── test_createHandler.cc
├── test_insertHandler.cc
├── test_load_schema.cc
└── test_proxy.cc
├── insert.sh
├── main
├── Analysis.cc
├── Analysis.hh
├── Connect.cc
├── Connect.hh
├── CryptoHandlers.cc
├── CryptoHandlers.hh
├── Makefrag
├── Translator.cc
├── Translator.hh
├── alter_sub_handler.cc
├── alter_sub_handler.hh
├── big_proxy.cc
├── big_proxy.hh
├── cdb_test.cc
├── change_test.cc
├── dbobject.hh
├── ddl_handler.cc
├── ddl_handler.hh
├── dispatcher.cc
├── dispatcher.hh
├── dml_handler.cc
├── dml_handler.hh
├── error.cc
├── error.hh
├── load_and_store.cc
├── macro_util.hh
├── metadata_tables.cc
├── metadata_tables.hh
├── rewrite_const.cc
├── rewrite_ds.cc
├── rewrite_ds.hh
├── rewrite_field.cc
├── rewrite_func.cc
├── rewrite_main.cc
├── rewrite_main.hh
├── rewrite_sum.cc
├── rewrite_util.cc
├── rewrite_util.hh
├── schema.cc
├── schema.hh
├── serializers.hh
├── sql_handler.cc
├── sql_handler.hh
├── stored_procedures.cc
├── stored_procedures.hh
├── test_layer.cc
├── test_proxy.cc
└── test_schema.cc
├── mbk.cc
├── mergedep.pl
├── metadata.data
├── mysql-proxy.cnf
├── mysqlproxy
├── ConnectWrapper.cc
└── Makefrag
├── packages
├── bison_2.7.1.dfsg-1_amd64.deb
├── libbison-dev_2.7.1.dfsg-1_amd64.deb
├── mysql-proxy-0.8.5.tar.gz
├── mysql-src.tar.gz
└── tls
│ ├── buildtags.sh
│ ├── essential.sh
│ ├── gdbs
│ ├── int.sh
│ ├── intnormal.sh
│ ├── myback
│ ├── mydumper
│ ├── .bzrignore
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ │ ├── 3.5.1
│ │ │ ├── CMakeCCompiler.cmake
│ │ │ ├── CMakeCXXCompiler.cmake
│ │ │ ├── CMakeDetermineCompilerABI_C.bin
│ │ │ ├── CMakeDetermineCompilerABI_CXX.bin
│ │ │ ├── CMakeSystem.cmake
│ │ │ ├── CompilerIdC
│ │ │ │ ├── CMakeCCompilerId.c
│ │ │ │ └── a.out
│ │ │ └── CompilerIdCXX
│ │ │ │ ├── CMakeCXXCompilerId.cpp
│ │ │ │ └── a.out
│ │ ├── CMakeDirectoryInformation.cmake
│ │ ├── CMakeOutput.log
│ │ ├── CMakeRuleHashes.txt
│ │ ├── Makefile.cmake
│ │ ├── Makefile2
│ │ ├── TargetDirectories.txt
│ │ ├── cmake.check_cache
│ │ ├── dist.dir
│ │ │ ├── DependInfo.cmake
│ │ │ ├── build.make
│ │ │ ├── cmake_clean.cmake
│ │ │ └── progress.make
│ │ ├── feature_tests.bin
│ │ ├── feature_tests.c
│ │ ├── feature_tests.cxx
│ │ ├── mydumper.dir
│ │ │ ├── C.includecache
│ │ │ ├── DependInfo.cmake
│ │ │ ├── build.make
│ │ │ ├── cmake_clean.cmake
│ │ │ ├── depend.internal
│ │ │ ├── depend.make
│ │ │ ├── flags.make
│ │ │ ├── link.txt
│ │ │ └── progress.make
│ │ ├── myloader.dir
│ │ │ ├── C.includecache
│ │ │ ├── DependInfo.cmake
│ │ │ ├── build.make
│ │ │ ├── cmake_clean.cmake
│ │ │ ├── depend.internal
│ │ │ ├── depend.make
│ │ │ ├── flags.make
│ │ │ ├── link.txt
│ │ │ └── progress.make
│ │ └── progress.marks
│ ├── CMakeLists.txt
│ ├── Makefile
│ ├── README
│ ├── binlog.c
│ ├── binlog.h
│ ├── cmake
│ │ └── modules
│ │ │ ├── CppcheckTargets.cmake
│ │ │ ├── FindGLIB2.cmake
│ │ │ ├── FindMySQL.cmake
│ │ │ ├── FindPCRE.cmake
│ │ │ ├── FindSphinx.cmake
│ │ │ ├── Findcppcheck.cmake
│ │ │ └── Findcppcheck.cpp
│ ├── cmake_install.cmake
│ ├── common.h
│ ├── config.h
│ ├── config.h.in
│ ├── dest
│ │ ├── metadata
│ │ ├── tdb3-schema-create.sql
│ │ ├── tdb3.student-schema.sql
│ │ └── tdb3.student.sql
│ ├── docs
│ │ ├── CMakeFiles
│ │ │ ├── CMakeDirectoryInformation.cmake
│ │ │ └── progress.marks
│ │ ├── CMakeLists.txt
│ │ ├── Makefile
│ │ ├── _build
│ │ │ ├── conf.py.in
│ │ │ └── sources.cmake.in
│ │ ├── authors.rst
│ │ ├── cmake_install.cmake
│ │ ├── compiling.rst
│ │ ├── examples.rst
│ │ ├── files.rst
│ │ ├── index.rst
│ │ ├── mydumper_usage.rst
│ │ └── myloader_usage.rst
│ ├── g_unix_signal.c
│ ├── g_unix_signal.h
│ ├── mydumper
│ ├── mydumper.c
│ ├── mydumper.h
│ ├── myloader
│ ├── myloader.c
│ ├── myloader.h
│ ├── server_detect.c
│ └── server_detect.h
│ ├── mysqlWrapper
│ ├── Makefile
│ ├── analysis.cc
│ ├── backFieldsToFiles.cc
│ ├── createSelect.cc
│ ├── inmain
│ ├── main.cc
│ └── mysqllib
│ │ ├── MyConnect.cc
│ │ ├── MyConnect.h
│ │ ├── utilities.cc
│ │ └── utilities.h
│ ├── shell
│ ├── a
│ ├── count.sh
│ └── insert.sh
│ ├── stopgdbs
│ ├── str.sh
│ ├── strnormal.sh
│ └── tpcc-mysql
│ ├── Dockerfile
│ ├── README.md
│ ├── a
│ ├── add_fkey_idx.sql
│ ├── count.sql
│ ├── create_table.sql
│ ├── cryptbenchmark.sh
│ ├── drop_cons.sql
│ ├── load.sh
│ ├── load_multi_schema.sh
│ ├── normalbenchmark.sh
│ ├── schema2
│ ├── add_fkey_idx.sql
│ ├── count.sql
│ ├── create_table.sql
│ └── drop_cons.sql
│ ├── scripts
│ ├── 2instances
│ │ └── run.sh
│ ├── analyze.full.sh
│ ├── analyze.sh
│ ├── analyzeR.sh
│ ├── analyze_checkpoint.sh
│ ├── analyze_checkpoint_xtradb.sh
│ ├── analyze_checkpoint_xtradb1.sh
│ ├── analyze_dirty.sh
│ ├── analyze_evicted.sh
│ ├── analyze_flushed.sh
│ ├── analyze_flushed_innodb.sh
│ ├── analyze_min.sh
│ ├── analyze_modified.sh
│ ├── flashcache_stat.sh
│ ├── innodb_stat.sh
│ ├── memlock
│ ├── memlock.c
│ ├── multi-instances
│ │ └── runX.sh
│ ├── parse_trx.py
│ ├── remote
│ │ └── runX.sh
│ ├── run.sh
│ ├── runX.sh
│ ├── run_no_backup.sh
│ └── virident_stat.sh
│ ├── src
│ ├── Makefile
│ ├── delivery.c
│ ├── delivery.o
│ ├── driver.c
│ ├── driver.o
│ ├── load.c
│ ├── load.o
│ ├── main.c
│ ├── main.o
│ ├── neword.c
│ ├── neword.o
│ ├── ordstat.c
│ ├── ordstat.o
│ ├── parse_port.h
│ ├── payment.c
│ ├── payment.o
│ ├── rthist.c
│ ├── rthist.h
│ ├── rthist.o
│ ├── sb_percentile.c
│ ├── sb_percentile.h
│ ├── sb_percentile.o
│ ├── sequence.c
│ ├── sequence.h
│ ├── sequence.o
│ ├── slev.c
│ ├── slev.o
│ ├── spt_proc.c
│ ├── spt_proc.h
│ ├── spt_proc.o
│ ├── support.c
│ ├── support.o
│ ├── tpc.h
│ └── trans_if.h
│ ├── tpcc_load
│ └── tpcc_start
├── parser
├── Makefrag
├── README
├── embedmysql.cc
├── embedmysql.hh
├── lex_util.cc
├── lex_util.hh
├── mysql_type_metadata.cc
├── mysql_type_metadata.hh
├── mysqld-filler.cc
├── sql_utils.cc
├── sql_utils.hh
└── stringify.hh
├── reset.sh
├── results
├── setup.sh
├── tutorial-basic.lua
├── udf
├── Makefrag
├── create.sql
└── edb.cc
├── util
├── Makefrag
├── cleanup.hh
├── coroutine.hpp
├── cryptdb_log.cc
├── cryptdb_log.hh
├── ctr.cc
├── ctr.hh
├── enum_text.hh
├── errstream.hh
├── hello.cc
├── onions.cc
├── onions.hh
├── params.hh
├── rob.hh
├── scoped_lock.hh
├── scopedperf.hh
├── timer.hh
├── unyield.hpp
├── util.cc
├── util.hh
├── version.hh
├── yield.hpp
└── zz.hh
├── verify.sh
└── wrapper.lua
/.gitignore:
--------------------------------------------------------------------------------
1 | mysql-src/
2 | normal.sh
3 | obj/
4 | tags
5 | shadow/
6 | core
7 | curMysql
8 | reset.sql
9 | test
10 | cscope.files
11 | cscope.out
12 | cscope.files
13 | cscope.out
14 | tags
15 | readFile
16 | writeFile
17 | *CMakeFiles*
18 | *all*
19 | *back1.sql
20 | *back.sql
21 | *load.sql
22 | data
23 | mtl
24 |
--------------------------------------------------------------------------------
/INSTALL.sh:
--------------------------------------------------------------------------------
1 | sudo apt update -y
2 | sudo apt remove bison libbison-dev -y
3 | sudo apt upgrade -y
4 | sudo apt install g++-4.7 gawk liblua5.1-0-dev libntl-dev libmysqlclient-dev libssl-dev libbsd-dev libevent-dev libglib2.0-dev libgmp-dev mysql-server libaio-dev automake gtk-doc-tools flex cmake libncurses5-dev make ruby lua5.1 libmysqld-dev exuberant-ctags cscope -y
5 | cd packages;sudo dpkg -i libbison-dev_2.7.1.dfsg-1_amd64.deb;sudo dpkg -i bison_2.7.1.dfsg-1_amd64.deb;cd ..
6 |
7 |
8 | echo =============COMPILE MYSQL================================
9 |
10 | rm -rf mysql-src
11 | tar -xvf packages/mysql-src.tar.gz
12 | export CXX=g++-4.7
13 | cd mysql-src;mkdir build;cd build;cmake -DWITH_EMBEDDED_SERVER=on -DENABLE_DTRACE=off .. ; make;cd ../..;
14 |
15 | echo ===============OK========================================
16 |
17 |
18 | echo =============INSTALL MYSQL-proxy=========================
19 |
20 | tar -xvf packages/mysql-proxy-0.8.5.tar.gz -C mysql-src/
21 |
22 | binpath=`pwd`/mysql-src/mysql-proxy-0.8.5/bin
23 |
24 | echo " " >> ~/.bashrc
25 | echo PATH='$'PATH:${binpath} >> ~/.bashrc
26 | source ~/.bashrc
27 |
28 | echo =============INSTALL Cryptdb=============================
29 |
30 | make
31 | sudo make install
32 | chmod 0660 mysql-proxy.cnf
33 |
34 | echo ============Enjoy it!!!=====================================
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The source code for CryptDB is licensed under the terms of the GPL v3
2 | license, unless otherwise noted (such as in the case of third-party
3 | components and libraries):
4 |
5 | CryptDB is free software: you can redistribute it and/or modify it
6 | under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | CryptDB is distributed in the hope that it will be useful, but
11 | WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | A copy of the GNU General Public License is included with CryptDB,
16 | under doc/gpl-3.txt. Alternatively, see .
17 |
18 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | MYSRC := $(shell pwd)/mysql-src
2 | MYBUILD := $(MYSRC)/build
3 | RPATH := 1
4 |
5 | CXX := g++-4.7
6 | MYSQL_PLUGIN_DIR := /usr/lib/mysql/plugin
7 |
8 |
9 | OBJDIR := obj
10 | TOP := $(shell echo $${PWD-`pwd`})
11 | #CXX := g++
12 | AR := ar
13 | ## -g -O0 -> -O2
14 | CXXFLAGS := -g -O0 -fno-strict-aliasing -fno-rtti -fwrapv -fPIC \
15 | -Wall -Werror -Wpointer-arith -Wendif-labels -Wformat=2 \
16 | -Wextra -Wmissing-noreturn -Wwrite-strings -Wno-unused-parameter \
17 | -Wno-deprecated \
18 | -Wmissing-declarations -Woverloaded-virtual \
19 | -Wunreachable-code -D_GNU_SOURCE -std=c++0x -I$(TOP)
20 | LDFLAGS := -L$(TOP)/$(OBJDIR) -Wl,--no-undefined
21 |
22 |
23 | ## Use RPATH only for debug builds; set RPATH=1 in config.mk.
24 | ifeq ($(RPATH),1)
25 | LDRPATH := -Wl,-rpath=$(TOP)/$(OBJDIR) -Wl,-rpath=$(TOP)
26 | endif
27 |
28 | CXXFLAGS += -I$(MYBUILD)/include \
29 | -I$(MYSRC)/include \
30 | -I$(MYSRC)/sql \
31 | -I$(MYSRC)/regex \
32 | -I$(MYBUILD)/sql \
33 | -DHAVE_CONFIG_H -DMYSQL_SERVER -DEMBEDDED_LIBRARY -DDBUG_OFF \
34 | -DMYSQL_BUILD_DIR=\"$(MYBUILD)\"
35 | LDFLAGS += -lpthread -lrt -ldl -lcrypt -lreadline
36 |
37 | ## To be populated by Makefrag files
38 |
39 | OBJDIRS :=
40 |
41 | .PHONY: all
42 | all:
43 |
44 | .PHONY: install
45 | install:
46 |
47 | .PHONY: clean
48 | clean:
49 | rm -rf $(OBJDIR) mtl
50 |
51 | .PHONY: doc
52 | doc:
53 | doxygen CryptDBdoxgen
54 |
55 | .PHONY: whitespace
56 | whitespace:
57 | find . -name '*.cc' -o -name '*.hh' -type f -exec sed -i 's/ *$//' '{}' ';'
58 |
59 | .PHONY: always
60 | always:
61 |
62 | # Eliminate default suffix rules
63 | .SUFFIXES:
64 |
65 | # Delete target files if there is an error (or make is interrupted)
66 | .DELETE_ON_ERROR:
67 |
68 | # make it so that no intermediate .o files are ever deleted
69 | .PRECIOUS: %.o
70 |
71 | $(OBJDIR)/%.o: %.cc
72 | @mkdir -p $(@D)
73 | $(CXX) -MD $(CXXFLAGS) -c $< -o $@
74 |
75 | $(OBJDIR)/%.o: $(OBJDIR)/%.cc
76 | @mkdir -p $(@D)
77 | $(CXX) -MD $(CXXFLAGS) -c $< -o $@
78 |
79 | mtl/%:$(OBJDIR)/debug/%.o
80 | @mkdir -p $(@D)
81 | $(CXX) -g -o $@ $^ $(CXXFLAGS) $(LDFLAGS) -L/$(MYBUILD)/libmysqld -lmysqld -laio -lz -ldl -lm -lcrypt -lpthread -lcryptdb -ledbcrypto -ledbutil -ledbparser -lntl -lcrypto
82 |
83 |
84 |
85 |
86 | include crypto/Makefrag
87 | include parser/Makefrag
88 | include main/Makefrag
89 | include util/Makefrag
90 | include udf/Makefrag
91 | include mysqlproxy/Makefrag
92 | include debug/Makefrag
93 |
94 |
95 | $(OBJDIR)/.deps: $(foreach dir, $(OBJDIRS), $(wildcard $(OBJDIR)/$(dir)/*.d))
96 | @mkdir -p $(@D)
97 | perl mergedep.pl $@ $^
98 | echo "after merge"
99 | -include $(OBJDIR)/.deps
100 |
101 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Make cryptdb Practical
2 |
3 | Cryptdb originated from MIT. This is a modified version. In this project, we try to add new features, fix bugs we meet in our environment, and rewrite the code and comments to make the source code easy to understand. Introduction to the features will be posted at yiwenshao.github.io. Also, analysis of the source code will be posted there so that you do not need so much effort contributing to this project.
4 |
5 | To deploy this version, you need follow the following steps.
6 |
7 | + have ubuntu 16.04 installed
8 | + install mysql-server 5.5 or higher, with the root password 'letmein'
9 | To verify this, you can use the command mysql -uroot -pletmein to log in
10 | + ./INSTALL.sh
11 | + source ~/.bashrc
12 | + source setup.sh
13 | + run ./cdbserver.sh
14 | + run ./cdbclient.sh
15 | + enjoy it!
16 |
17 |
18 |
19 | If you meet any problems installing it, or if you meet bugs or need new features that if not yet supported, post issues or contact me via shaoyiwenetATgmailDotcom.
20 |
21 |
22 |
23 | New features added
24 |
25 | + foreign key constraint
26 |
27 | ```
28 | create table student (id integer primary key);
29 | create table choose (sid integer, foreign key fk(sid) references student(id));
30 | insert into student values(1);
31 | insert into choose values(1);
32 |
33 | ```
34 |
35 | + set user variable
36 | + timestamp
37 | + show create table
38 | + cdb_test for simple curd
39 |
40 | obselete functions deleted
41 |
42 | + annotation
43 | + dbobject.tt
44 |
45 | ### features to be added
46 |
47 | + extended-insert
48 | + QUOTE
49 | + Search
50 |
--------------------------------------------------------------------------------
/cdbclient.sh:
--------------------------------------------------------------------------------
1 | `pwd`/mysql-src/build/client/mysql -uroot -pletmein -h 127.0.0.1 -P3399
2 |
--------------------------------------------------------------------------------
/cdbserver.sh:
--------------------------------------------------------------------------------
1 | mkdir shadow
2 | mysql-proxy --defaults-file=./mysql-proxy.cnf --proxy-lua-script=`pwd`/wrapper.lua
3 |
4 |
--------------------------------------------------------------------------------
/crypto/ECJoin.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | /*
4 | * ECJoin.h
5 | *
6 | * Implements CryptDB's adjustable join encryption scheme.
7 | * It is based on the elliptic-curve DDH assumption.
8 | *
9 | * Currently, it is using the NIST curve denoted NID_X9_62_prime192v1 believed to satisfy ECDDH
10 | * To use a different NIST curve, simply modify the NID field below.
11 | *
12 | *
13 | * Public parameters:
14 | * G: elliptic curve group of prime order
15 | * P: a random point on the elliptic curve
16 | * order: the order of G
17 | *
18 | * To encrypt v, we compute E_k[v] := PRF_k(v) * k * P \in G, where
19 | * k: secret key
20 | *
21 | * To adjust encryption of v under k1, to encryption under k2, we perform:
22 | * \delta k = k2 * k1^{-1} mod order
23 | * E_k2[v] = E_k1[v]*\delta k \in G
24 | *
25 | * TODO: may speed up by:
26 | * - passing BN_CTX * to some functions (and CTX for point, group, if any)
27 | * - using ssl's preprocessing functions
28 | * - use NIST curves with less bits representation, e.g., NID_secp160r1; there are even shorter
29 | */
30 |
31 | #include
32 | #include
33 | #include
34 |
35 | #include
36 |
37 |
38 | struct ECJoinSK{
39 | const AES_KEY * aesKey;
40 | BIGNUM * k; //secret key
41 | EC_POINT * kP;
42 | };
43 |
44 | struct ECDeltaSK {
45 | BIGNUM * deltaK;
46 | EC_GROUP * group;
47 | BIGNUM * ZeroBN;
48 | };
49 |
50 | class ECJoin
51 | {
52 | public:
53 | //setups the elliptic curve and systems parameters
54 | ECJoin();
55 |
56 | ECJoinSK * getSKey(const AES_KEY * baseKey, const std::string & columnKey);
57 |
58 | //returns secret key needed to adjust from encryption with key 1 to encryption with key 2
59 | ECDeltaSK * getDeltaKey(const ECJoinSK * key1, const ECJoinSK * key2);
60 |
61 | std::string encrypt(const ECJoinSK * sk, const std::string & ptext);
62 | static std::string adjust(const ECDeltaSK * deltaSK, const std::string & ctext);
63 |
64 | virtual
65 | ~ECJoin();
66 |
67 | private:
68 | //setup parameters
69 | EC_GROUP * group;
70 | EC_POINT * P;
71 |
72 |
73 | //helper parameters
74 | BIGNUM * order; //order of the group
75 | EC_POINT * Infty;
76 | BIGNUM * ZeroBN;
77 | BN_CTX * bn_ctx;
78 |
79 |
80 | //using curve of 160 bits prime field \n";
81 | static const int NID = NID_X9_62_prime192v1;
82 | static const unsigned int bytesLong = 24;
83 | static const unsigned int MAX_BUF = 256;
84 |
85 | /*** Helper Functions ***/
86 |
87 | //returns a random point on the EC
88 | EC_POINT * randomPoint();
89 | // a PRF with 128 bits security, but bytesLong output
90 | static std::string PRFForEC(const AES_KEY * sk, const std::string & ptext);
91 | static std::string point2Str(const EC_GROUP * group, const EC_POINT * point);
92 | };
93 |
--------------------------------------------------------------------------------
/crypto/Makefrag:
--------------------------------------------------------------------------------
1 | OBJDIRS += crypto
2 | CRYPTOSRC := BasicCrypto.cc paillier.cc urandom.cc arc4.cc hgd.cc pbkdf2.cc \
3 | ecjoin.cc ECJoin.cc search.cc skip32.cc ffx.cc online_ope.cc mont.cc \
4 | prng.cc ope.cc SWPSearch.cc
5 | CRYPTOOBJ := $(patsubst %.cc,$(OBJDIR)/crypto/%.o,$(CRYPTOSRC))
6 |
7 | all: $(OBJDIR)/libedbcrypto.a $(OBJDIR)/libedbcrypto.so
8 |
9 | $(OBJDIR)/libedbcrypto.so: $(CRYPTOOBJ) $(OBJDIR)/libedbutil.so
10 | $(CXX) -fPIC -shared -o $@ $(CRYPTOOBJ) $(LDFLAGS) $(LDRPATH) \
11 | -ledbutil -lcrypto -lntl
12 |
13 | $(OBJDIR)/libedbcrypto.a: $(CRYPTOOBJ)
14 | $(AR) r $@ $(CRYPTOOBJ)
15 |
16 | #all: $(OBJDIR)/crypto/x
17 | $(OBJDIR)/crypto/x: $(OBJDIR)/crypto/x.o $(OBJDIR)/libedbcrypto.so
18 | $(CXX) $< -o $@ $(LDFLAGS) $(LDRPATH) -ledbcrypto
19 |
20 | #install: install_crypto
21 |
22 | #.PHONY: install_crypto
23 | #install_crypto: $(OBJDIR)/libedbcrypto.so
24 | # install -m 644 $(OBJDIR)/libedbcrypto.so /usr/lib
25 |
26 | # vim: set noexpandtab:
27 |
--------------------------------------------------------------------------------
/crypto/aes.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 | class AES {
11 | public:
12 | AES(const std::string &key) {
13 | throw_c(key.size() == 16 || key.size() == 24 || key.size() == 32);
14 | AES_set_encrypt_key((const uint8_t*) key.data(), key.size() * 8, &enc);
15 | AES_set_decrypt_key((const uint8_t*) key.data(), key.size() * 8, &dec);
16 | }
17 |
18 | void block_encrypt(const void *ptext, void *ctext) const {
19 | AES_encrypt((const uint8_t*) ptext, (uint8_t*) ctext, &enc);
20 | }
21 |
22 | void block_decrypt(const void *ctext, void *ptext) const {
23 | AES_decrypt((const uint8_t*) ctext, (uint8_t*) ptext, &dec);
24 | }
25 |
26 | static const size_t blocksize = 16;
27 |
28 | private:
29 | AES_KEY enc;
30 | AES_KEY dec;
31 | };
32 |
33 |
--------------------------------------------------------------------------------
/crypto/all:
--------------------------------------------------------------------------------
1 | BasicCrypto.cc
2 | paillier.cc
3 | urandom.cc
4 | arc4.cc
5 | hgd.cc
6 | pbkdf2.cc
7 | ecjoin.cc
8 | ECJoin.cc
9 | search.cc
10 | skip32.cc
11 | ffx.cc
12 | online_ope.cc
13 | mont.cc
14 | prng.cc
15 | ope.cc
16 | SWPSearch.cc
17 |
--------------------------------------------------------------------------------
/crypto/arc4.cc:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | using namespace std;
4 |
5 | arc4::arc4(const std::string &key)
6 | {
7 | reset();
8 | for (size_t n = 0; n < key.size(); n += 128)
9 | addkey((const uint8_t *) &key[n], min((size_t) 128, key.size() - n));
10 | j = i;
11 |
12 | /* discard first bytes */
13 | for (int n = 0; n < 4096; n++)
14 | getbyte();
15 | }
16 |
17 | void
18 | arc4::reset()
19 | {
20 | i = 0xff;
21 | j = 0;
22 | for (int n = 0; n < 0x100; n++)
23 | s[n] = n;
24 | }
25 |
26 | void
27 | arc4::addkey(const uint8_t *key, size_t keylen)
28 | {
29 | size_t n, keypos;
30 | uint8_t si;
31 | for (n = 0, keypos = 0; n < 256; n++, keypos++) {
32 | if (keypos >= keylen)
33 | keypos = 0;
34 | i = (i + 1) & 0xff;
35 | si = s[i];
36 | j = (j + si + key[keypos]) & 0xff;
37 | s[i] = s[j];
38 | s[j] = si;
39 | }
40 | }
41 |
42 | uint8_t
43 | arc4::getbyte()
44 | {
45 | uint8_t si, sj;
46 | i = (i + 1) & 0xff;
47 | si = s[i];
48 | j = (j + si) & 0xff;
49 | sj = s[j];
50 | s[i] = sj;
51 | s[j] = si;
52 | return s[(si + sj) & 0xff];
53 | }
54 |
--------------------------------------------------------------------------------
/crypto/arc4.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | class arc4 {
6 | public:
7 | arc4(const std::string &key);
8 | uint8_t getbyte();
9 |
10 | private:
11 | arc4(const arc4 &);
12 |
13 | void reset();
14 | void addkey(const uint8_t *key, size_t keylen);
15 |
16 | uint8_t i;
17 | uint8_t j;
18 | uint8_t s[256];
19 | };
20 |
--------------------------------------------------------------------------------
/crypto/blowfish.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | class blowfish {
8 | public:
9 | blowfish(const std::string &key) {
10 | BF_set_key(&k, key.size(), (const uint8_t*) key.data());
11 | }
12 |
13 | void block_encrypt(const void *ptext, void *ctext) const {
14 | BF_ecb_encrypt((const uint8_t*) ptext, (uint8_t*) ctext, &k, BF_ENCRYPT);
15 | }
16 |
17 | void block_decrypt(const void *ctext, void *ptext) const {
18 | BF_ecb_encrypt((const uint8_t*) ctext, (uint8_t*) ptext, &k, BF_DECRYPT);
19 | }
20 |
21 | uint64_t encrypt(uint64_t pt) const {
22 | uint64_t ct;
23 | block_encrypt(&pt, &ct);
24 | return ct;
25 | }
26 |
27 | uint64_t decrypt(uint64_t ct) const {
28 | uint64_t pt;
29 | block_decrypt(&ct, &pt);
30 | return pt;
31 | }
32 |
33 | static const size_t blocksize = 8;
34 |
35 | private:
36 | BF_KEY k;
37 | };
38 |
--------------------------------------------------------------------------------
/crypto/bn.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 | class _bignum_ctx {
11 | public:
12 | _bignum_ctx() { c = BN_CTX_new(); }
13 | ~_bignum_ctx() { BN_CTX_free(c); }
14 | BN_CTX *ctx() { return c; }
15 |
16 | static BN_CTX *the_ctx() {
17 | static _bignum_ctx cx;
18 | return cx.ctx();
19 | }
20 |
21 | private:
22 | BN_CTX *c;
23 | };
24 |
25 | class bignum {
26 | public:
27 | bignum() {
28 | BN_init(&b);
29 | }
30 |
31 | bignum(unsigned long v) {
32 | BN_init(&b);
33 | BN_set_word(&b, v);
34 | }
35 |
36 | bignum(const bignum &other) {
37 | BN_init(&b);
38 | throw_c(BN_copy(&b, other.bn()));
39 | }
40 |
41 | bignum(const uint8_t *buf, size_t nbytes) {
42 | BN_init(&b);
43 | throw_c(BN_bin2bn(buf, nbytes, &b));
44 | }
45 |
46 | bignum(const std::string &v) {
47 | BN_init(&b);
48 | throw_c(BN_bin2bn((uint8_t*) v.data(), v.size(), &b));
49 | }
50 |
51 | ~bignum() { BN_free(&b); }
52 |
53 | BIGNUM *bn() { return &b; }
54 | const BIGNUM *bn() const { return &b; }
55 | unsigned long word() const {
56 | unsigned long v = BN_get_word(&b);
57 | if (v == 0xffffffffL)
58 | throw std::runtime_error("out of range");
59 | return v;
60 | }
61 |
62 | #define op(opname, func, args...) \
63 | bignum opname(const bignum &mod) { \
64 | bignum res; \
65 | throw_c(1 == func(res.bn(), &b, mod.bn(), ##args)); \
66 | return res; \
67 | }
68 |
69 | op(operator+, BN_add)
70 | op(operator-, BN_sub)
71 | op(operator%, BN_mod, _bignum_ctx::the_ctx())
72 | op(operator*, BN_mul, _bignum_ctx::the_ctx())
73 | #undef op
74 |
75 | #define pred(predname, cmp) \
76 | bool predname(const bignum &other) { \
77 | return BN_cmp(&b, other.bn()) cmp; \
78 | }
79 |
80 | pred(operator<, < 0)
81 | pred(operator<=, <= 0)
82 | pred(operator>, > 0)
83 | pred(operator>=, >= 0)
84 | pred(operator==, == 0)
85 | #undef pred
86 |
87 | bignum invmod(const bignum &mod) {
88 | bignum r;
89 | throw_c(BN_mod_inverse(r.bn(), &b, mod.bn(), _bignum_ctx::the_ctx()));
90 | return r;
91 | }
92 |
93 | private:
94 | BIGNUM b;
95 | };
96 |
97 | static inline std::ostream&
98 | operator<<(std::ostream &out, const bignum &bn)
99 | {
100 | char *s = BN_bn2dec(bn.bn());
101 | out << s;
102 | OPENSSL_free(s);
103 | return out;
104 | }
105 |
--------------------------------------------------------------------------------
/crypto/cbcmac.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | template
7 | class cbcmac {
8 | public:
9 | cbcmac(const BlockCipher *cx) {
10 | c = cx;
11 | memset(v, 0, BlockCipher::blocksize);
12 | mbytes = 0;
13 | }
14 |
15 | cbcmac(const BlockCipher *cx, void *iv) {
16 | c = cx;
17 | memcpy(v, iv, BlockCipher::blocksize);
18 | mbytes = 0;
19 | }
20 |
21 | void update(const void *data, size_t len) {
22 | const uint8_t *d = static_cast (data);
23 |
24 | if (mbytes) {
25 | size_t ncopy = std::min(len, BlockCipher::blocksize - mbytes);
26 | memcpy(&m[mbytes], d, ncopy);
27 | d += ncopy;
28 | len -= ncopy;
29 | mbytes += ncopy;
30 | }
31 |
32 | if (mbytes == BlockCipher::blocksize) {
33 | do_block(m);
34 | mbytes = 0;
35 | }
36 |
37 | while (len >= BlockCipher::blocksize) {
38 | do_block(d);
39 | d += BlockCipher::blocksize;
40 | len -= BlockCipher::blocksize;
41 | }
42 |
43 | if (len) {
44 | memcpy(m, d, len);
45 | mbytes = len;
46 | }
47 | }
48 |
49 | void update(const std::string &v) {
50 | update(v.data(), v.size());
51 | }
52 |
53 | void final(uint8_t *buf) {
54 | if (mbytes) {
55 | memset(&m[mbytes], 0, BlockCipher::blocksize - mbytes);
56 | do_block(m);
57 | }
58 |
59 | memcpy(buf, v, BlockCipher::blocksize);
60 | }
61 |
62 | std::string final() {
63 | std::string f;
64 | f.resize(BlockCipher::blocksize);
65 | final((uint8_t*) f.data());
66 | return f;
67 | }
68 |
69 | static const size_t blocksize = BlockCipher::blocksize;
70 |
71 | private:
72 | void do_block(const uint8_t *p) {
73 | uint8_t x[BlockCipher::blocksize];
74 | for (size_t i = 0; i < BlockCipher::blocksize; i++)
75 | x[i] = v[i] ^ p[i];
76 | c->block_encrypt(x, v);
77 | }
78 |
79 | uint8_t v[BlockCipher::blocksize];
80 | uint8_t m[BlockCipher::blocksize];
81 | uint8_t mbytes;
82 |
83 | const BlockCipher *c;
84 | };
85 |
--------------------------------------------------------------------------------
/crypto/dj.hh:
--------------------------------------------------------------------------------
1 | /*
2 | * Damgard-Jurik (a generalization of Paillier) provides a ciphertext
3 | * size that is asymptotically close to the plaintext size, rather
4 | * than a factor of 2 larger in standard Paillier.
5 | *
6 | * This may be especially useful in applications where ciphertext space
7 | * is the bottleneck, where in combination with packing, this should
8 | * provide almost no ciphertext storage overheads (except for spacing
9 | * for aggregate overflow).
10 | *
11 | * "A Generalisation, a Simplification and some Applications of
12 | * Paillier's Probabilistic Public-Key System", by Damgard and Jurik.
13 | *
14 | */
15 |
16 |
--------------------------------------------------------------------------------
/crypto/ec.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | class ec_point {
8 | public:
9 | ec_point(const EC_GROUP *group) {
10 | gr = group;
11 | pt = EC_POINT_new(gr);
12 | }
13 |
14 | ec_point(const ec_point &other) {
15 | gr = other.gr;
16 | pt = EC_POINT_dup(other.pt, gr);
17 | }
18 |
19 | ~ec_point() {
20 | EC_POINT_free(pt);
21 | }
22 |
23 | ec_point operator*(const bignum &n) const {
24 | bignum zero(0);
25 | ec_point res(gr);
26 | throw_c(EC_POINT_mul(gr, res.p(), zero.bn(),
27 | pt, n.bn(), _bignum_ctx::the_ctx()));
28 | return res;
29 | }
30 |
31 | bool operator==(const ec_point &other) const {
32 | return EC_POINT_cmp(gr, pt, other.pt, _bignum_ctx::the_ctx()) == 0;
33 | }
34 |
35 | bool operator!=(const ec_point &other) const {
36 | return EC_POINT_cmp(gr, pt, other.pt, _bignum_ctx::the_ctx()) != 0;
37 | }
38 |
39 | std::string to_string(point_conversion_form_t form =
40 | POINT_CONVERSION_UNCOMPRESSED) const {
41 | char *s = EC_POINT_point2hex(gr, pt, form, _bignum_ctx::the_ctx());
42 | std::string r(s);
43 | free(s);
44 | return r;
45 | }
46 |
47 | EC_POINT *p() { return pt; }
48 |
49 | private:
50 | EC_POINT *pt;
51 | const EC_GROUP *gr;
52 | };
53 |
54 | static inline std::ostream&
55 | operator<<(std::ostream &out, const ec_point &p)
56 | {
57 | return out << p.to_string();
58 | }
59 |
--------------------------------------------------------------------------------
/crypto/ecjoin.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | ecjoin::ecjoin(int curve_id)
7 | {
8 | group = EC_GROUP_new_by_curve_name(curve_id);
9 | throw_c(group);
10 |
11 | throw_c(EC_GROUP_get_order(group, order.bn(), _bignum_ctx::the_ctx()));
12 | }
13 |
14 | ecjoin::~ecjoin()
15 | {
16 | EC_GROUP_free(group);
17 | }
18 |
19 | ec_point
20 | ecjoin::adjust(const ec_point &p, const bignum &delta_k)
21 | {
22 | return p * delta_k;
23 | }
24 |
25 |
26 | ecjoin_priv::ecjoin_priv(const std::string &base_key, int curve_id)
27 | : ecjoin(curve_id), base(sha256::hash(base_key)), basept(group)
28 | {
29 | streamrng r(base_key);
30 |
31 | for (;;) {
32 | bignum x = r.rand_bn_mod(order);
33 | if (!EC_POINT_set_compressed_coordinates_GFp(group, basept.p(),
34 | x.bn(), 1,
35 | _bignum_ctx::the_ctx()))
36 | continue;
37 |
38 | bignum y;
39 | throw_c(EC_POINT_get_affine_coordinates_GFp(group, basept.p(),
40 | x.bn(), y.bn(),
41 | _bignum_ctx::the_ctx()));
42 | if (x == 0 || y == 0)
43 | continue;
44 |
45 | if (EC_POINT_is_on_curve(group, basept.p(), _bignum_ctx::the_ctx()))
46 | break;
47 | }
48 | }
49 |
50 | ec_point
51 | ecjoin_priv::hash(const std::string &ptext, const std::string &k)
52 | {
53 | auto hash = sha1::hash(ptext);
54 | throw_c(hash.size() >= base.blocksize);
55 | hash.resize(base.blocksize);
56 |
57 | std::string enc;
58 | enc.resize(base.blocksize);
59 | base.block_encrypt(&hash[0], &enc[0]);
60 |
61 | bignum kn(sha256::hash(k));
62 | bignum enc_bn(enc);
63 |
64 | return basept * (kn % order) * (enc_bn % order);
65 | }
66 |
67 | bignum
68 | ecjoin_priv::delta(const std::string &k0, const std::string &k1)
69 | {
70 | bignum kn0(sha256::hash(k0));
71 | bignum kn1(sha256::hash(k1));
72 |
73 | return ((kn1 % order) * kn0.invmod(order)) % order;
74 | }
75 |
--------------------------------------------------------------------------------
/crypto/ecjoin.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | static int ecjoin_default_curve = NID_X9_62_prime192v1;
10 |
11 | class ecjoin {
12 | public:
13 | ecjoin(int curve_id = ecjoin_default_curve);
14 | ~ecjoin();
15 |
16 | static ec_point adjust(const ec_point &p, const bignum &delta_k);
17 |
18 | protected:
19 | EC_GROUP *group;
20 | bignum order;
21 | };
22 |
23 | class ecjoin_priv : public ecjoin {
24 | public:
25 | ecjoin_priv(const std::string &base_key,
26 | int curve_id = ecjoin_default_curve);
27 |
28 | ec_point hash(const std::string &ptext, const std::string &k);
29 | bignum delta(const std::string &k0, const std::string &k1);
30 |
31 | private:
32 | AES base;
33 | ec_point basept;
34 | };
35 |
--------------------------------------------------------------------------------
/crypto/ffx.cc:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void ffx_mem_to_u64(const uint8_t *p,
4 | uint64_t *a, uint64_t *b,
5 | uint abits, uint bbits)
6 | {
7 | throw_c(abits <= 64 && bbits <= 64);
8 |
9 | *a = 0;
10 | *b = 0;
11 |
12 | while (abits >= 8) {
13 | *a = *a << 8 | *p;
14 | p++;
15 | abits -= 8;
16 | }
17 |
18 | if (abits) {
19 | *a = *a << abits | *p >> (8 - abits);
20 | uint8_t pleft = *p & ((1 << (8 - abits)) - 1);
21 | if (bbits < 8 - abits) {
22 | *b = pleft >> (8 - bbits);
23 | bbits = 0;
24 | } else {
25 | *b = pleft;
26 | bbits -= 8 - abits;
27 | }
28 | p++;
29 | }
30 |
31 | while (bbits >= 8) {
32 | *b = *b << 8 | *p;
33 | p++;
34 | bbits -= 8;
35 | }
36 |
37 | if (bbits)
38 | *b = *b << bbits | *p >> (8 - bbits);
39 | }
40 |
41 | void ffx_u64_to_mem(uint64_t a, uint64_t b,
42 | uint64_t abits, uint64_t bbits,
43 | uint8_t *p)
44 | {
45 | throw_c(abits <= 64 && bbits <= 64);
46 |
47 | while (abits >= 8) {
48 | *p = a >> (abits - 8);
49 | p++;
50 | abits -= 8;
51 | }
52 |
53 | if (abits) {
54 | *p = a & ((1 << abits) - 1);
55 | if (bbits < 8 - abits) {
56 | *p = (*p << bbits | (b & ((1 << bbits) - 1))) << (8 - abits - bbits);
57 | bbits = 0;
58 | } else {
59 | *p = *p << (8 - abits) | b >> (bbits - (8 - abits));
60 | bbits -= (8 - abits);
61 | }
62 | p++;
63 | }
64 |
65 | while (bbits >= 8) {
66 | *p = b >> (bbits - 8);
67 | p++;
68 | bbits -= 8;
69 | }
70 |
71 | if (bbits)
72 | *p = b << (8 - bbits);
73 | }
74 |
--------------------------------------------------------------------------------
/crypto/hgd.hh:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | /*
5 | * KK is the number of elements drawn from an urn where there are NN1 white
6 | * balls and NN2 black balls; the result is the number of white balls in
7 | * the KK sample.
8 | *
9 | * The implementation is based on an adaptation of the H2PEC alg for large
10 | * numbers; see hgd.cc for details
11 | */
12 | NTL::ZZ HGD(const NTL::ZZ &KK,
13 | const NTL::ZZ &NN1,
14 | const NTL::ZZ &NN2,
15 | PRNG *prng);
16 |
--------------------------------------------------------------------------------
/crypto/hmac.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | template
6 | class hmac {
7 | public:
8 | hmac(const void *keydata, size_t keylen) {
9 | static_assert(Hash::blocksize >= Hash::hashsize,
10 | "Hack::blocksize should be >= Hash::hashsize");
11 |
12 | uint8_t k[Hash::blocksize];
13 | memset(k, 0, sizeof(k));
14 | if (keylen <= Hash::blocksize) {
15 | memcpy(k, keydata, keylen);
16 | } else {
17 | Hash kh;
18 | kh.update(keydata, keylen);
19 | kh.final(k);
20 | }
21 |
22 | for (size_t i = 0; i < Hash::blocksize; i++) {
23 | opad[i] = k[i] ^ 0x5c;
24 | ipad[i] = k[i] ^ 0x36;
25 | }
26 |
27 | h.update(ipad, sizeof(ipad));
28 | }
29 |
30 | void update(const void *data, size_t len) {
31 | h.update(data, len);
32 | }
33 |
34 | void final(uint8_t *buf) {
35 | uint8_t inner[Hash::hashsize];
36 | h.final(inner);
37 |
38 | Hash outer;
39 | outer.update(opad, sizeof(opad));
40 | outer.update(inner, sizeof(inner));
41 | outer.final(buf);
42 | }
43 |
44 | std::string final() {
45 | std::string v;
46 | v.resize(Hash::hashsize);
47 | final((uint8_t*) v.data());
48 | return v;
49 | }
50 |
51 | static std::string mac(const std::string &v, const std::string &key) {
52 | hmac x(&key[0], key.size());
53 | x.update(&v[0], v.size());
54 | return x.final();
55 | }
56 |
57 | private:
58 | uint8_t opad[Hash::blocksize];
59 | uint8_t ipad[Hash::blocksize];
60 | Hash h;
61 | };
62 |
--------------------------------------------------------------------------------
/crypto/mont.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #include
5 |
6 | using namespace std;
7 | using namespace NTL;
8 |
9 | ZZ
10 | montgomery::to_mont(const ZZ &a)
11 | {
12 | return MulMod(a, _r, _m);
13 | }
14 |
15 | ZZ
16 | montgomery::from_mont(const ZZ &a)
17 | {
18 | return MulMod(a, _rinv, _m);
19 | }
20 |
21 | #define SIZE(p) (((long *) (p))[1])
22 | #define DATA(p) ((mp_limb_t *) (((long *) (p)) + 2))
23 |
24 | ZZ
25 | montgomery::mmul(const ZZ &a, const ZZ &b)
26 | {
27 | static_assert(sizeof(mp_limb_t) == sizeof(long), "mp_limb_t not long");
28 | ZZ ab = a * b;
29 | if (ab == 0) return ab; // to avoid testing in loop
30 |
31 | for (uint i = 0; i < _mbits; i += sizeof(long) * 8) {
32 | uint thisbits = std::min((uint) sizeof(long) * 8, _mbits - i);
33 | mp_limb_t* abdata = DATA(ab.rep);
34 | long l = abdata[0];
35 | long c = _minusm_inv_modr * l;
36 | if (thisbits < sizeof(long) * 8)
37 | c &= (((long)1) << thisbits) - 1;
38 | ab += _m * c;
39 |
40 | // throw_c(trunc_long(ab, thisbits) == 0);
41 | ab >>= thisbits;
42 | }
43 |
44 | while (ab >= _m)
45 | ab = ab - _m;
46 | return ab;
47 | }
48 |
--------------------------------------------------------------------------------
/crypto/mont.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | class montgomery {
6 | private:
7 | NTL::ZZ _m;
8 | uint _mbits;
9 | NTL::ZZ _r;
10 | NTL::ZZ _rinv;
11 | long _minusm_inv_modr;
12 |
13 | public:
14 | montgomery(const NTL::ZZ &m)
15 | : _m(m), _mbits(NumBits(m)), _r(NTL::to_ZZ(1) << _mbits),
16 | _rinv(InvMod(_r % _m, _m)),
17 | _minusm_inv_modr(trunc_long(InvMod(_r-_m, _r), sizeof(long) * 8)) {}
18 |
19 | NTL::ZZ to_mont(const NTL::ZZ &a);
20 | NTL::ZZ from_mont(const NTL::ZZ &a);
21 | NTL::ZZ mmul(const NTL::ZZ &a, const NTL::ZZ &b);
22 | };
23 |
--------------------------------------------------------------------------------
/crypto/ope.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | using namespace std;
10 | using namespace NTL;
11 |
12 | /*
13 | * A gap is represented by the next integer value _above_ the gap.
14 | */
15 | static ZZ
16 | domain_gap(const ZZ &ndomain, const ZZ &nrange, const ZZ &rgap, PRNG *prng)
17 | {
18 | return HGD(rgap, ndomain, nrange-ndomain, prng);
19 | }
20 |
21 | template
22 | ope_domain_range
23 | OPE::lazy_sample(const ZZ &d_lo, const ZZ &d_hi,
24 | const ZZ &r_lo, const ZZ &r_hi,
25 | CB go_low, blockrng *prng)
26 | {
27 | ZZ ndomain = d_hi - d_lo + 1;
28 | ZZ nrange = r_hi - r_lo + 1;
29 | throw_c(nrange >= ndomain);
30 |
31 | if (ndomain == 1)
32 | return ope_domain_range(d_lo, r_lo, r_hi);
33 |
34 | /*
35 | * Deterministically reset the PRNG counter, regardless of
36 | * whether we had to use it for HGD or not in previous round.
37 | */
38 | auto v = hmac::mac(StringFromZZ(d_lo) + "/" +
39 | StringFromZZ(d_hi) + "/" +
40 | StringFromZZ(r_lo) + "/" +
41 | StringFromZZ(r_hi), key);
42 | v.resize(AES::blocksize);
43 | prng->set_ctr(v);
44 |
45 | ZZ rgap = nrange/2;
46 | ZZ dgap;
47 |
48 | auto ci = dgap_cache.find(r_lo + rgap);
49 | if (ci == dgap_cache.end()) {
50 | dgap = domain_gap(ndomain, nrange, nrange / 2, prng);
51 | dgap_cache[r_lo + rgap] = dgap;
52 | } else {
53 | dgap = ci->second;
54 | }
55 |
56 | if (go_low(d_lo + dgap, r_lo + rgap))
57 | return lazy_sample(d_lo, d_lo + dgap - 1, r_lo, r_lo + rgap - 1, go_low, prng);
58 | else
59 | return lazy_sample(d_lo + dgap, d_hi, r_lo + rgap, r_hi, go_low, prng);
60 | }
61 |
62 | template
63 | ope_domain_range
64 | OPE::search(CB go_low)
65 | {
66 | blockrng r(aesk);
67 |
68 | return lazy_sample(to_ZZ(0), to_ZZ(1) << pbits,
69 | to_ZZ(0), to_ZZ(1) << cbits,
70 | go_low, &r);
71 | }
72 |
73 | ZZ
74 | OPE::encrypt(const ZZ &ptext)
75 | {
76 | ope_domain_range dr =
77 | search([&ptext](const ZZ &d, const ZZ &) { return ptext < d; });
78 |
79 | auto v = sha256::hash(StringFromZZ(ptext));
80 | v.resize(16);
81 |
82 | blockrng aesrand(aesk);
83 | aesrand.set_ctr(v);
84 |
85 | ZZ nrange = dr.r_hi - dr.r_lo + 1;
86 | return dr.r_lo + aesrand.rand_zz_mod(nrange);
87 | }
88 |
89 | ZZ
90 | OPE::decrypt(const ZZ &ctext)
91 | {
92 | ope_domain_range dr =
93 | search([&ctext](const ZZ &, const ZZ &r) { return ctext < r; });
94 | return dr.d;
95 | }
96 |
--------------------------------------------------------------------------------
/crypto/ope.hh:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include