コード例 #1
0
ファイル: Classes.py プロジェクト: str4d/Crux
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
ファイル: Classes.py プロジェクト: jdewasseige/Crux
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
コード例 #3
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)
コード例 #4
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))
コード例 #5
0
ファイル: Lab02Code.py プロジェクト: CESource/PET-challenge02
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
ファイル: format.py プロジェクト: gdanezis/loopix
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 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
コード例 #8
0
ファイル: Lab01Code.py プロジェクト: yongtw123/PET-Exercises
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)
コード例 #9
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)
コード例 #10
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)
コード例 #11
0
ファイル: generate_dbs.py プロジェクト: mavroudisv/Crux
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
コード例 #12
0
def measure_mix_and_decrypt_execution_times(num_ciphertexts_l,
                                            m_value=4,
                                            curve_nid=415,
                                            n_repetitions=1):
    """Measure the execution time for mix and decrypt operations."""

    group = EcGroup(curve_nid)
    key_pair = elgamal.KeyPair(group)
    pk = key_pair.pk

    measures = list()

    for num_ciphertexts in num_ciphertexts_l:

        LOGGER.info("Running mix and decrypt with %d ctxts.", num_ciphertexts)
        ctxts = [
            pk.encrypt(i * group.generator()) for i in range(num_ciphertexts)
        ]
        for _ in range(n_repetitions):
            mixnet_per_server = MixNetPerTeller(key_pair, pk, ctxts, m_value)
            proof_time = mixnet_per_server.time_mixing
            decryption_time = mixnet_per_server.time_decrypting

            measures.append([num_ciphertexts, proof_time, decryption_time])

    return measures
コード例 #13
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)
コード例 #14
0
ファイル: Lab01Code.py プロジェクト: WeiqiuLiu/PET-Exercises
def time_scalar_mul():
    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()

    def average_time(func, scalar_name, samples=20):
        scalar = globals()[scalar_name]
        times = []
        for i in range(samples):
            t1 = clock()
            func(a, b, p, gx0, gy0, scalar)
            t2 = clock()
            times.append(t2 - t1)

        mean = reduce((lambda x, y: x + y), times) / samples
        print('{}, {}, mean of {} samples: {}'.format(func.__name__,
                                                      scalar_name, samples,
                                                      mean))

    average_time(point_scalar_multiplication_double_and_add, 'R1')
    average_time(point_scalar_multiplication_double_and_add, 'R2')
    average_time(point_scalar_multiplication_montgomerry_ladder, 'R1')
    average_time(point_scalar_multiplication_montgomerry_ladder, 'R2')
コード例 #15
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)
コード例 #16
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)
コード例 #17
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
コード例 #18
0
ファイル: kulan.py プロジェクト: lucamelis/petlib
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)))
コード例 #19
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)
コード例 #20
0
ファイル: genzkp.py プロジェクト: gdanezis/petlib
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)
コード例 #21
0
ファイル: Lab02Tests.py プロジェクト: Sevyls/pets_ws2015
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
コード例 #22
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"
コード例 #23
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)))
コード例 #24
0
def dh_get_key():
    """ Generate a DH key pair """
    G = EcGroup()
    priv_dec = G.order().random()
    pub_enc = priv_dec * G.generator()

    return (G, priv_dec, pub_enc)
コード例 #25
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)
コード例 #26
0
class Group_ECC:
    "Group operations in ECC"

    def __init__(self, gid=713):
        self.G = EcGroup(gid)
        self.g = self.G.generator()

    def gensecret(self):
        return self.G.order().random()

    def expon(self, base, exp):
        x = exp[0]
        for f in exp[1:]:
            x = x.mod_mul(f, self.G.order())
        b = base
        return (x * b)

    def expon_base(self, exp):
        x = exp[0]
        for f in exp[1:]:
            x = x.mod_mul(f, self.G.order())
        return (x * self.g)

    def makeexp(self, data):
        return (Bn.from_binary(data) % self.G.order())

    def in_group(self, alpha):
        # All strings of length 32 are in the group, says DJB
        b = alpha
        return self.G.check_point(b)

    def printable(self, alpha):
        return alpha.export(POINT_CONVERSION_UNCOMPRESSED)
コード例 #27
0
def test_Point_doubling():
    """
    Test whether the EC point doubling 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()

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

    from Lab01Code import is_point_on_curve
    from Lab01Code import point_double

    x2, y2 = point_double(a, b, p, gx0, gy0)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert x2 == gx2 and y2 == gy2

    x2, y2 = point_double(a, b, p, None, None)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert x2 == None and y2 == None
コード例 #28
0
def test_Point_doubling():
    """
    Test whether the EC point doubling 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()

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

    from Lab01Code import is_point_on_curve
    from Lab01Code import point_double

    x2, y2 = point_double(a, b, p, gx0, gy0)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert x2 == gx2 and y2 == gy2

    x2, y2 = point_double(a, b, p, None, None)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert x2 == None and y2 == None
コード例 #29
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)
コード例 #30
0
ファイル: Lab02Code.py プロジェクト: PETS-TUWien/pets_ws2015
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)
コード例 #31
0
ファイル: Lab02Tests.py プロジェクト: evantsik/PET-Exercises
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
コード例 #32
0
ファイル: Lab02Tests.py プロジェクト: daklaus/pets_ws2015
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
コード例 #33
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
コード例 #34
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
コード例 #35
0
ファイル: Lab02Code.py プロジェクト: Gerard1066/PET-Exercises
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)
コード例 #36
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)
コード例 #37
0
ファイル: kulan.py プロジェクト: lucamelis/petlib
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
コード例 #38
0
ファイル: Lab02Code.py プロジェクト: PETS-TUWien/pets_ws2015
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)
コード例 #39
0
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
コード例 #40
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)
コード例 #41
0
def test(parallel=0):
    from client import Client

    G = EcGroup(713)
    o = G.order()
    g = G.generator()
    o_bytes = int(math.ceil(math.log(float(int(o))) / math.log(256)))

    s = (G, o, g, o_bytes)

    mix1privk = Bn.from_binary(
        base64.b64decode("z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ=="))
    mix1pubk = mix1privk * g

    mix2privk = Bn.from_binary(
        base64.b64decode("266YjC8rEyiEpqXCNXCz1qXTEnwAsqz/tCyzcA=="))
    mix2pubk = mix2privk * g

    privk = Bn.from_binary(
        base64.b64decode("DCATXyhAkzSiKaTgCirNJqYh40ha6dcXPw3Pqw=="))
    recpubk = privk * g

    dbprivk = Bn.from_binary(
        base64.b64decode("/m8A5kOfWNhP4BMcUm7DF0/G0/TBs2YH8KAYzQ=="))
    dbpubk = dbprivk * g

    m1m2 = (mix1privk * G.order().random()) * mix2pubk
    m1db = (mix1privk * G.order().random()) * dbpubk
    m1c = (mix1privk * G.order().random()) * recpubk
    m2db = (mix2privk * G.order().random()) * dbpubk
    m2c = (mix2privk * G.order().random()) * recpubk
    cdb = (privk * G.order().random()) * dbpubk

    pub = [
        Actor("M1", 8001, "127.0.0.1", (mix1pubk, s)),
        Actor("M2", 8002, "127.0.0.1", (mix2pubk, s)),
        Actor("C", 8007, "127.0.0.1", (dbpubk, s)),
        Actor("DB", 9999, "127.0.0.1", (recpubk, s))
    ]

    print "C"
    receiver = Client('C', 9999, "127.0.0.1", s, privk, recpubk, pub,
                      urandom(24))
    receiver.privk = privk
    receiver.pubk = recpubk
    receiver.group = s
    receiver.shared_secrets = {"M1": m1c, "M2": m2c, "DB": cdb}
    receiver.cascade = parallel

    data = receiver.sendCascade()
    print "cascade -----------------------------------------------------"
    print data

    receiver.keys = []
    data = receiver.sendParallel()
    print "\nparallel --------------------------------------------------"
    print data

    print "init finished"
コード例 #42
0
ファイル: tormedian.py プロジェクト: sdklj/petlib
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
コード例 #43
0
    def test_full(self):
        # Generate parameters (should be same in other parts of program)
        Gq = EcGroup()
        p = Gq.order()
        h = Gq.generator()
        G = Gq.hash_to_point(b'G')
        params = (Gq, p, G, h)

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

        # Set (t,n)-threshold parameters
        n = 4
        t = 3

        # 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)

        # Prove generates shares validity
        print("Test verify")
        Y_list = pub['Y_list']
        C_list = pub['C_list']
        assert cpni.DLEQ_verify_list(p, h, pub_keys, C_list, Y_list,
                                     proof) is True

        # 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'])
        ]

        # Check participants proofs
        if pvss.batch_verify_correct_decryption(
                proved_decryptions, pub['Y_list'], pub_keys, p, G) is False:
            print("Verification of decryption failed")

        # Use participants decrypted shares to recreate secret
        S_list = [S_i for (S_i, decrypt_proof) in proved_decryptions]
        actual_decryption = pvss.decode(S_list[0:-1], [1, 2, 3], p)

        # Verify secret
        print("Test decrypt")
        assert expected_decryption == actual_decryption
コード例 #44
0
ファイル: tormedian.py プロジェクト: gdanezis/petlib
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
コード例 #45
0
ファイル: Classes.py プロジェクト: mavroudisv/Crux
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
コード例 #46
0
ファイル: kulan.py プロジェクト: lucamelis/petlib
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
コード例 #47
0
ファイル: kulan.py プロジェクト: lucamelis/petlib
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
コード例 #48
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)
コード例 #49
0
ファイル: Lab02Tests.py プロジェクト: daklaus/pets_ws2015
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
コード例 #50
0
ファイル: tormedian.py プロジェクト: gdanezis/petlib
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
コード例 #51
0
ファイル: generate_db.py プロジェクト: str4d/Crux
def _make_table(start=-200000, end=2000000):
    G = EcGroup(nid=713)
    g = G.generator()
    o = G.order()

    i_table = {}
    n_table = {}
    ix = start * g

    for i in range(start, end):
        i_table[str(ix)] = str(i)
        n_table[str((o + i) % o)] = str(ix)
        ix = ix + g
        #print type(ix)
        #print type(ix.export())

    return i_table, n_table
コード例 #52
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()
    
    # generate shared element
    shared = public_key.pt_mul(private_key)
    material = sha512(shared.export()).digest()
    
    # split shared key for different operations
    hmac_key = material[:16]
    address_key = material[16:32]
    message_key = material[32:48]
    
    # random inistialisation vector
    iv = b"\x00"*16
    
    # encoding address and message
    address_cipher = aes_ctr_enc_dec(address_key, iv, address_plaintext)
    message_cipher = aes_ctr_enc_dec(message_key, iv, message_plaintext)
    
    # generate hmac h
    h = Hmac(b"sha512",hmac_key)
    h.update(address_cipher)
    h.update(message_cipher)
    expected_mac = h.digest()
    expected_mac = expected_mac[:20]

    return OneHopMixMessage(client_public_key, expected_mac, address_cipher, message_cipher)
コード例 #53
0
ファイル: Lab02Code.py プロジェクト: Andreea25bv/PETWS2015
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()

    encryption_key = private_key * public_key
    ek = sha512(encryption_key.export()).digest()
		
    #TODO ADD CODE HERE 	
    
    #get coresponding key parts	
    hmac_key = ek[:16]
    address_key = ek[16:32]
    message_key = ek[32:48]
	 
    #encrypt
    iv = b"\x00"*16
    address_cipher = aes_ctr_enc_dec(address_key, iv, address_plaintext)            
    message_cipher = aes_ctr_enc_dec(message_key, iv, message_plaintext)

    #calculate mac
    h = Hmac(b"sha512", hmac_key)        
    h.update(address_cipher)
    h.update(message_cipher)
    expected_mac = h.digest()
    expected_mac = expected_mac[:20]
      
    return OneHopMixMessage(client_public_key, expected_mac, address_cipher, message_cipher)
コード例 #54
0
def test_on_curve():
    """
    Test the procedues that tests whether a point is on a curve.

    """

    ## Example on how to define a curve
    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()
    gx, gy = g.get_affine()

    from Lab01Code import is_point_on_curve
    assert is_point_on_curve(a, b, p, gx, gy)

    assert is_point_on_curve(a, b, p, None, None)
コード例 #55
0
ファイル: Lab02Tests.py プロジェクト: daklaus/pets_ws2015
def test_simple_client_decode_many():
    from os import urandom

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

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

    messages = []
    for _ in range(100):
        m = mix_client_one_hop(public_key, urandom(256), urandom(1000))
        messages += [m]

    # Ensure the mix can decode the message correctly    
    res1 = mix_server_one_hop(private_key, messages)

    assert len(res1) == 100
コード例 #56
0
ファイル: Lab02Tests.py プロジェクト: daklaus/pets_ws2015
def test_Alice_message_overlong():
    """
    Test overlong address or message
    """

    from os import urandom

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

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

    with raises(Exception) as excinfo:
        mix_client_one_hop(public_key, urandom(1000), b"Dear Alice,\nHello!\nBob")

    with raises(Exception) as excinfo:
        mix_client_one_hop(public_key, b"Alice", urandom(10000))
コード例 #57
0
def test_Point_addition_check_inf_result():
    """
    Test whether the EC point addition is correct for pt - pt = inf
    """
    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()
    gx1, gy1 = gx0, p - gy0


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

    x, y = point_add(a, b, p, gx0, gy0, gx1, gy1)
    assert is_point_on_curve(a, b, p, x, y)
    assert (x,y) == (None, None)
コード例 #58
0
def test_Point_scalar_mult_double_and_add():
    """
    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()


    x2, y2 = point_scalar_multiplication_double_and_add(a, b, p, gx0, gy0, r)
    assert is_point_on_curve(a, b, p, x2, y2)
    assert gx2 == x2
    assert gy2 == y2