├── rebar3 ├── rebar.lock ├── .gitignore ├── test ├── group_test.erl ├── serialize_deserialize_test.erl ├── dealer_test.erl ├── dealer_SUITE.erl ├── signature_SUITE.erl └── decrypt_SUITE.erl ├── src ├── erlang_tpke.app.src ├── tpke_privkey.erl ├── dealer.erl └── tpke_pubkey.erl ├── rebar.config ├── Makefile ├── README.md ├── eqc ├── secret_key_match_eqc.erl ├── combine_signature_shares_eqc.erl └── decrypt_shares_eqc.erl ├── .github └── workflows │ └── ci.yml └── LICENSE /rebar3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helium/erlang-tpke/HEAD/rebar3 -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | [{<<"erlang_pbc">>, 2 | {git,"https://github.com/helium/erlang_pbc.git", 3 | {ref,"1d2651ba01ba81b748c553d9f729c0e167eeab72"}}, 4 | 0}]. 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .eunit 2 | deps 3 | *.o 4 | *.beam 5 | *.plt 6 | erl_crash.dump 7 | ebin/*.beam 8 | rel/example_project 9 | .concrete/DEV_MODE 10 | .rebar 11 | _build 12 | .rebar3/ 13 | *.crashdump 14 | .eqc 15 | current_counterexample.eqc 16 | .eqc-info 17 | -------------------------------------------------------------------------------- /test/group_test.erl: -------------------------------------------------------------------------------- 1 | -module(group_test). 2 | 3 | -include_lib("eunit/include/eunit.hrl"). 4 | 5 | basic_test() -> 6 | Group = erlang_pbc:group_new('SS512'), 7 | Element = erlang_pbc:element_new('G1', Group), 8 | ?assertEqual(erlang_pbc:element_to_string(Element), "O"), 9 | ok. 10 | -------------------------------------------------------------------------------- /src/erlang_tpke.app.src: -------------------------------------------------------------------------------- 1 | {application, erlang_tpke, 2 | [{description, "Erlang implementation of TPKE"}, 3 | {vsn, "0.1.0"}, 4 | {applications, 5 | [kernel, 6 | stdlib, 7 | erlang_pbc 8 | ]}, 9 | {env,[]}, 10 | 11 | {maintainers, ["Helium"]}, 12 | {licenses, ["Apache 2.0"]}, 13 | {links, [{"Github", "https://github.com/helium/erlang-tpke"}]} 14 | ]}. 15 | -------------------------------------------------------------------------------- /test/serialize_deserialize_test.erl: -------------------------------------------------------------------------------- 1 | -module(serialize_deserialize_test). 2 | 3 | -include_lib("eunit/include/eunit.hrl"). 4 | 5 | simple_test() -> 6 | {ok, Dealer} = dealer:new(), 7 | {ok, _Group} = dealer:group(Dealer), 8 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 9 | 10 | SerializedPubKey = tpke_pubkey:serialize(PubKey), 11 | SerializedPvtKeys = [tpke_privkey:serialize(PK) || PK <- PrivateKeys], 12 | Foo = hd(SerializedPvtKeys), 13 | ?assertEqual(SerializedPubKey, tpke_pubkey:serialize(tpke_privkey:public_key(tpke_privkey:deserialize(Foo)))), 14 | ok. 15 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | %% -*- erlang -*- 2 | 3 | {erl_opts, [debug_info, warn_untyped_record, warnings_as_errors]}. 4 | 5 | {cover_export_enabled, true}. 6 | {cover_enabled, true}. 7 | {cover_opts, [verbose]}. 8 | 9 | {deps, [ 10 | {erlang_pbc, ".*", {git, "https://github.com/helium/erlang_pbc.git", {branch, "master"}}} 11 | ]}. 12 | 13 | {plugins, [ 14 | {rebar3_eqc, {git, "https://github.com/Vagabond/rebar3-eqc-plugin", {branch, "master"}}}, 15 | covertool 16 | ]}. 17 | 18 | {dialyzer, [ 19 | {warnings, [unknown]}, 20 | {plt_apps, all_deps} 21 | ]}. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: compile rel test typecheck 2 | 3 | REBAR=./rebar3 4 | 5 | compile: 6 | $(REBAR) compile 7 | 8 | clean: 9 | $(REBAR) clean 10 | 11 | test: 12 | $(REBAR) as test do eunit,ct 13 | 14 | typecheck: 15 | $(REBAR) dialyzer 16 | 17 | ci: 18 | $(REBAR) do dialyzer && $(REBAR) do eunit,ct 19 | $(REBAR) do cover,covertool generate 20 | codecov --required -f _build/test/covertool/erlang_tpke.covertool.xml 21 | 22 | ci-nightly: 23 | $(REBAR) do eunit,ct,eqc -t 1800 24 | cp -f _build/eqc/cover/eqc.coverdata _build/test/cover/ 25 | $(REBAR) do cover,covertool generate 26 | codecov --required -f _build/test/covertool/erlang_tpke.covertool.xml 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | erlang_tpke 2 | ===== 3 | 4 | [![CI](https://github.com/helium/erlang-tpke/actions/workflows/ci.yml/badge.svg)](https://github.com/helium/erlang-tpke/actions/workflows/ci.yml) 5 | [![codecov](https://codecov.io/gh/helium/erlang-tpke/branch/master/graph/badge.svg)](https://codecov.io/gh/helium/erlang-tpke) 6 | 7 | Erlang implementation of TPKE 8 | 9 | Build 10 | ----- 11 | 12 | $ make 13 | 14 | Test 15 | ----- 16 | 17 | $ make test 18 | 19 | References 20 | ----- 21 | 22 | * [Simple and Efficient Threshold Cryptosystem from the Gap Diffie-Hellman Group](https://pdfs.semanticscholar.org/f613/e2a76843153d19adcd7c59f2766334f799bf.pdf) 23 | * [Honey Badger of BFT Protocols](https://eprint.iacr.org/2016/199.pdf) 24 | * [Distributed Key Generation in the Wild](https://eprint.iacr.org/2012/377.pdf) 25 | * [Efficient threshold signature, multisignature and blind signature schemes based on the Gap Diffie-Hellman group signature scheme](https://eprint.iacr.org/2002/118.pdf) 26 | -------------------------------------------------------------------------------- /eqc/secret_key_match_eqc.erl: -------------------------------------------------------------------------------- 1 | -module(secret_key_match_eqc). 2 | 3 | -include_lib("eqc/include/eqc.hrl"). 4 | 5 | -export([prop_secret_key_match/0]). 6 | 7 | prop_secret_key_match() -> 8 | ?FORALL(N, gen_coefficients(), 9 | begin 10 | Group = erlang_pbc:group_new('SS512'), 11 | Element = erlang_pbc:element_new('Zr', Group), 12 | Coefficients = [ erlang_pbc:element_random(Element) || _ <- lists:seq(1, N)], 13 | Secret = hd(Coefficients), 14 | FirstSecret = dealer:share_secret(0, Coefficients), 15 | ?WHENFAIL(begin 16 | io:format("Secret ~p~n", [erlang_pbc:element_to_string(Secret)]), 17 | io:format("FirstSecret ~p~n", [erlang_pbc:element_to_string(FirstSecret)]) 18 | end, 19 | conjunction([ 20 | {secret_equality, eqc:equals(erlang_pbc:element_to_string(Secret), erlang_pbc:element_to_string(FirstSecret))} 21 | ])) 22 | end). 23 | 24 | gen_coefficients() -> 25 | ?SUCHTHAT(L, int(), L > 0). 26 | -------------------------------------------------------------------------------- /test/dealer_test.erl: -------------------------------------------------------------------------------- 1 | -module(dealer_test). 2 | 3 | -include_lib("eunit/include/eunit.hrl"). 4 | 5 | first_secret_equality_test() -> 6 | {ok, Dealer} = dealer:new(), 7 | {ok, Group} = dealer:group(Dealer), 8 | %% TODO make this work over the MNT224 curve 9 | %Group = erlang_pbc:group_new('MNT224'), 10 | Element = erlang_pbc:element_new('Zr', Group), 11 | K = 5, 12 | Coefficients = [erlang_pbc:element_random(Element) || _ <- lists:seq(1, K)], 13 | Secret = hd(Coefficients), 14 | FirstSecret = dealer:share_secret(0, Coefficients), 15 | ?assert(erlang_pbc:element_cmp(Secret, FirstSecret)). 16 | 17 | zero_reconstruction_test() -> 18 | {ok, Dealer} = dealer:new(), 19 | {ok, Group} = dealer:group(Dealer), 20 | {ok, {PubKey, _PrivateKeys}} = dealer:deal(Dealer), 21 | Element = erlang_pbc:element_new('Zr', Group), 22 | K = 5, 23 | Coefficients = [erlang_pbc:element_random(Element) || _ <- lists:seq(1, K)], 24 | FirstSecret = dealer:share_secret(0, Coefficients), 25 | Set = ordsets:from_list(lists:seq(0, K-1)), 26 | Bits = [ erlang_pbc:element_mul(tpke_pubkey:lagrange(PubKey, Set, J), dealer:share_secret(J+1, Coefficients)) || J <- ordsets:to_list(Set)], 27 | SumBits = lists:foldl(fun erlang_pbc:element_add/2, hd(Bits), tl(Bits)), 28 | ?assert(erlang_pbc:element_cmp(FirstSecret, SumBits)). 29 | -------------------------------------------------------------------------------- /test/dealer_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(dealer_SUITE). 2 | 3 | -include_lib("common_test/include/ct.hrl"). 4 | -include_lib("eunit/include/eunit.hrl"). 5 | 6 | -export([all/0, init_per_testcase/2, end_per_testcase/2]). 7 | -export([first_secret_equality_test/1, zero_reconstruction_test/1]). 8 | 9 | all() -> 10 | [first_secret_equality_test, zero_reconstruction_test]. 11 | 12 | init_per_testcase(_, Config) -> 13 | {ok, Dealer} = dealer:new(), 14 | {ok, Group} = dealer:group(Dealer), 15 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 16 | Element = erlang_pbc:element_new('Zr', Group), 17 | K = 5, 18 | Coefficients = [erlang_pbc:element_random(Element) || _ <- lists:seq(1, K)], 19 | [ {dealer, Dealer}, {group, Group}, {pubkey, PubKey}, {privkeys, PrivateKeys}, {element, Element}, {k, K}, {coefficients, Coefficients} | Config ]. 20 | 21 | end_per_testcase(_, _Config) -> 22 | ok. 23 | 24 | zero_reconstruction_test(Config) -> 25 | K = proplists:get_value(k, Config), 26 | Coefficients = proplists:get_value(coefficients, Config), 27 | PubKey = proplists:get_value(pubkey, Config), 28 | FirstSecret = dealer:share_secret(0, Coefficients), 29 | Set = ordsets:from_list(lists:seq(0, K-1)), 30 | Bits = [ erlang_pbc:element_mul(tpke_pubkey:lagrange(PubKey, Set, J), dealer:share_secret(J+1, Coefficients)) || J <- ordsets:to_list(Set)], 31 | SumBits = lists:foldl(fun erlang_pbc:element_add/2, hd(Bits), tl(Bits)), 32 | ?assert(erlang_pbc:element_cmp(FirstSecret, SumBits)). 33 | 34 | first_secret_equality_test(Config) -> 35 | Coefficients = proplists:get_value(coefficients, Config), 36 | Secret = hd(Coefficients), 37 | FirstSecret = dealer:share_secret(0, Coefficients), 38 | ?assert(erlang_pbc:element_cmp(Secret, FirstSecret)). 39 | -------------------------------------------------------------------------------- /test/signature_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(signature_SUITE). 2 | 3 | -include_lib("common_test/include/ct.hrl"). 4 | -include_lib("eunit/include/eunit.hrl"). 5 | 6 | -export([all/0, init_per_testcase/2, end_per_testcase/2]). 7 | -export([threshold_signatures_test/1]). 8 | 9 | all() -> 10 | [threshold_signatures_test]. 11 | 12 | init_per_testcase(_, Config) -> 13 | Curves = [ 'SS512', 'MNT224', 'MNT159'], 14 | LowDealers = [ dealer:new(10, 5, Curve) || Curve <- Curves ], 15 | HighDealers = [ dealer:new(100, 30, Curve) || Curve <- Curves ], 16 | [ {dealers, LowDealers ++ HighDealers} | Config ]. 17 | 18 | end_per_testcase(_, _Config) -> 19 | ok. 20 | 21 | threshold_signatures_test(Config) -> 22 | Dealers = proplists:get_value(dealers, Config), 23 | lists:foreach(fun({ok, Dealer}) -> 24 | {ok, K} = dealer:threshold(Dealer), 25 | {ok, _Group} = dealer:group(Dealer), 26 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 27 | Msg = crypto:hash(sha256, crypto:strong_rand_bytes(12)), 28 | MessageToSign = tpke_pubkey:hash_message(PubKey, Msg), 29 | Signatures = [ tpke_privkey:sign(PrivKey, MessageToSign) || PrivKey <- PrivateKeys], 30 | io:format("Signatures ~p~n", [[ erlang_pbc:element_to_string(S) || {_, S} <- Signatures]]), 31 | ?assert(lists:all(fun(X) -> X end, [tpke_pubkey:verify_signature_share(PubKey, Share, MessageToSign) || Share <- Signatures])), 32 | {ok, Sig} = tpke_pubkey:combine_signature_shares(PubKey, dealer:random_n(K, Signatures), MessageToSign), 33 | ?assert(tpke_pubkey:verify_signature(PubKey, Sig, MessageToSign)) 34 | end, Dealers). 35 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | CI: 11 | runs-on: ubuntu-18.04 12 | container: heliumsystems/builder-erlang:2 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Cancel previous runs 19 | if: ${{ !env.ACT }} 20 | uses: styfle/cancel-workflow-action@0.5.0 21 | with: 22 | access_token: ${{ github.token }} 23 | 24 | - name: Cache Hex Packages 25 | if: ${{ !env.ACT }} 26 | uses: actions/cache@v1 27 | with: 28 | path: ~/.cache/rebar3/hex/hexpm/packages 29 | key: ${{ runner.os }}-hex-${{ hashFiles(format('{0}{1}', github.workspace, '/rebar.lock')) }} 30 | restore-keys: | 31 | ${{ runner.os }}-hex- 32 | 33 | - name: Cache Dialyzer PLTs 34 | if: ${{ !env.ACT }} 35 | uses: actions/cache@v1 36 | with: 37 | path: ~/.cache/rebar3/rebar3_*_plt 38 | key: ${{ runner.os }}-dialyzer-${{ hashFiles(format('{0}{1}', github.workspace, '/rebar.config')) }} 39 | restore-keys: | 40 | ${{ runner.os }}-dialyzer- 41 | 42 | - name: Build 43 | run: rebar3 compile 44 | 45 | - name: Run tests 46 | env: 47 | DATABASE_RO_URL: ${{ secrets.DATABASE_RO_URL }} 48 | DATABASE_RO_POOL_SIZE: 5 49 | run: rebar3 as test do eunit,ct,cover 50 | 51 | - name: Run Dialyzer 52 | run: rebar3 do dialyzer, xref 53 | 54 | - name: Generate coverage report 55 | run: rebar3 covertool generate 56 | 57 | - name: Upload coverage report 58 | if: ${{ !env.ACT }} 59 | uses: codecov/codecov-action@v1 60 | with: 61 | file: _build/test/covertool/erlang_tpke.covertool.xml 62 | fail_ci_if_error: true 63 | -------------------------------------------------------------------------------- /src/tpke_privkey.erl: -------------------------------------------------------------------------------- 1 | -module(tpke_privkey). 2 | 3 | -record(privkey, { 4 | pubkey :: tpke_pubkey:pubkey(), 5 | secret_key :: erlang_pbc:element(), 6 | secret_key_index :: non_neg_integer() 7 | }). 8 | 9 | -record(privkey_serialized, { 10 | pubkey :: tpke_pubkey:pubkey_serialized(), 11 | secret_key :: binary(), 12 | secret_key_index :: non_neg_integer() 13 | }). 14 | 15 | -opaque privkey() :: #privkey{}. 16 | -opaque privkey_serialized() :: #privkey_serialized{}. 17 | -type share() :: {non_neg_integer(), erlang_pbc:element()}. 18 | 19 | -export_type([privkey/0, share/0, privkey_serialized/0]). 20 | 21 | -export([init/3, decrypt_share/2, sign/2, public_key/1, serialize/1, deserialize/1]). 22 | 23 | -spec init(tpke_pubkey:pubkey(), erlang_pbc:element(), non_neg_integer()) -> privkey(). 24 | init(PubKey, SecretKey, SecretKeyIndex) -> 25 | #privkey{pubkey=PubKey, secret_key=SecretKey, secret_key_index=SecretKeyIndex}. 26 | 27 | %% Section 3.2.2 Baek and Zheng 28 | %% Dski(C): 29 | -spec decrypt_share(privkey(), tpke_pubkey:ciphertext()) -> share(). 30 | decrypt_share(PrivKey, CipherText) -> 31 | {U, _V, _W} = tpke_pubkey:check_ciphertext(PrivKey#privkey.pubkey, CipherText), 32 | %% computes Ui = xiU 33 | Share = erlang_pbc:element_mul(PrivKey#privkey.secret_key, U), 34 | %% output Di = (i, Ui) 35 | {PrivKey#privkey.secret_key_index, Share}. 36 | 37 | %% Section 5.2 Boldyrevya 38 | %% MS 39 | -spec sign(privkey(), erlang_pbc:element()) -> share(). 40 | sign(PrivKey, H) -> 41 | %% σj←H(M)^xj 42 | %% Note that H(M) has already been computed here 43 | {PrivKey#privkey.secret_key_index, erlang_pbc:element_pow(H, PrivKey#privkey.secret_key)}. 44 | 45 | -spec public_key(privkey()) -> tpke_pubkey:pubkey(). 46 | public_key(PrivKey) -> 47 | PrivKey#privkey.pubkey. 48 | 49 | -spec serialize(privkey()) -> privkey_serialized(). 50 | serialize(#privkey{pubkey=PubKey, secret_key=SK, secret_key_index=SKI}) -> 51 | #privkey_serialized{pubkey=tpke_pubkey:serialize(PubKey), secret_key=erlang_pbc:element_to_binary(SK), secret_key_index=SKI}. 52 | 53 | -spec deserialize(privkey_serialized()) -> privkey(). 54 | deserialize(#privkey_serialized{pubkey=PubKey, secret_key=SK, secret_key_index=SKI}) -> 55 | DeserializedPubKey = tpke_pubkey:deserialize(PubKey), 56 | #privkey{pubkey=DeserializedPubKey, secret_key=tpke_pubkey:deserialize_element(DeserializedPubKey, SK), secret_key_index=SKI}. 57 | -------------------------------------------------------------------------------- /src/dealer.erl: -------------------------------------------------------------------------------- 1 | -module(dealer). 2 | 3 | -export([new/0, 4 | new/3, 5 | share_secret/2, 6 | threshold/1, 7 | group/1, 8 | deal/1, 9 | random_n/2, 10 | shuffle/1]). 11 | 12 | -record(dealer, { 13 | pubkey :: undefined | tpke_pubkey:pubkey(), 14 | privkeys :: undefined | [tpke_privkey:privkey(), ...], 15 | group :: erlang_pbc:group(), 16 | players :: non_neg_integer(), 17 | curve :: tpke_pubkey:curve(), 18 | threshold :: non_neg_integer() 19 | }). 20 | 21 | new() -> 22 | new(10, 5, 'SS512'). 23 | 24 | new(Players, Threshold, Curve) -> 25 | {ok, #dealer{players=Players, curve=Curve, threshold=Threshold, group=erlang_pbc:group_new(Curve)}}. 26 | 27 | deal(_Dealer=#dealer{group=Group, threshold=Threshold, players=Players, curve=Curve}) -> 28 | Element = erlang_pbc:element_new('Zr', Group), 29 | Coefficients = [erlang_pbc:element_random(Element) || _ <- lists:seq(1, Threshold)], 30 | MasterSecret = hd(Coefficients), 31 | MasterSecretKeyShares = [share_secret(N, Coefficients) || N <- lists:seq(1, Players)], 32 | G1 = erlang_pbc:element_from_hash(erlang_pbc:element_new('G1', Group), crypto:strong_rand_bytes(32)), 33 | G2 = case erlang_pbc:pairing_is_symmetric(Group) of 34 | true -> G1; 35 | false -> erlang_pbc:element_from_hash(erlang_pbc:element_new('G2', Group), crypto:strong_rand_bytes(32)) 36 | end, 37 | %% pre-process them for faster exponents later 38 | erlang_pbc:element_pp_init(G1), 39 | erlang_pbc:element_pp_init(G2), 40 | VerificationKey = erlang_pbc:element_pow(G2, MasterSecret), 41 | VerificationKeys = [erlang_pbc:element_pow(G2, SecretKeyShare) || SecretKeyShare <- MasterSecretKeyShares], 42 | PublicKey = tpke_pubkey:init(Players, Threshold, G1, G2, VerificationKey, VerificationKeys, Curve), 43 | PrivateKeys = [tpke_privkey:init(PublicKey, SKShare, Index) || {Index, SKShare} <- enumerate(MasterSecretKeyShares)], 44 | {ok, {PublicKey, PrivateKeys}}. 45 | 46 | group(Dealer) -> 47 | {ok, Dealer#dealer.group}. 48 | 49 | threshold(Dealer) -> 50 | {ok, Dealer#dealer.threshold}. 51 | 52 | share_secret(Xval, Coefficients) -> 53 | Zero = erlang_pbc:element_set(hd(Coefficients), 0), 54 | One = erlang_pbc:element_set(hd(Coefficients), 1), 55 | share_secret(Xval, Coefficients, Zero, One). 56 | 57 | share_secret(_Xval, [] = _Coefficients, NewY, _InitX) -> NewY; 58 | share_secret(Xval, [Head | Tail] = _Coefficients, Y, X) -> 59 | NewY = erlang_pbc:element_add(Y, erlang_pbc:element_mul(Head, X)), 60 | NewX = erlang_pbc:element_mul(X, Xval), 61 | share_secret(Xval, Tail, NewY, NewX). 62 | 63 | %% helper functions 64 | 65 | enumerate(List) -> 66 | lists:zip(lists:seq(0, length(List) - 1), List). 67 | 68 | random_n(N, List) -> 69 | lists:sublist(shuffle(List), N). 70 | 71 | shuffle(List) -> 72 | [X || {_,X} <- lists:sort([{rand:uniform(), N} || N <- List])]. 73 | -------------------------------------------------------------------------------- /test/decrypt_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(decrypt_SUITE). 2 | 3 | -include_lib("common_test/include/ct.hrl"). 4 | -include_lib("eunit/include/eunit.hrl"). 5 | 6 | -export([all/0, init_per_testcase/2, end_per_testcase/2]). 7 | -export([threshold_decrypt_test/1]). 8 | 9 | all() -> 10 | [threshold_decrypt_test]. 11 | 12 | init_per_testcase(_, Config) -> 13 | D1 = dealer:new(10, 5, 'SS512'), 14 | D2 = dealer:new(100, 30, 'SS512'), 15 | [ {dealers, [D1, D2]} | Config ]. 16 | 17 | end_per_testcase(_, _Config) -> 18 | ok. 19 | 20 | threshold_decrypt_test(Config) -> 21 | Dealers = proplists:get_value(dealers, Config), 22 | lists:foreach(fun({ok, Dealer}) -> 23 | {ok, _Group} = dealer:group(Dealer), 24 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 25 | {ok, {OtherPubKey, OtherPrivateKeys}} = dealer:deal(Dealer), 26 | {ok, K} = dealer:threshold(Dealer), 27 | Message = crypto:hash(sha256, <<"my hovercraft is full of eels">>), 28 | CipherText = tpke_pubkey:encrypt(PubKey, Message), 29 | %% verify ciphertext 30 | ?assertError(unverified_ciphertext, [ tpke_privkey:decrypt_share(SK, CipherText) || SK <- PrivateKeys ]), 31 | {ok, VerifiedCipherText} = tpke_pubkey:verify_ciphertext(PubKey, CipherText), 32 | ?assertError(inconsistent_ciphertext, [ tpke_privkey:decrypt_share(SK, VerifiedCipherText) || SK <- OtherPrivateKeys ]), 33 | Shares = [ tpke_privkey:decrypt_share(SK, VerifiedCipherText) || SK <- PrivateKeys ], 34 | %% verify share 35 | ?assertError(unverified_ciphertext, lists:all(fun(X) -> X end, [tpke_pubkey:verify_share(PubKey, Share, CipherText) || Share <- Shares])), 36 | ?assertError(inconsistent_ciphertext, lists:all(fun(X) -> X end, [tpke_pubkey:verify_share(OtherPubKey, Share, VerifiedCipherText) || Share <- Shares])), 37 | ?assert(lists:all(fun(X) -> X end, [tpke_pubkey:verify_share(PubKey, Share, VerifiedCipherText) || Share <- Shares])), 38 | %% verify combine_shares 39 | ?assertError(unverified_ciphertext, tpke_pubkey:combine_shares(PubKey, CipherText, dealer:random_n(K, Shares))), 40 | ?assertError(inconsistent_ciphertext, tpke_pubkey:combine_shares(OtherPubKey, VerifiedCipherText, dealer:random_n(K, Shares))), 41 | ?assertEqual(Message, tpke_pubkey:combine_shares(PubKey, VerifiedCipherText, dealer:random_n(K, Shares))), 42 | %% test serialization/deserialization 43 | SerializedCipherText = tpke_pubkey:ciphertext_to_binary(VerifiedCipherText), 44 | %% we don't encode validation status 45 | ?assertEqual(SerializedCipherText, tpke_pubkey:ciphertext_to_binary(CipherText)), 46 | DeserializedCipherText = tpke_pubkey:binary_to_ciphertext(SerializedCipherText, PubKey), 47 | ?assertError(inconsistent_ciphertext, tpke_pubkey:binary_to_ciphertext(SerializedCipherText, OtherPubKey)), 48 | ?assertEqual(Message, tpke_pubkey:combine_shares(PubKey, DeserializedCipherText, dealer:random_n(K, Shares))), 49 | ok 50 | end, Dealers). 51 | -------------------------------------------------------------------------------- /eqc/combine_signature_shares_eqc.erl: -------------------------------------------------------------------------------- 1 | -module(combine_signature_shares_eqc). 2 | 3 | -include_lib("eqc/include/eqc.hrl"). 4 | 5 | -export([prop_combine_signature_shares/0]). 6 | 7 | prop_combine_signature_shares() -> 8 | ?FORALL({{Players, Threshold}, Curve, Fail}, {gen_players_threshold(), gen_curve(), gen_failure_mode()}, 9 | begin 10 | {ok, Dealer} = dealer:new(Players, Threshold, Curve), 11 | {ok, K} = dealer:threshold(Dealer), 12 | {ok, _Group} = dealer:group(Dealer), 13 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 14 | FailPKeys = case Fail of 15 | wrong_key -> 16 | {ok, {_, PKs}} = dealer:deal(Dealer), 17 | PKs; 18 | _ -> 19 | PrivateKeys 20 | end, 21 | Msg = crypto:hash(sha256, crypto:strong_rand_bytes(12)), 22 | MessageToSign = tpke_pubkey:hash_message(PubKey, Msg), 23 | FailMessage = case Fail of 24 | wrong_message -> 25 | tpke_pubkey:hash_message(PubKey, crypto:hash(sha256, crypto:strong_rand_bytes(12))); 26 | _ -> 27 | MessageToSign 28 | end, 29 | Signatures = [ tpke_privkey:sign(PrivKey, MessageToSign) || PrivKey <- PrivateKeys], 30 | FailSignatures = [ tpke_privkey:sign(PrivKey, FailMessage) || PrivKey <- FailPKeys], 31 | Shares = case Fail of 32 | duplicate_shares -> 33 | %% provide K shares, but with a duplicate 34 | [S|Ss] = dealer:random_n(K, Signatures), 35 | [S, S | tl(Ss)]; 36 | none -> dealer:random_n(K, Signatures); 37 | _ -> 38 | %% either wrong_message or wrong_key 39 | dealer:random_n(K-1, Signatures) ++ dealer:random_n(1, FailSignatures) 40 | end, 41 | 42 | SignatureVerified = case Fail of 43 | _ when Fail == none orelse Fail == duplicate_shares -> 44 | {ok, Sig} = tpke_pubkey:combine_signature_shares(PubKey, Shares, MessageToSign), 45 | tpke_pubkey:verify_signature(PubKey, Sig, MessageToSign); 46 | _ -> 47 | not ({error, bad_signature_share} == tpke_pubkey:combine_signature_shares(PubKey, Shares, MessageToSign)) 48 | end, 49 | 50 | SharesVerified = lists:all(fun(X) -> X end, [tpke_pubkey:verify_signature_share(PubKey, Share, MessageToSign) || Share <- Shares]), 51 | ?WHENFAIL(begin 52 | io:format("Signatures ~p~n", [[ erlang_pbc:element_to_string(S) || {_, S} <- Signatures]]), 53 | io:format("Shares ~p~n", [[ erlang_pbc:element_to_string(S) || {_, S} <- Shares]]) 54 | end, 55 | conjunction([ 56 | {verify_signature_share, eqc:equals((Fail == none orelse Fail == duplicate_shares), SharesVerified)}, 57 | {verify_combine_signature_shares, eqc:equals((Fail == none), SignatureVerified)} 58 | ])) 59 | end). 60 | 61 | gen_players_threshold() -> 62 | ?SUCHTHAT({Players, Threshold}, 63 | ?LET({X, Y}, 64 | ?SUCHTHAT({A, B}, {int(), int()}, A > 0 andalso B >= 0 andalso A > B), 65 | {X*3, X - Y}), 66 | Players > 3*Threshold+1 andalso Threshold > 1). 67 | 68 | gen_curve() -> 69 | elements(['SS512', 'MNT224', 'MNT159']). 70 | 71 | gen_failure_mode() -> 72 | elements([none, wrong_message, wrong_key, duplicate_shares]). 73 | -------------------------------------------------------------------------------- /eqc/decrypt_shares_eqc.erl: -------------------------------------------------------------------------------- 1 | -module(decrypt_shares_eqc). 2 | 3 | -include_lib("eqc/include/eqc.hrl"). 4 | 5 | -export([prop_decrypt_shares/0]). 6 | 7 | prop_decrypt_shares() -> 8 | ?FORALL({{Players, Threshold}, Curve, Fail}, {gen_players_threshold(), gen_curve(), gen_failure_mode()}, 9 | begin 10 | {ok, Dealer} = dealer:new(Players, Threshold, Curve), 11 | {ok, K} = dealer:threshold(Dealer), 12 | {ok, _Group} = dealer:group(Dealer), 13 | {ok, {PubKey, PrivateKeys}} = dealer:deal(Dealer), 14 | 15 | {FailPubKey, FailPKeys} = case Fail of 16 | wrong_key -> 17 | {ok, {FPk, PKs}} = dealer:deal(Dealer), 18 | {FPk, PKs}; 19 | _ -> 20 | {PubKey, PrivateKeys} 21 | end, 22 | 23 | Message = crypto:hash(sha256, crypto:strong_rand_bytes(12)), 24 | FailMessage = case Fail of 25 | wrong_message -> 26 | crypto:hash(sha256, crypto:strong_rand_bytes(12)); 27 | _ -> 28 | Message 29 | end, 30 | 31 | CipherText = tpke_pubkey:encrypt(PubKey, Message), 32 | {ok, VerifiedCipherText} = tpke_pubkey:verify_ciphertext(PubKey, CipherText), 33 | FailCipherText = tpke_pubkey:encrypt(FailPubKey, FailMessage), 34 | FailVerifiedCipherText = case tpke_pubkey:verify_ciphertext(PubKey, FailCipherText) of 35 | {ok, _} -> true; 36 | _ -> false 37 | end, 38 | 39 | GoodShares = [ tpke_privkey:decrypt_share(SK, VerifiedCipherText) || SK <- PrivateKeys ], 40 | 41 | FailShares = case Fail of 42 | wrong_message -> 43 | {ok, FCS} = tpke_pubkey:verify_ciphertext(PubKey, FailCipherText), 44 | [ tpke_privkey:decrypt_share(SK, FCS) || SK <- PrivateKeys ]; 45 | _ -> 46 | {ok, FCS} = tpke_pubkey:verify_ciphertext(FailPubKey, FailCipherText), 47 | [ tpke_privkey:decrypt_share(SK, FCS) || SK <- FailPKeys ] 48 | end, 49 | 50 | Shares = case Fail of 51 | duplicate_shares -> 52 | %% provide K shares, but with a duplicate 53 | [S|Ss] = dealer:random_n(K, GoodShares), 54 | [S, S | tl(Ss)]; 55 | none -> dealer:random_n(K, GoodShares); 56 | _ -> 57 | %% either wrong_message or wrong_key 58 | dealer:random_n(K-1, GoodShares) ++ dealer:random_n(1, FailShares) 59 | end, 60 | 61 | VerifiedShares = lists:all(fun(X) -> X end, [tpke_pubkey:verify_share(PubKey, Share, VerifiedCipherText) || Share <- Shares]), 62 | ValidShares = lists:usort([ Share || Share <- Shares, tpke_pubkey:verify_share(PubKey, Share, VerifiedCipherText) ]), 63 | VerifiedCombinedShares = tpke_pubkey:combine_shares(PubKey, VerifiedCipherText, Shares), 64 | 65 | ?WHENFAIL(begin 66 | io:format("K ~p~n", [K]), 67 | io:format("Shares ~p~n", [Shares]), 68 | io:format("FailShares ~p~n", [FailShares]) 69 | end, 70 | conjunction([ 71 | {dont_verify_wrong_ciphertext, eqc:equals((Fail /= wrong_key), FailVerifiedCipherText)}, 72 | {verify_share, eqc:equals((Fail == none orelse Fail == duplicate_shares), VerifiedShares)}, 73 | {verify_combine_shares, eqc:equals((Fail == none), Message == VerifiedCombinedShares)}, 74 | {all_shares_validate, eqc:equals((Fail == none), length(Shares) == length(ValidShares))} 75 | ])) 76 | end). 77 | 78 | gen_players_threshold() -> 79 | ?SUCHTHAT({Players, Threshold}, 80 | ?LET({X, Y}, 81 | ?SUCHTHAT({A, B}, {int(), int()}, A > 0 andalso B >= 0 andalso A > B), 82 | {X*3, X - Y}), 83 | Players > 3*Threshold+1 andalso Threshold > 1). 84 | 85 | gen_curve() -> 86 | elements(['SS512']). 87 | 88 | gen_failure_mode() -> 89 | elements([none, wrong_key, wrong_message, duplicate_shares]). 90 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018, Helium Systems Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/tpke_pubkey.erl: -------------------------------------------------------------------------------- 1 | -module(tpke_pubkey). 2 | 3 | -record(pubkey, { 4 | players :: pos_integer(), 5 | k :: non_neg_integer(), 6 | curve :: curve(), 7 | g1 :: erlang_pbc:element(), 8 | g2 :: erlang_pbc:element(), 9 | verification_key :: erlang_pbc:element(), 10 | verification_keys :: [erlang_pbc:element(), ...] 11 | }). 12 | 13 | -record(pubkey_serialized, { 14 | players :: pos_integer(), 15 | k :: non_neg_integer(), 16 | curve :: curve(), 17 | g1 :: binary(), 18 | g2 :: binary(), 19 | verification_key :: binary(), 20 | verification_keys :: [binary(), ...] 21 | }). 22 | 23 | -record(ciphertext, { 24 | u :: erlang_pbc:element(), 25 | v :: <<_:256>>, 26 | w :: erlang_pbc:element(), 27 | g1 :: erlang_pbc:element() | undefined, %% g1 of the public key this ciphertext is valid with 28 | verified = false :: boolean() %% whether we can trust this ciphertext has been verified 29 | }). 30 | 31 | -type curve() :: 'SS512' | 'MNT159' | 'MNT224'. 32 | -type pubkey() :: #pubkey{}. 33 | -type pubkey_serialized() :: #pubkey_serialized{}. 34 | -opaque ciphertext() :: #ciphertext{}. 35 | 36 | -export_type([pubkey/0, ciphertext/0, curve/0, pubkey_serialized/0]). 37 | -export([init/7, 38 | lagrange/3, 39 | encrypt/2, 40 | verify_ciphertext/2, 41 | verify_share/3, 42 | combine_shares/3, 43 | hash_message/2, 44 | verify_signature/3, 45 | combine_signature_shares/3, 46 | combine_verified_signature_shares/2, 47 | verify_signature_share/3, 48 | deserialize_element/2, 49 | verification_key/1, 50 | serialize/1, 51 | deserialize/1, 52 | check_ciphertext/2, 53 | ciphertext_to_binary/1, 54 | binary_to_ciphertext/2 55 | ]). 56 | 57 | %% Note: K can be 0 here, meaning every player is honest. 58 | -spec init(pos_integer(), non_neg_integer(), erlang_pbc:element(), erlang_pbc:element(), erlang_pbc:element(), [erlang_pbc:element(), ...], curve()) -> pubkey(). 59 | init(Players, K, G1, G2, VK, VKs, Curve) -> 60 | erlang_pbc:pairing_pp_init(G1), 61 | erlang_pbc:element_pp_init(G1), 62 | #pubkey{players=Players, k=K, verification_key=VK, verification_keys=VKs, g1=G1, g2=G2, curve=Curve}. 63 | 64 | %% Section 3.2.2 Baek and Zheng 65 | %% Epk(m): 66 | %% Note: V is a binary, this is by design in the paper. 67 | -spec encrypt(pubkey(), binary()) -> ciphertext(). 68 | encrypt(PubKey, Message) when is_binary(Message) -> 69 | 32 = byte_size(Message), 70 | %% r is randomly chosen from ZZ∗q 71 | R = erlang_pbc:element_random(erlang_pbc:element_new('Zr', PubKey#pubkey.verification_key)), 72 | %% U = rP 73 | U = erlang_pbc:element_mul(R, PubKey#pubkey.g1), 74 | %% V = G(rY)⊕m 75 | V = xor_bin(hashG(erlang_pbc:element_mul(R, PubKey#pubkey.verification_key)), Message), 76 | %% W = rH(U, V) 77 | W = erlang_pbc:element_mul(R, hashH(U, V)), 78 | %% ciphertext C = (U, V, W) 79 | #ciphertext{u=U, v=V, w=W}. 80 | 81 | %% Section 3.2.2 Baek and Zheng 82 | %% common code to verify ciphertext is valid 83 | -spec verify_ciphertext(pubkey(), ciphertext()) -> {ok, ciphertext()} | error. 84 | verify_ciphertext(PubKey, #ciphertext{u=U, v=V, w=W}=CipherText) -> 85 | %% H = H(U, V) 86 | H = hashH(U, V), 87 | %% check if ˆe(P, W) = ˆe(U, H) 88 | case erlang_pbc:element_cmp(erlang_pbc:element_pairing(PubKey#pubkey.g1, W), 89 | erlang_pbc:element_pairing(U, H)) of 90 | true -> 91 | {ok, CipherText#ciphertext{verified=true, g1=PubKey#pubkey.g1}}; 92 | false -> 93 | error 94 | end. 95 | 96 | %% Section 3.2.2 Baek and Zheng 97 | %% Vvk(C, Di): 98 | -spec verify_share(pubkey(), tpke_privkey:share(), ciphertext()) -> boolean(). 99 | verify_share(PubKey, {Index, Share}, CipherText) -> 100 | {U, _V, _W} = check_ciphertext(PubKey, CipherText), 101 | true = 0 =< Index andalso Index < PubKey#pubkey.players, 102 | %% check if ˆe(P, Ui) = ˆe(U, Yi). 103 | Yi = lists:nth(Index+1, PubKey#pubkey.verification_keys), 104 | erlang_pbc:element_cmp(erlang_pbc:element_pairing(PubKey#pubkey.g2, Share), 105 | erlang_pbc:element_pairing(U, Yi)). 106 | 107 | %% Section 3.2.2 Baek and Zheng 108 | %% SCvk(C,{Di}i∈Φ): 109 | -spec combine_shares(pubkey(), ciphertext(), [tpke_privkey:share(), ...]) -> binary() | undefined. 110 | combine_shares(PubKey, CipherText, Shares) -> 111 | {_U, V, _W} = check_ciphertext(PubKey, CipherText), 112 | {Indices, _} = lists:unzip(Shares), 113 | Set = ordsets:from_list(Indices), 114 | MySet = ordsets:from_list(lists:seq(0, PubKey#pubkey.players - 1)), 115 | true = ordsets:is_subset(Set, MySet), 116 | 117 | %% m=G(∑i∈ΦλΦ0iUi)⊕V 118 | Bleh = [ erlang_pbc:element_pow(Share, lagrange(PubKey, Set, Index)) || {Index, Share} <- Shares], 119 | Res = lists:foldl(fun(E, Acc) -> 120 | erlang_pbc:element_mul(Acc, E) 121 | end, hd(Bleh), tl(Bleh)), 122 | xor_bin(hashG(Res), V). 123 | 124 | %% Section 3.1 Boldyreva 125 | %% Decisional Diffie-Hellman (DDH) problem. 126 | -spec verify_signature_share(pubkey(), tpke_privkey:share(), erlang_pbc:element()) -> boolean(). 127 | verify_signature_share(PubKey, {Index, Share}, HM) -> 128 | true = 0 =< Index andalso Index < PubKey#pubkey.players, 129 | Y = lists:nth(Index+1, PubKey#pubkey.verification_keys), 130 | %% In order to verify the validity of a candidate signature σ of a messageM, 131 | %% a verifier simply checks whether (g,y,H(M),σ) is a valid Diffie-Hellman tuple. 132 | %% Given (g,g^x,g^y,g^z) it is possible to check z=xy if e(g,g^z) == e(g^x,g^y) 133 | erlang_pbc:element_cmp(erlang_pbc:element_pairing(PubKey#pubkey.g2, Share), 134 | erlang_pbc:element_pairing(Y, HM)). 135 | 136 | %% Section 3.2 Boldyrevya 137 | %% V(pk,M,σ) : 138 | -spec verify_signature(pubkey(), erlang_pbc:element(), erlang_pbc:element()) -> boolean(). 139 | verify_signature(PubKey, Signature, H) -> 140 | %% VDDH(g,y,H(M),σ) 141 | %% VDDH(g,pkL,H(M),σ) 142 | A = erlang_pbc:element_pairing(Signature, PubKey#pubkey.g2), 143 | B = erlang_pbc:element_pairing(H, PubKey#pubkey.verification_key), 144 | erlang_pbc:element_cmp(A, B). 145 | 146 | -spec combine_signature_shares(pubkey(), [tpke_privkey:share(), ...], binary() | erlang_pbc:element()) -> {ok, erlang_pbc:element()} | {error, bad_signature_share}. 147 | combine_signature_shares(PubKey, Shares, Msg) when is_binary(Msg) -> 148 | combine_signature_shares(PubKey, Shares, hash_message(PubKey, Msg)); 149 | combine_signature_shares(PubKey, Shares, HM) -> 150 | {Indices, _} = lists:unzip(Shares), 151 | Set = ordsets:from_list(Indices), 152 | MySet = ordsets:from_list(lists:seq(0, PubKey#pubkey.players - 1)), 153 | true = ordsets:is_subset(Set, MySet), 154 | 155 | case lists:all(fun({Index, Share}) -> verify_signature_share(PubKey, {Index, Share}, HM) end, Shares) of 156 | true -> 157 | %% pkL= Πj∈J(pkj) =Πj∈J(gxj) 158 | Bleh = [ erlang_pbc:element_pow(Share, lagrange(PubKey, Set, Index)) || {Index, Share} <- Shares], 159 | Res = lists:foldl(fun(E, Acc) -> 160 | erlang_pbc:element_mul(E, Acc) 161 | end, hd(Bleh), tl(Bleh)), 162 | erlang_pbc:pairing_pp_init(Res), 163 | {ok, Res}; 164 | false -> 165 | {error, bad_signature_share} 166 | end. 167 | 168 | %% if you've verified the shares as you've received them and don't need/want to reverify them 169 | -spec combine_verified_signature_shares(pubkey(), [tpke_privkey:share(), ...]) -> {ok, erlang_pbc:element()}. 170 | combine_verified_signature_shares(PubKey, Shares) -> 171 | {Indices, _} = lists:unzip(Shares), 172 | Set = ordsets:from_list(Indices), 173 | MySet = ordsets:from_list(lists:seq(0, PubKey#pubkey.players - 1)), 174 | true = ordsets:is_subset(Set, MySet), 175 | 176 | %% pkL= Πj∈J(pkj) =Πj∈J(gxj) 177 | Bleh = [ erlang_pbc:element_pow(Share, lagrange(PubKey, Set, Index)) || {Index, Share} <- Shares], 178 | Res = lists:foldl(fun(E, Acc) -> 179 | erlang_pbc:element_mul(E, Acc) 180 | end, hd(Bleh), tl(Bleh)), 181 | erlang_pbc:pairing_pp_init(Res), 182 | {ok, Res}. 183 | 184 | %% H(M) 185 | -spec hash_message(pubkey(), binary()) -> erlang_pbc:element(). 186 | hash_message(PubKey, Msg) -> 187 | Res = erlang_pbc:element_from_hash(erlang_pbc:element_new('G1', PubKey#pubkey.verification_key), Msg), 188 | erlang_pbc:element_pp_init(Res), 189 | erlang_pbc:pairing_pp_init(Res), 190 | Res. 191 | 192 | 193 | -spec deserialize_element(pubkey(), binary()) -> erlang_pbc:element(). 194 | deserialize_element(PubKey, Binary) when is_binary(Binary) -> 195 | erlang_pbc:binary_to_element(PubKey#pubkey.verification_key, Binary). 196 | 197 | 198 | -spec lagrange(pubkey(), ordsets:ordset(non_neg_integer()), non_neg_integer()) -> erlang_pbc:element(). 199 | lagrange(PubKey, Set, Index) -> 200 | true = ordsets:is_set(Set), 201 | %true = PubKey#pubkey.k == ordsets:size(Set), 202 | MySet = ordsets:from_list(lists:seq(0, PubKey#pubkey.players - 1)), 203 | true = ordsets:is_subset(Set, MySet), 204 | 205 | true = ordsets:is_element(Index, Set), 206 | true = 0 =< Index andalso Index < PubKey#pubkey.players, 207 | 208 | One = erlang_pbc:element_set(erlang_pbc:element_new('Zr', PubKey#pubkey.verification_key), 1), 209 | 210 | Num = lists:foldl(fun(E, Acc) -> 211 | erlang_pbc:element_mul(Acc, E) 212 | end, One, [ 0 - JJ - 1 || JJ <- ordsets:to_list(Set), JJ /= Index]), 213 | 214 | Den = lists:foldl(fun(E, Acc) -> 215 | erlang_pbc:element_mul(Acc, E) 216 | end, One, [ Index - JJ || JJ <- ordsets:to_list(Set), JJ /= Index]), 217 | 218 | erlang_pbc:element_div(Num, Den). 219 | 220 | -spec hashG(erlang_pbc:element()) -> binary(). 221 | hashG(G) -> 222 | crypto:hash(sha256, erlang_pbc:element_to_binary(G)). 223 | 224 | -spec hashH(erlang_pbc:element(), binary()) -> erlang_pbc:element(). 225 | hashH(G, X) -> 226 | 32 = byte_size(X), 227 | erlang_pbc:element_from_hash(erlang_pbc:element_new('G2', G), list_to_binary([erlang_pbc:element_to_binary(G), X])). 228 | 229 | -spec xor_bin(binary(), binary()) -> binary(). 230 | xor_bin(A, B) -> 231 | 32 = byte_size(A), 232 | 32 = byte_size(B), 233 | xor_bin(A, B, []). 234 | 235 | -spec xor_bin(binary(), binary(), [byte()]) -> binary(). 236 | xor_bin(<<>>, <<>>, Acc) -> 237 | list_to_binary(lists:reverse(Acc)); 238 | xor_bin(<>, <>, Acc) -> 239 | xor_bin(T1, T2, [A bxor B | Acc]). 240 | 241 | -spec verification_key(pubkey()) -> erlang_pbc:element(). 242 | verification_key(Pubkey) -> 243 | Pubkey#pubkey.verification_key. 244 | 245 | -spec serialize(pubkey()) -> pubkey_serialized(). 246 | serialize(#pubkey{players=Players, k=K, curve=Curve, g1=G1, g2=G2, verification_key=VK, verification_keys=VKs}) -> 247 | #pubkey_serialized{players=Players, 248 | k=K, 249 | curve=Curve, 250 | g1=erlang_pbc:element_to_binary(G1), 251 | g2=erlang_pbc:element_to_binary(G2), 252 | verification_key=erlang_pbc:element_to_binary(VK), 253 | verification_keys=[erlang_pbc:element_to_binary(V) || V <- VKs]}. 254 | 255 | -spec deserialize(pubkey_serialized()) -> pubkey(). 256 | deserialize(#pubkey_serialized{players=Players, k=K, curve=Curve, g1=G1, g2=G2, verification_key=VK, verification_keys=VKs}) -> 257 | Group = erlang_pbc:group_new(Curve), 258 | Element = erlang_pbc:element_new('G1', Group), 259 | #pubkey{players=Players, 260 | k=K, 261 | curve=Curve, 262 | g1=erlang_pbc:binary_to_element(Element, G1), 263 | g2=erlang_pbc:binary_to_element(Element, G2), 264 | verification_key=erlang_pbc:binary_to_element(Element, VK), 265 | verification_keys=[erlang_pbc:binary_to_element(Element, V) || V <- VKs]}. 266 | 267 | -spec check_ciphertext(pubkey(), ciphertext()) -> {U::erlang_pbc:element(), V::<<_:256>>, W::erlang_pbc:element()}. 268 | check_ciphertext(_PubKey, #ciphertext{verified=false}) -> 269 | erlang:error(unverified_ciphertext); 270 | check_ciphertext(#pubkey{g1=KG1}, #ciphertext{verified=true, g1=CG1, u=U, v=V, w=W}) -> 271 | %% check if they're the same reference or the same value 272 | %% reference comparisons are cheaper so do those first 273 | case CG1 == KG1 orelse erlang_pbc:element_cmp(CG1, KG1) of 274 | true -> 275 | {U, V, W}; 276 | false -> 277 | erlang:error(inconsistent_ciphertext) 278 | end. 279 | 280 | -spec ciphertext_to_binary(ciphertext()) -> binary(). 281 | ciphertext_to_binary(#ciphertext{u=U, v=V, w=W}) -> 282 | UBin = erlang_pbc:element_to_binary(U), 283 | USize = byte_size(UBin), 284 | WBin = erlang_pbc:element_to_binary(W), 285 | WSize = byte_size(WBin), 286 | <>. 287 | 288 | -spec binary_to_ciphertext(binary(), tpke_pubkey:pubkey()) -> ciphertext(). 289 | binary_to_ciphertext(<>, PubKey) -> 290 | U = tpke_pubkey:deserialize_element(PubKey, UBin), 291 | W = tpke_pubkey:deserialize_element(PubKey, WBin), 292 | case verify_ciphertext(PubKey, #ciphertext{u=U, v=V, w=W}) of 293 | {ok, CipherText} -> 294 | CipherText; 295 | error -> 296 | erlang:error(inconsistent_ciphertext) 297 | end. 298 | --------------------------------------------------------------------------------