Пример #1
0
def Ct_dec_unit_test():
    try:    
        G = EcGroup()
        x_1 = G.order().random()
        y_1 = x_1 * G.generator()
    
        x_2 = G.order().random()
        y_2 = x_2 * G.generator()

        x_3 = G.order().random()
        y_3 = x_3 * G.generator()
    
        #
        E1 = Ct.enc(y_1+y_2, 2)
        E = copy(E1)
        E.b = E1.partial_dec(x_1)
        
        
        #
        E3 = Ct.enc(y_1, 22)
        E4 = Ct.enc(y_2+y_3, E3)
        E5 = copy(E4)
        E5.b = E4.partial_dec(x_1)
        
        return ((E.dec(x_2) == 2) and (E1.dec(x_1+x_2) == 2) and (E5.dec(x_2+x_3)==22))
        
    except Exception:
        return False
Пример #2
0
def test_fails():
    G, priv_dec, pub_enc = dh_get_key()
    message = u"Hello World!"
    ciphertext = dh_encrypt(pub_enc, message)
    iv, real_ciphertext, tag, pub_enc = ciphertext

    # Test for random iv
    with raises(Exception) as excinfo:
        rand_iv = urandom(16), real_ciphertext, tag, pub_enc
        dh_decrypt(priv_dec, rand_iv)
    assert 'decryption failed' in str(excinfo.value)

    # Test for random tag
    with raises(Exception) as excinfo:
        rand_tag = iv, real_ciphertext, urandom(16), pub_enc
        dh_decrypt(priv_dec, rand_tag)
    assert 'decryption failed' in str(excinfo.value)

    # Test for random public key
    with raises(Exception) as excinfo:
        G = EcGroup()
        rand_dec = G.order().random()
        rand_p = rand_dec * G.generator()
        rand_pub = iv, real_ciphertext, tag, rand_p
        dh_decrypt(priv_dec, rand_pub)
    assert 'decryption failed' in str(excinfo.value)

    # Test for a random private_key
    with raises(Exception) as excinfo:
        dh_decrypt(EcGroup().order().random(), ciphertext)
    assert 'decryption failed' in str(excinfo.value)
Пример #3
0
def time_scalar_mul():
    # setup curve
    G = EcGroup(713)  # NIST curve
    d = G.parameters()
    a, b, p = d["a"], d["b"], d["p"]
    g = G.generator()
    gx0, gy0 = g.get_affine()
    order = G.order()

    r = order.random()

    gx2, gy2 = (r * g).get_affine()

    # First a value with low hamming weight
    scalar_1 = Bn.from_hex('11111111111111111111111111111111111111111')

    # The second scalar value with a much higher hamming weight
    scalar_2 = Bn.from_hex('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
    # Scalar values with higher hamming weight will take longer to
    # compute the multiplication of.
    t1 = time.clock()
    x2, y2 = point_scalar_multiplication_double_and_add(
        a, b, p, gx0, gy0, scalar_1)
    t2 = time.clock()
    runtime = t2 - t1
    print("Runtime for scalar 1: " + str(runtime))

    t1 = time.clock()
    x2, y2 = point_scalar_multiplication_double_and_add(
        a, b, p, gx0, gy0, scalar_2)
    t2 = time.clock()
    runtime = t2 - t1
    print("Runtime for scalar 2: " + str(runtime))
Пример #4
0
    def helper_function_reconstruct(self, t, n):
        Gq = EcGroup()
        p = Gq.order()
        g = Gq.generator()
        G = Gq.hash_to_point(b'G')
        params = (Gq, p, g, G)

        # Decide on a secret to be distributed
        m = p.from_binary(b'This is a test')

        # Initiate participants, and generate their key-pairs
        priv_keys = []
        pub_keys = []
        for i in range(n):
            (x_i, y_i) = pvss.helper_generate_key_pair(params)
            priv_keys.append(x_i)
            pub_keys.append(y_i)

        # Encrypt secret, create shares and proof
        (pub, proof) = pvss.gen_proof(params, t, n, m, pub_keys)

        # Decryption
        # Calculate what a correct decryption should be
        expected_decryption = m * g

        # Let participants decrypt their shares and generate proofs
        proved_decryptions = [
            pvss.participant_decrypt_and_prove(params, x_i, enc_share)
            for (x_i, enc_share) in zip(priv_keys, pub['Y_list'])
        ]
        if pvss.batch_verify_correct_decryption(
                proved_decryptions, pub['Y_list'], pub_keys, p, G) is False:
            print("Verification of decryption failed")
        S_list = [S_i for (S_i, decrypt_proof) in proved_decryptions]
        return (expected_decryption, S_list, p)
Пример #5
0
def mix_client_n_hop(public_keys, address, message, use_blinding_factor=False):
    """
    Encode a message to travel through a sequence of mixes with a sequence public keys. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 

    The implementation of the blinding factor is optional and therefore only activated 
    in the bonus tests. It can be ignored for the standard task.
    If you implement the bonus task make sure to only activate it if use_blinding_factor is True.
    """
    G = EcGroup()
    # assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # use those encoded values as the payload you encrypt!
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key = private_key * G.generator()

    #TODO ADD CODE HERE

    return NHopMixMessage(client_public_key, hmacs, address_cipher,
                          message_cipher)
Пример #6
0
def setup():
    ''' Setup the parameters of the mix crypto-system '''
    G = EcGroup()
    o = G.order()
    g = G.generator()
    o_bytes = int(math.ceil(math.log(float(int(o))) / math.log(256)))
    return G, o, g, o_bytes
Пример #7
0
def setup():
    """ Generates parameters for Commitments """
    G = EcGroup()
    g = G.hash_to_point(b'g')
    h = G.hash_to_point(b'h')
    o = G.order()
    return (G, g, h, o)
Пример #8
0
    def test_gen_polynomial(self):
        Gq = EcGroup()
        p = Gq.order()

        px = pvss.gen_polynomial(3, 42, p)
        for pi in px:
            assert pi < p
Пример #9
0
def _make_table(start=conf.LOWER_LIMIT, end=conf.UPPER_LIMIT):
    G = EcGroup(nid=713)
    g = G.generator()
    o = G.order()

    i_table = {}
    n_table = {}
    ix = start * g
	
    trunc_limit = conf.TRUNC_LIMIT
	
    for i in range(start, end):
        #i_table[str(ix)] = str(i) #Uncompressed
        #Compression trick
        trunc_ix = str(ix)[:trunc_limit]
        #print ix
        #print trunc_ix
        if trunc_ix in i_table:
            i_table[trunc_ix] = i_table[trunc_ix] + "," + str(i)
        else:
            i_table[trunc_ix] = str(i)
        
        
        n_table[str((o + i) % o)] = str(ix)
        ix = ix + g
        #print type(ix)
        #print type(ix.export())
        
    print "size: " + str(len(i_table))
    return i_table, n_table
Пример #10
0
def test_timings():
    # Make 100 keys
    G = EcGroup()

    keys = []
    for _ in range(100):
        sec = G.order().random()
        k = Key(sec.binary(), False)
        # bpub, bsec = k.export()
        keys += [k]

    msg = urandom(32)

    # time sign
    t0 = timer()
    sigs = []
    for i in range(1000):
        sigs += [(keys[i % 100], keys[i % 100].sign(msg))]
    t1 = timer()
    print "\nSign rate: %2.2f / sec" % (1.0 / ((t1-t0)/1000.0))

    # time verify
    t0 = timer()
    for k, sig in sigs:
        assert k.verify(msg, sig)
    t1 = timer()
    print "Verify rate: %2.2f / sec" % (1.0 / ((t1-t0)/1000.0))

    # time hash
    t0 = timer()
    for _ in range(10000):
        sha256(msg).digest()
    t1 = timer()
    print "Hash rate: %2.2f / sec" % (1.0 / ((t1-t0)/10000.0))
Пример #11
0
def setup():
    """ generate all public parameters """
    G = EcGroup()
    o = G.order()
    g = G.generator()
    h = G.hash_to_point("mac_ggm".encode("utf8"))
    return (G, o, g, h)
Пример #12
0
def test_Pedersen_Shorthand():

    # Define an EC group
    G = EcGroup(713)
    order = G.order()

    ## Proof definitions
    zk = ZKProof(G)
    zk.g, zk.h = ConstGen, ConstGen
    zk.x, zk.o = Sec, Sec
    zk.Cxo = Gen
    zk.add_proof(zk.Cxo, zk.x*zk.g + zk.o*zk.h)

    print(zk.render_proof_statement())

    # A concrete Pedersen commitment
    ec_g = G.generator()
    ec_h = order.random() * ec_g
    bn_x = order.random()
    bn_o = order.random()
    ec_Cxo = bn_x * ec_g + bn_o * ec_h

    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h 
    env.Cxo = ec_Cxo
    env.x = bn_x 
    env.o = bn_o

    sig = zk.build_proof(env.get())

    # Execute the verification
    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h 

    assert zk.verify_proof(env.get(), sig)
Пример #13
0
def setup():
    """ Generates parameters for Commitments """
    G = EcGroup()
    g = G.hash_to_point(b'g')
    h = G.hash_to_point(b'h')
    o = G.order()
    return (G, g, h, o)
Пример #14
0
def setup():
    """Generates the Cryptosystem Parameters."""
    G = EcGroup(nid=713)
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()
    return (G, g, h, o)
Пример #15
0
def test_Alice_encode_3_hop():
    """
    Test sending a multi-hop message through 1-hop
    """

    from os import urandom

    G = EcGroup()
    g = G.generator()
    o = G.order()

    private_keys = [o.random() for _ in range(3)]
    public_keys  = [pk * g for pk in private_keys]

    address = b"Alice"
    message = b"Dear Alice,\nHello!\nBob"

    m1 = mix_client_n_hop(public_keys, address, message)
    out = mix_server_n_hop(private_keys[0], [m1])
    out = mix_server_n_hop(private_keys[1], out)
    out = mix_server_n_hop(private_keys[2], out, final=True)

    assert len(out) == 1
    assert out[0][0] == address
    assert out[0][1] == message
Пример #16
0
def test_Pedersen_Shorthand():

    # Define an EC group
    G = EcGroup(713)
    order = G.order()

    ## Proof definitions
    zk = ZKProof(G)
    zk.g, zk.h = ConstGen, ConstGen
    zk.x, zk.o = Sec, Sec
    zk.Cxo = Gen
    zk.add_proof(zk.Cxo, zk.x * zk.g + zk.o * zk.h)

    print(zk.render_proof_statement())

    # A concrete Pedersen commitment
    ec_g = G.generator()
    ec_h = order.random() * ec_g
    bn_x = order.random()
    bn_o = order.random()
    ec_Cxo = bn_x * ec_g + bn_o * ec_h

    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h
    env.Cxo = ec_Cxo
    env.x = bn_x
    env.o = bn_o

    sig = zk.build_proof(env.get())

    # Execute the verification
    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h

    assert zk.verify_proof(env.get(), sig)
Пример #17
0
def setup_ggm(nid = 713):
    """Generates the parameters for an EC group nid"""
    G = EcGroup(nid)
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()
    return (G, g, h, o)
Пример #18
0
def mix_client_n_hop(public_keys, address, message, use_blinding_factor=False):
    """
    Encode a message to travel through a sequence of mixes with a sequence public keys. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 

    The implementation of the blinding factor is optional and therefore only activated 
    in the bonus tests. It can be ignored for the standard task.
    If you implement the bonus task make sure to only activate it if use_blinding_factor is True.
    """
    G = EcGroup()
    # assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # use those encoded values as the payload you encrypt!
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key  = private_key * G.generator()

    #TODO ADD CODE HERE

    return NHopMixMessage(client_public_key, hmacs, address_cipher, message_cipher)
Пример #19
0
def execute_Alice_encode_hop(hops, use_blinding_factor=False):
    """
    Test sending a multi-hop message through 1-hop
    """

    from os import urandom

    G = EcGroup()
    g = G.generator()
    o = G.order()

    private_keys = [o.random() for _ in range(hops)]
    public_keys = [pk * g for pk in private_keys]

    address = b"Alice"
    message = b"Dear Alice,\nHello!\nBob"

    # Execute the encoding with the client implementation
    m1 = mix_client_n_hop(public_keys, address, message, use_blinding_factor)

    # Walk through the hops with the server implementation
    out = [m1]
    for hop in range(0, hops - 1):
        out = mix_server_n_hop(private_keys[hop], out, use_blinding_factor)
    out = mix_server_n_hop(private_keys[hops - 1], out, use_blinding_factor, final=True)

    # Check the result
    assert len(out) == 1
    assert out[0][0] == address
    assert out[0][1] == message
Пример #20
0
def setup():
    """ Generates the Cryptosystem Parameters. """
    G = EcGroup(nid=713)
    g = G.hash_to_point(b"g")
    hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(4)]
    o = G.order()
    return (G, g, hs, o)
Пример #21
0
def _make_table(trunc_limit, start=conf.LOWER_LIMIT, end=conf.UPPER_LIMIT):
    G = EcGroup(nid=713)
    g = G.generator()
    o = G.order()

    i_table = {}
    n_table = {}
    ix = start * g
	
    print "Generating db with truc: " + str(trunc_limit)
    #trunc_limit = conf.TRUNC_LIMIT
	
    for i in range(start, end):
        #i_table[str(ix)] = str(i) #Uncompressed
        #Compression trick
        trunc_ix = str(ix)[:trunc_limit]
        #print ix
        #print trunc_ix
        if trunc_ix in i_table:
            i_table[trunc_ix] = i_table[trunc_ix] + "," + str(i)
        else:
            i_table[trunc_ix] = str(i)
        
        
        n_table[str((o + i) % o)] = str(ix)
        ix = ix + g
        #print type(ix)
        #print type(ix.export())
        
    print "size: " + str(len(i_table))
    return i_table, n_table
Пример #22
0
def setup():
    ''' Setup the parameters of the mix crypto-system '''
    group = EcGroup()
    order = group.order()
    generator = group.generator()
    o_bytes = int(math.ceil(math.log(float(int(order))) / math.log(256)))
    return group, order, generator, o_bytes
Пример #23
0
def setup():
    ''' Setup the parameters of the mix crypto-system '''
    G = EcGroup()
    o = G.order()
    g = G.generator()
    o_bytes = int(math.ceil(math.log(float(int(o))) / math.log(256)))
    return G, o, g, o_bytes
Пример #24
0
def setup_ggm(nid=713):
    """Generates the parameters for an EC group nid"""
    G = EcGroup(nid)
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()
    return (G, g, h, o)
Пример #25
0
def mix_client_n_hop(public_keys, address, message):
    """
    Encode a message to travel through a sequence of mixes with a sequence public keys. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 

    """
    G = EcGroup()
    # assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # use those encoded values as the payload you encrypt!
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key  = private_key * G.generator()

    ## ADD CODE HERE

    return NHopMixMessage(client_public_key, hmacs, address_cipher, message_cipher)
Пример #26
0
def test_broad():
    G = EcGroup()
    g = G.generator()
    x = G.order().random()

    a, puba = pair(G)
    b, pubb = pair(G)
    c, pubc = pair(G)
    a2, puba2 = pair(G)
    b2, pubb2 = pair(G)
    c2, pubc2 = pair(G)

    pki = {"a":(puba,puba2) , "b":(pubb, pubb2), "c":(pubc, pubc2)}
    client = KulanClient(G, "me", x, pki)

    msgs = client.broadcast_encrypt(b"Hello!")

    pki2 = {"me": x * g, "b":(pubb, pubb2), "c":(pubc, pubc2)}
    dec_client = KulanClient(G, "a", a, pki2)

    dec_client.priv_enc = a2
    dec_client.pub_enc = puba2

    namex, keysx = dec_client.broadcast_decrypt(msgs)
    assert namex == "me"
    # print msgs
Пример #27
0
def test_steady():
    G = EcGroup()
    g = G.generator()
    x = G.order().random()
    pki = {"me": (x * g, x * g)}
    client = KulanClient(G, "me", x, pki)

    ## Mock some keys
    client.Ks += [bytes(urandom(16))]

    # Decrypt a small message
    ciphertext = client.steady_encrypt(b"Hello World!")
    client.steady_decrypt(ciphertext)

    # Decrypt a big message
    ciphertext = client.steady_encrypt(b"Hello World!" * 10000)
    client.steady_decrypt(ciphertext)

    # decrypt an empty string
    ciphertext = client.steady_encrypt(b"")
    client.steady_decrypt(ciphertext)

    # Time it
    import time
    t0 = time.clock()
    for _ in range(1000):
        ciphertext = client.steady_encrypt(b"Hello World!" * 10)
        client.steady_decrypt(ciphertext)
    t = time.clock() - t0

    print()
    print(" - %2.2f operations / sec" % (1.0 / (t / 1000)))
Пример #28
0
def time_scalar_mul():
    import time, pprint

    G = EcGroup()
    d = G.parameters()
    a, b, p = d["a"], d["b"], d["p"]
    g = G.generator()
    x, y = g.get_affine()
    scalars = G.order().hex()
    results = []

    for i in range(0, len(scalars), 3):
        r = Bn.from_hex(scalars[:i+1])
        start = time.clock()
        point_scalar_multiplication_double_and_add(a, b, p, x, y, r)
        elapsed = (time.clock() - start)
        results.append((r, elapsed))
    pp = pprint.PrettyPrinter(indent=2, width=160)
    pp.pprint(results)

    for i in range(0, len(scalars), 3):
        r = Bn.from_hex(scalars[:i+1])
        start = time.clock()
        point_scalar_multiplication_montgomerry_ladder(a, b, p, x, y, r)
        elapsed = (time.clock() - start)
        results.append((r, elapsed))
    pp = pprint.PrettyPrinter(indent=2, width=160)
    pp.pprint(results)
Пример #29
0
def test_broad():
    G = EcGroup()
    g = G.generator()
    x = G.order().random()

    a, puba = pair(G)
    b, pubb = pair(G)
    c, pubc = pair(G)
    a2, puba2 = pair(G)
    b2, pubb2 = pair(G)
    c2, pubc2 = pair(G)

    pki = {"a": (puba, puba2), "b": (pubb, pubb2), "c": (pubc, pubc2)}
    client = KulanClient(G, "me", x, pki)

    msgs = client.broadcast_encrypt(b"Hello!")

    pki2 = {"me": x * g, "b": (pubb, pubb2), "c": (pubc, pubc2)}
    dec_client = KulanClient(G, "a", a, pki2)

    dec_client.priv_enc = a2
    dec_client.pub_enc = puba2

    namex, keysx = dec_client.broadcast_decrypt(msgs)
    assert namex == "me"
Пример #30
0
def test_Pedersen():

    # Define an EC group
    G = EcGroup(713)
    order = G.order()

    ## Proof definitions
    zk = ZKProof(G)
    g, h = zk.get(ConstGen, ["g", "h"])
    x, o = zk.get(Sec, ["x", "o"])
    Cxo = zk.get(Gen, "Cxo")
    zk.add_proof(Cxo, x * g + o * h)

    # A concrete Pedersen commitment
    ec_g = G.generator()
    ec_h = order.random() * ec_g
    bn_x = order.random()
    bn_o = order.random()
    ec_Cxo = bn_x * ec_g + bn_o * ec_h

    # Execute the proof
    env = {"g": ec_g, "h": ec_h, "Cxo": ec_Cxo, "x": bn_x, "o": bn_o}
    sig = zk.build_proof(env)

    # Execute the verification
    env_verify = {"g": ec_g, "h": ec_h}

    assert zk.verify_proof(env_verify, sig)
Пример #31
0
def setup():
    """Generates the Cryptosystem Parameters."""
    G = EcGroup(nid=713)
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()
    return (G, g, h, o)
Пример #32
0
def mix_client_one_hop(public_key, address, message):
    """
    Encode a message to travel through a single mix with a set public key. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'OneHopMixMessage' with four parts: a public key, an hmac (20 bytes),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 
    """

    G = EcGroup()
    assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # Use those as the payload for encryption
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key = private_key * G.generator()

    ## ADD CODE HERE

    return OneHopMixMessage(client_public_key, expected_mac, address_cipher,
                            message_cipher)
Пример #33
0
def mix_client_n_hop(public_keys, address, message):
    """
    Encode a message to travel through a sequence of mixes with a sequence public keys. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 

    """
    G = EcGroup()
    # assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # use those encoded values as the payload you encrypt!
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key = private_key * G.generator()

    ## ADD CODE HERE

    return NHopMixMessage(client_public_key, hmacs, address_cipher,
                          message_cipher)
Пример #34
0
def test_Pedersen_Env():

    # Define an EC group
    G = EcGroup(713)
    order = G.order()

    ## Proof definitions
    zk = ZKProof(G)
    g, h = zk.get(ConstGen, ["g", "h"])
    x, o = zk.get(Sec, ["x", "o"])
    Cxo = zk.get(Gen, "Cxo")
    zk.add_proof(Cxo, x*g + o*h)

    # A concrete Pedersen commitment
    ec_g = G.generator()
    ec_h = order.random() * ec_g
    bn_x = order.random()
    bn_o = order.random()
    ec_Cxo = bn_x * ec_g + bn_o * ec_h

    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h 
    env.Cxo = ec_Cxo
    env.x = bn_x 
    env.o = bn_o

    sig = zk.build_proof(env.get())

    # Execute the verification
    env = ZKEnv(zk)
    env.g, env.h = ec_g, ec_h 

    assert zk.verify_proof(env.get(), sig)
Пример #35
0
def mix_client_one_hop(public_key, address, message):
    """
    Encode a message to travel through a single mix with a set public key. 
    The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively.
    Returns an 'OneHopMixMessage' with four parts: a public key, an hmac (20 bytes),
    an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). 
    """

    G = EcGroup()
    assert G.check_point(public_key)
    assert isinstance(address, bytes) and len(address) <= 256
    assert isinstance(message, bytes) and len(message) <= 1000

    # Encode the address and message
    # Use those as the payload for encryption
    address_plaintext = pack("!H256s", len(address), address)
    message_plaintext = pack("!H1000s", len(message), message)

    ## Generate a fresh public key
    private_key = G.order().random()
    client_public_key  = private_key * G.generator()

    #TODO ADD CODE HERE
    
    return OneHopMixMessage(client_public_key, expected_mac, address_cipher, message_cipher)
Пример #36
0
def test_steady():
    G = EcGroup()
    g = G.generator()
    x = G.order().random()
    pki = {"me":(x * g, x * g)}
    client = KulanClient(G, "me", x, pki)

    ## Mock some keys
    client.Ks += [bytes(urandom(16))]

    # Decrypt a small message
    ciphertext = client.steady_encrypt(b"Hello World!")
    client.steady_decrypt(ciphertext)

    # Decrypt a big message
    ciphertext = client.steady_encrypt(b"Hello World!"*10000)
    client.steady_decrypt(ciphertext)

    # decrypt an empty string
    ciphertext = client.steady_encrypt(b"")
    client.steady_decrypt(ciphertext)

    # Time it
    import time
    t0 = time.clock()
    for _ in range(1000):
        ciphertext = client.steady_encrypt(b"Hello World!"*10)
        client.steady_decrypt(ciphertext)
    t = time.clock() - t0

    print()
    print(" - %2.2f operations / sec" % (1.0 / (t / 1000)))
def test_Point_scalar_mult_montgomerry_ladder():
    """
    Test the scalar multiplication using double and add.
    """

    from pytest import raises
    from petlib.ec import EcGroup, EcPt
    G = EcGroup(713)  # NIST curve
    d = G.parameters()
    a, b, p = d["a"], d["b"], d["p"]
    g = G.generator()
    gx0, gy0 = g.get_affine()

    r = G.order().random()

    gx2, gy2 = (r * g).get_affine()

    from Lab01Code import is_point_on_curve
    from Lab01Code import point_scalar_multiplication_montgomerry_ladder

    x2, y2 = point_scalar_multiplication_montgomerry_ladder(
        a, b, p, gx0, gy0, r)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert gx2 == x2
    assert gy2 == y2
def ecdsa_key_gen():
    """ Returns an EC group, a random private key for signing 
        and the corresponding public key for verification"""
    G = EcGroup()
    priv_sign = G.order().random()
    pub_verify = priv_sign * G.generator()
    return (G, priv_sign, pub_verify)
Пример #39
0
def ecdsa_key_gen():
    """ Returns an EC group, a random private key for signing 
        and the corresponding public key for verification"""
    G = EcGroup()
    priv_sign = G.order().random()
    pub_verify = priv_sign * G.generator()
    return (G, priv_sign, pub_verify)
Пример #40
0
def setup(nid=713):
    """ generates cryptosystem parameters """
    G = EcGroup(nid)
    g = G.generator()
    hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(4)]
    o = G.order()
    return (G, g, hs, o)
Пример #41
0
def test_Alice_encode_15_hop():
    """
    Test sending a multi-hop message through 1-hop
    """

    from os import urandom

    G = EcGroup()
    g = G.generator()
    o = G.order()

    private_keys = [o.random() for _ in range(15)]
    public_keys = [pk * g for pk in private_keys]

    address = b"Alice"
    message = b"Dear Alice,\nHello!\nBob"

    m1 = mix_client_n_hop(public_keys, address, message)
    out = mix_server_n_hop(private_keys[0], [m1])
    for i in range(13):
        out = mix_server_n_hop(private_keys[i + 1], out)

    out = mix_server_n_hop(private_keys[14], out, final=True)

    assert len(out) == 1
    assert out[0][0] == address
    assert out[0][1] == message
Пример #42
0
def setup():
    """ Generates the Cryptosystem Parameters. """
    G = EcGroup(nid=713)
    g = G.hash_to_point(b"g")
    hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(4)]
    o = G.order()
    return (G, g, hs, o)
Пример #43
0
def credential_setup():
    """ Generates the parameters of the algebraic MAC scheme"""
    G = EcGroup()
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()

    params = (G, g, h, o)
    return params
def credential_setup():
    """ Generates the parameters of the algebraic MAC scheme"""
    G = EcGroup()
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    o = G.order()

    params = (G, g, h, o)
    return params
Пример #45
0
def test_fails():
    from pytest import raises

    test_mesage = "This is a test message"
    G, bob_priv, bob_pub = dh_get_key()
    alice_pub, iv, encrypted_text, tag = dh_encrypt(bob_pub, test_mesage, None)

    with raises(Exception) as excinfo:
        dh_decrypt(bob_priv,
                   (alice_pub, iv, urandom(len(encrypted_text)), tag),
                   None)
    assert 'decryption failed' in str(excinfo.value)

    with raises(Exception) as excinfo:
        dh_decrypt(bob_priv,
                   (alice_pub, iv, encrypted_text, urandom(len(tag))),
                   None)
    assert 'decryption failed' in str(excinfo.value)

    with raises(Exception) as excinfo:
        dh_decrypt(bob_priv,
                   (alice_pub, urandom(len(iv)), encrypted_text, tag),
                   None)
    assert 'decryption failed' in str(excinfo.value)

    with raises(Exception) as excinfo:
        # we generate a random point on the curve
        G = EcGroup()
        priv_dec = G.order().random()
        pub_enc = priv_dec * G.generator()

        dh_decrypt(bob_priv,
                   (pub_enc, iv, encrypted_text, tag),
                   None)
    assert 'decryption failed' in str(excinfo.value)

    with raises(Exception) as excinfo:
        # we generate a random scalar from the group
        G = EcGroup()
        priv_dec = G.order().random()
        dh_decrypt(priv_dec,
                   (alice_pub, iv, encrypted_text, tag),
                   None)
    assert 'decryption failed' in str(excinfo.value)
Пример #46
0
def test_Decrypt():
    G = EcGroup()
    x = G.order().random()
    y = x * G.generator()
    import random

    for _ in range(100):
        i = random.randint(-1000, 999)
        E = Ct.enc(y, i)
        assert E.dec(x) == i
Пример #47
0
def BL_setup(Gid=settings.SERVER_GID):
    # Parameters of the BL schemes
    G = EcGroup(Gid)
    q = G.order()
    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    z = G.hash_to_point(b"z")
    hs = [G.hash_to_point(("h%s" % i).encode("utf8"))
          for i in range(2)]  # 2-> hs[0], hs[1]
    return (G, q, g, h, z, hs)
Пример #48
0
def BL_setup(Gid = 713):
    G = EcGroup(Gid)
    q = G.order()

    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    z = G.hash_to_point(b"z")
    hs = [G.hash_to_point(("h%s" % i).encode("utf-8")) for i in range(100)]#what is this

    return (G, q, g, h, z, hs)
Пример #49
0
def test_CountSketchCt():
    G = EcGroup()
    x = G.order().random()
    y = x * G.generator()
    
    cs = CountSketchCt(50, 7, y)
    cs.insert(11)
    c, d = cs.estimate(11)
    est = c.dec(x)
    # print(est)
    assert est == d
Пример #50
0
def BL_setup(Gid=713):
    # Parameters of the BL schemes
    G = EcGroup(713)
    q = G.order()

    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    z = G.hash_to_point(b"z")
    hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(100)]

    return (G, q, g, h, z, hs)
Пример #51
0
def CountSketchCt_unit_test():

        G = EcGroup()
        x = G.order().random()
        y = x * G.generator()
        cs = CountSketchCt(50, 7, y)
        cs.insert(11)
        c, d = cs.estimate(11)
        
        est = c.dec(x)
        #assert est == d
        return est == d
Пример #52
0
def test_2DH():
    G = EcGroup()
    g = G.generator()
    o = G.order()

    priv1 = o.random()
    priv2 = o.random()
    priv3 = o.random()

    k1 = derive_2DH_sender(G, priv1, priv2 * g, priv3 * g)
    k2 = derive_2DH_receiver(G, priv1 * g, priv2, priv3)

    assert k1 == k2
Пример #53
0
def test_3DH():
    G = EcGroup()
    g = G.generator()
    o = G.order()

    priv1, pub1 = pair(G)
    priv2, pub2 = pair(G)
    priv3, pub3 = pair(G)
    priv4, pub4 = pair(G)

    k1 = derive_3DH_sender(G, priv1, priv2, pub3, pub4)
    k2 = derive_3DH_receiver(G, pub1, pub2, priv3, priv4)
    assert k1 == k2
Пример #54
0
def test_Point_addition():
    """
    Test whether the EC point addition is correct.
    """
    from pytest import raises
    from petlib.ec import EcGroup, EcPt
    G = EcGroup(713) # NIST curve
    d = G.parameters()
    a, b, p = d["a"], d["b"], d["p"]
    g = G.generator()
    gx0, gy0 = g.get_affine()

    r = G.order().random()
    gx1, gy1 = (r*g).get_affine()

    from Lab01Code import is_point_on_curve
    from Lab01Code import point_add

    assert is_point_on_curve(a, b, p, gx0, gy0)
    assert is_point_on_curve(a, b, p, gx1, gy1)

    ## Test a simple addition
    h = (r + 1) * g
    hx1, hy1 = h.get_affine()

    x, y = point_add(a, b, p, gx0, gy0, gx1, gy1)
    assert is_point_on_curve(a, b, p, x, y)
    assert x == hx1
    assert y == hy1

    ## Ensure commutativity
    xp, yp = point_add(a, b, p, gx1, gy1, gx0, gy0)
    assert is_point_on_curve(a, b, p, xp, yp)
    assert x == xp
    assert y == yp

    ## Ensure addition with neutral returns the element
    xp, yp = point_add(a, b, p, gx1, gy1, None, None)
    assert is_point_on_curve(a, b, p, xp, yp)
    assert xp == gx1
    assert yp == gy1
    
    xp, yp = point_add(a, b, p, None, None, gx0, gy0)
    assert is_point_on_curve(a, b, p, xp, yp)
    assert gx0 == xp
    assert gy0 == yp

    ## An error is raised in case the points are equal
    with raises(Exception) as excinfo:
        point_add(a, b, p, gx0, gy0, gx0, gy0)
    assert 'EC Points must not be equal' in str(excinfo.value)
Пример #55
0
def encode_Alice_message():
    """
    Encode a single message
    """

    G = EcGroup()
    g = G.generator()
    o = G.order()

    private_key = o.random()
    public_key = private_key * g

    m1 = mix_client_one_hop(public_key, b"Alice", b"Dear Alice,\nHello!\nBob")
    return private_key, m1
Пример #56
0
def _make_table(start=-10000, end=10000):
    G = EcGroup()
    g = G.generator()
    o = G.order()

    i_table = {}
    n_table = {}
    ix = start * g
    for i in range(start, end):
        i_table[ix] = i
        n_table[(o + i) % o] = ix
        ix = ix + g
        
    return i_table, n_table
Пример #57
0
def test_latex_print():

    # Define an EC group
    G = EcGroup(713)
    order = G.order()

    ## Proof definitions
    zk = ZKProof(G)
    g, h = zk.get(ConstGen, ["g", "h"])
    x, o = zk.get(Sec, ["x", "o"])
    Cxo = zk.get(Gen, "Cxo")
    zk.add_proof(Cxo, x*g + o*h)

    print(zk.render_proof_statement())