def keygen(self):
     group = ECGroup(prime192v2)
     g = group.random(G)
     x = group.random(ZR)
     h = g ** x
     pk = {'g': g, 'h': h, 'group': group, 'order': 6277101735386680763835789423078825936192100537584385056049}
     sk = {'x': x}
     return pk, sk
Example #2
0
    def testRandomGroupDecode(self):
        group = ECGroup(prime192v1)

        for i in range(runs):
            r = group.random(G)
            m = group.decode(r, True)
            n = group.encode(m, True)
            assert r == n, "Failed to encode/decode properly including counter"
Example #3
0
 def testRandomMessageDecode(self):
     group = ECGroup(prime192v2)
     for i in range(runs):
         msg_len = group.bitsize()
         s = OpenSSLRand().getRandomBytes(msg_len)
         g = group.encode(s)
         t = group.decode(g)
         assert s == t, "Failed to encode/decode %d properly" % i
Example #4
0
    def testECGroup(self):    
        groupObj = ECGroup(prime192v1)
        p=groupObj.random()
        data={'p':p,'String':"foo",'list':[p,{},1,1.7, b'dfa',]}

        x=objectToBytes(data,groupObj)
        data2=bytesToObject(x,groupObj)
        self.assertEqual(data,data2)
Example #5
0
 def readPoint(pointX, pointY):
     group = ECGroup(prime192v1)
     point = group.deserialize(b'1:' +
                               b64encode(a2b_hex('03' + pointX.zfill(48))))
     if str(group.coordinates(point)[1]) != str(int(pointY, 16)):
         #			print("inverting ("+str(group.coordinates(point)[1])+", "+str(int(pointY, 16))+")")
         point = point**-1
     return point
Example #6
0
 def keygen(self):
     group = ECGroup(prime192v2)
     g = group.random(G)
     x = group.random(ZR)
     h = g**x
     pk = {
         'g': g,
         'h': h,
         'group': group,
         'order': 6277101735386680763835789423078825936192100537584385056049
     }
     sk = {'x': x}
     return pk, sk
Example #7
0
    def testHybridEnc(self):
        groupObj = ECGroup(prime192v1)
        pkenc = ElGamal(groupObj)
        hyenc = HybridEnc(pkenc, msg_len=groupObj.bitsize())

        (pk, sk) = hyenc.keygen()

        # message len should be group.bitsize() len for prime192v1 (or 20 bytes)
        m = b'the hello world msg1'
        cipher = hyenc.encrypt(pk, m)
        orig_m = hyenc.decrypt(pk, sk, cipher)
        assert m == orig_m, "Failed Decryption"
        if debug: print("Successful Decryption!!")
Example #8
0
def main():
    grp = ECGroup(secp256k1)
    ms = MuSig(grp)
    g = grp.random(G)
    if debug:
        print('Generator...', g)

    msg = 'hello there'
    num_signers = 5

    if debug:
        print('{} signers will sign {}'.format(num_signers, msg))

    signers = [ms.keygen(g) for _ in range(num_signers)]

    nonces = [ms.new_nonce() for _ in range(num_signers)]
    an = ms.aggregate_nonce(g, nonces)
    all_pub_keys = [signer[0] for signer in signers]

    if debug:
        print('Public keys...')
        for pk in all_pub_keys:
            print(pk)

    apk = ms.aggregated_pub_key(all_pub_keys)
    if debug:
        print('Aggregated Public key: ', apk)

    challenge = ms.compute_challenge(apk, an, msg)
    sigs = [
        ms.sign(nonces[i], signers[i][1], signers[i][0], challenge,
                all_pub_keys) for i in range(num_signers)
    ]

    if debug:
        print('Signatures...')
        for sig in sigs:
            print(sig)

    asig = ms.aggregate_sigs(sigs)

    if debug:
        print('Aggregated signature: ', asig)

    assert ms.verify(all_pub_keys, (an, asig),
                     msg), 'Aggregated sig verification failed'

    if debug:
        print('Verification succeeded')
Example #9
0
 def testCM_Ped92(self):
     groupObj = ECGroup(410)    
     cm = CM_Ped92(groupObj)
    
     pk = cm.setup()
     if debug: 
         print("Public parameters...")
         print("pk =>", pk)
     
     m = groupObj.random(ZR)
     if debug: print("Commiting to =>", m)
     (c, d) = cm.commit(pk, m)
     
     assert cm.decommit(pk, c, d, m), "FAILED to decommit"
     if debug: print("Successful and Verified decommitment!!!")
     del groupObj
Example #10
0
def parseFromXML(xmlObjectString, group=None):
    assert type(xmlObjectString) == str, "Invalid type for XML object"
    dom = parseString(xmlObjectString)
    assert dom.documentElement.tagName == "charm", "Not a Charm element"
    #    print(dom.toprettyxml(indent="  "))

    groupObj = dom.getElementsByTagName("group")
    assert groupObj != None, "Error: could not find group tag."
    groupObj = groupObj[0]
    charmObj1 = dom.getElementsByTagName("object")
    assert charmObj1 != None, "Error: could not find object tag."
    charmObj1 = charmObj1[0]

    structure = {}
    setting = groupObj.getAttribute("setting")
    param = groupObj.getAttribute("param")

    charmObj2 = dom.getElementsByTagName("name")
    structure['name'] = None
    if charmObj2 != None:
        charmObj2 = charmObj2[0]  # what is this useful for?
        structure['name'] = charmObj2.getAttribute("id")

    bytesObj = getText(charmObj1.childNodes).strip()

    if setting == 'pairing' and group == None:
        group = PairingGroup(param)
    elif structure['setting'] == 'elliptic_curve' and group == None:
        group = ECGroup(param)
    elif structure['setting'] == 'integer':
        # TODO: this is a special case
        pass
    return bytesToObject(bytesObj, group)
Example #11
0
def ecdsa():
    group = ECGroup(prime192v2)
    ecdsa = ECDSA(group)

    results = 0.0
    for i in range(0, number):
        start = time.clock()
        (public_key, secret_key) = ecdsa.keygen(0)
        end = time.clock()
        results += end - start
    mean = results / number
    logging.info("ECDSA key generation time: " + str(mean))
    (public_key, secret_key) = ecdsa.keygen(0)

    msg = "hello world! this is a test message."

    results = 0.0
    for i in range(0, number):
        start = time.clock()
        ecdsa.sign(public_key, secret_key, msg)
        end = time.clock()
        results += end - start
    mean = results / number
    logging.info("ECDSA signing time: " + str(mean))
    signature = ecdsa.sign(public_key, secret_key, msg)

    results = 0.0
    for i in range(0, number):
        start = time.clock()
        ecdsa.verify(public_key, signature, msg)
        end = time.clock()
        results += end - start
    mean = results / number
    logging.info("ECDSA verify time: " + str(mean))
    ecdsa.verify(public_key, signature, msg)
Example #12
0
    def testCM_Ped92(self):
        groupObj = ECGroup(410)
        cm = CM_Ped92(groupObj)

        pk = cm.setup()
        if debug:
            print("Public parameters...")
            print("pk =>", pk)

        m = groupObj.random(ZR)
        if debug: print("Commiting to =>", m)
        (c, d) = cm.commit(pk, m)

        assert cm.decommit(pk, c, d, m), "FAILED to decommit"
        if debug: print("Successful and Verified decommitment!!!")
        del groupObj
Example #13
0
 def testECGroup(self):
     trials = 10
     group = ECGroup(prime192v2)
     g = group.random(G)
     h = group.random(G)
     i = group.random(G)
     
     self.assertTrue(group.InitBenchmark())
     group.StartBenchmark(["RealTime", "Mul", "Div", "Exp", "Granular"])
     for a in range(trials):
         j = g * h 
         k = h ** group.random(ZR)
         t = (j ** group.random(ZR)) / k 
     group.EndBenchmark()
     
     msmtDict = group.GetGeneralBenchmarks()
     self.assertTrue(isSaneBenchmark(msmtDict))        
     
     granDict = group.GetGranularBenchmarks()
     self.assertTrue(isSaneBenchmark(granDict))        
     
     self.assertTrue(group.InitBenchmark())
     group.StartBenchmark(["RealTime", "Mul", "Div", "Exp", "Granular"])
     for a in range(trials*2):
         j = g * h 
         k = h ** group.random(ZR)
         t = (j ** group.random(ZR)) / k 
     group.EndBenchmark()
     
     msmtDict = group.GetGeneralBenchmarks()
     granDict = group.GetGranularBenchmarks()
     del group
     self.assertTrue(isSaneBenchmark(msmtDict))        
     self.assertTrue(isSaneBenchmark(granDict))
Example #14
0
 def testElGamal(self):
     groupObj = ECGroup(prime192v2)
     el = ElGamal(groupObj)
     (pk, sk) = el.keygen()
     msg = b"hello world!"
     cipher1 = el.encrypt(pk, msg)
     m = el.decrypt(pk, sk, cipher1)
     assert m == msg, "Failed Decryption!!!"
     if debug: print("SUCCESSFULLY DECRYPTED!!!")
Example #15
0
    def testECGroup(self):
        groupObj = ECGroup(prime192v1)
        p = groupObj.random()
        data = {
            'p': p,
            'String': "foo",
            'list': [
                p,
                {},
                1,
                1.7,
                b'dfa',
            ]
        }

        x = objectToBytes(data, groupObj)
        data2 = bytesToObject(x, groupObj)
        self.assertEqual(data, data2)
Example #16
0
    def testECDSA(self):
        groupObj = ECGroup(prime192v2)
        ecdsa = ECDSA(groupObj)
        
        (pk, sk) = ecdsa.keygen(0)
        m = "hello world! this is a test message."

        sig = ecdsa.sign(pk, sk, m)
        assert ecdsa.verify(pk, sig, m), "Failed verification!"
        if debug: print("Signature Verified!!!")
Example #17
0
 def testElGamal(self):
     groupObj = ECGroup(prime192v2)
     el = ElGamal(groupObj)
     (pk, sk) = el.keygen()
     # message len should be group.bitsize() len for prime192v1 (or 20 bytes)
     msg = b'the hello world msg1'
     cipher1 = el.encrypt(pk, msg)
     m = el.decrypt(pk, sk, cipher1)
     assert m == msg, "Failed Decryption!!!"
     if debug: print("SUCCESSFULLY DECRYPTED!!!")
Example #18
0
    def initParams():
        group = ECGroup(prime192v1)
        g = Params.readPoint(
            "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
            "7192B95FFC8DA78631011ED6B24CDD573F977A11E794811")
        h = Params.readPoint(
            "87656f2b5fee3821b53b00d78bd61a8d407ce4393ea48906",
            "b52e5b337ca8f667935a63d02d6f6fec689c7f18a640a8a5")
        #		g = group.random(G)
        #		h = group.random(G)
        params = {'g': g, 'h': h}

        # generators for the proof of shuffling
        for i in range(-4, 100):  # FIXME: make this 101
            params['f' + str(i)] = group.random(G)

        f = open('pc.param', 'wb')
        f.write(objectToBytes(params, group))
        f.close()
        return [params, group]
    def setup(self, curve, subscribers):
        """
        Setup the scheme using a trusted third party.
        """
        group = ECGroup(curve)
        g = group.random(G)

        ak = 0
        sk = list()
        for i in range(subscribers):
            key = group.random(ZR)
            ak -= key
            sk.append(key)

        self.pp = {'subscribers': subscribers, 'group': group, 'g': g}
        self.ak = ak
        self.sk = sk

        self.baby_steps = None

        return (self.pp, self.ak, self.sk)
def main():
    groupObj = ECGroup(prime192v1)
    pkenc = CS98(groupObj)
    hyenc = HybridEnc(pkenc)

    (pk, sk) = hyenc.keygen()

    m = b'this is a new message'
    cipher = hyenc.encrypt(pk, m)
    orig_m = hyenc.decrypt(pk, sk, cipher)
    assert m == orig_m, "Failed Decryption"
    if debug: print("Successful Decryption!!")
Example #21
0
 def readParams(filename='pc.param'):
     if (os.path.isfile(filename)):
         group = ECGroup(prime192v1)
         f = open(filename, 'rb')
         params = f.readline()
         f.close()
         params = bytesToObject(params, group)
         return [params, group]
     else:
         raise Exception(
             "I can't find the parameters file. You have to create them first using -n when starting."
         )
Example #22
0
def el_gamal_cryptosystem():
    from charm.toolbox.eccurve import prime192v2
    from charm.toolbox.ecgroup import ECGroup
    from charm.schemes.pkenc.pkenc_elgamal85 import ElGamal

    groupObj = ECGroup(prime192v2)
    el = ElGamal(groupObj)
    (public_key, secret_key) = el.keygen()
    msg = b"hello world!12345678"
    cipher_text = el.encrypt(public_key, msg)
    decrypted_msg = el.decrypt(public_key, secret_key, cipher_text)
    print(decrypted_msg == msg)
Example #23
0
File: HIKE.py Project: Pica4x6/HIKE
def testIntEncryption():
    from charm.toolbox.eccurve import secp256k1
    from charm.toolbox.ecgroup import ECGroup

    groupObj = ECGroup(secp256k1)
    hike = HIKE(groupObj)
    (secret_key, eval_key) = hike.keygen()
    (secret_key_prime, eval_key_prime) = hike.keygen()
    msg = 10
    label = b"label1"

    print('Public Key...')
    Q = hike.publicKey(secret_key_prime)
    print()

    label = hike.generateLabel(secret_key, label, Q)
    cipher_text = hike.encrypt(secret_key, label, msg)

    program = {'f': [0, 1], 'labels': [label]}
    decrypted_msg = hike.decrypt(secret_key, program, cipher_text)

    print("Decrypted message {}".format(decrypted_msg))
    print()

    print('Eval...')
    msg2 = 10
    label2 = b"label2"
    label2 = hike.generateLabel(secret_key, label2, Q)
    program = {'f': [0, 1, 1], 'labels': [label, label2]}

    cipher_text2 = hike.encrypt(secret_key, label2, msg2)

    cipher_text_eval = hike.eval(program['f'], [cipher_text, cipher_text2])
    decrypted_msg = hike.decrypt(secret_key, program, cipher_text_eval)
    print("Decrypted message eval f(0,1,1) and msg[1,1]: {}".format(
        decrypted_msg))
    print()

    print('Token Gen...')
    tok = hike.tokenGen(secret_key, program)
    print()

    print('Token Dec...')
    tokenDec = hike.tokenDec(secret_key_prime, cipher_text, tok)
    print("TokenDec message {}".format(tokenDec))

    print()

    print('ct: {}'.format(cipher_text['ct']))
    print('Destroying ct....')
    ct = hike.destroyEnc(cipher_text)
    print('ct: {}'.format(ct['ct']))
Example #24
0
    def __init__(self, builtin_cv, common_input=None):
        Protocol.__init__(self, None)
        verifier_states = {
            2: self.verifier_state2,
            4: self.verifier_state4,
            6: self.verifier_state6
        }
        prover_states = {
            1: self.prover_state1,
            3: self.prover_state3,
            5: self.prover_state5
        }

        verifier_trans = {2: 4, 4: [2, 6]}
        prover_trans = {1: 3, 3: 5, 5: 1}
        # describe the parties involved and the valid transitions
        Protocol.addPartyType(self, VERIFIER, verifier_states, verifier_trans)
        Protocol.addPartyType(self, PROVER, prover_states, prover_trans, True)

        self.group = ECGroup(builtin_cv)
        #db = {}
        Protocol.setSubclassVars(self, self.group)  #, db)
Example #25
0
    def testEC_CS98(self):
        groupObj = ECGroup(prime192v1)
        pkenc = CS98(groupObj)

        (pk, sk) = pkenc.keygen()

        # message len should be group.bitsize() len for prime192v1 (or 20 bytes)
        M = b'the hello world msg1'
        ciphertext = pkenc.encrypt(pk, M)
        message = pkenc.decrypt(pk, sk, ciphertext)

        assert M == message, "Failed Decryption!!!"
        if debug: print("SUCCESSFUL DECRYPTION!!! => %s" % message)
Example #26
0
    def testEC_CS98(self):
        groupObj = ECGroup(prime192v1)
        pkenc = CS98(groupObj)

        (pk, sk) = pkenc.keygen()
        M = b"hello world!!!"

        ciphertext = pkenc.encrypt(pk, M)

        message = pkenc.decrypt(pk, sk, ciphertext)

        assert M == message, "Failed Decryption!!!"
        if debug: print("SUCCESSFUL DECRYPTION!!! => %s" % message)
Example #27
0
def twoHandler(twoParameter):
    group = ECGroup(security_dict[twoParameter.L])
    omega = group.init(ZR, int(twoParameter.omega))
    delta = group.init(ZR, int(twoParameter.delta))
    g = group.deserialize(str.encode(twoParameter.sg))
    h = group.deserialize(str.encode(twoParameter.sh))
    y = group.deserialize(str.encode(twoParameter.sy))
    zeta1 = group.deserialize(str.encode(twoParameter.szeta1))
    zeta2 = group.deserialize(str.encode(twoParameter.szeta2))
    roi = group.init(ZR, int(twoParameter.roi))
    sigma1 = group.init(ZR, int(twoParameter.sigma1))
    sigma2 = group.init(ZR, int(twoParameter.sigma2))

    tmp1 = (g**roi) * (y**omega)
    tmp2 = (g**sigma1) * (zeta1**delta)
    tmp3 = (h**sigma2) * (zeta2**delta)
    m = twoParameter.m
    return (str(omega + delta),
            str(group.hash((zeta1, tmp1, tmp2, tmp3, m), ZR)))
Example #28
0
    def __init__(self, builtin_cv, common_input=None):
        Protocol.__init__(self, None)        
        verifier_states = { 2:self.verifier_state2, 4:self.verifier_state4, 6:self.verifier_state6 }
        prover_states = { 1:self.prover_state1, 3:self.prover_state3, 5:self.prover_state5 }

        verifier_trans = { 2:4, 4:[2,6] }
        prover_trans = { 1:3, 3:5, 5:1 }
        # describe the parties involved and the valid transitions
        Protocol.addPartyType(self, VERIFIER, verifier_states, verifier_trans)
        Protocol.addPartyType(self, PROVER, prover_states, prover_trans, True)

        self.group = ECGroup(builtin_cv)
        #db = {}
        Protocol.setSubclassVars(self, self.group) #, db)
Example #29
0
File: HIKE.py Project: Pica4x6/HIKE
def testStringEncryption():
    from charm.toolbox.eccurve import secp256k1
    from charm.toolbox.ecgroup import ECGroup

    groupObj = ECGroup(secp256k1)
    hike = HIKE(groupObj)
    (secret_key, eval_key) = hike.keygen()
    (secret_key_prime, eval_key_prime) = hike.keygen()

    msg = b"hello world!1234567891234567"
    label = b"label1"

    print('Public Key...')
    Q = hike.publicKey(secret_key_prime)
    print()

    label = hike.generateLabel(secret_key, label, Q)

    cipher_text = hike.encrypt(secret_key, label, msg)

    program = {'f': [0, 1], 'labels': [label]}
    decrypted_msg = hike.decrypt(secret_key, program, cipher_text)

    print("Decrypted message {}".format(decrypted_msg))
    print()

    tok = hike.tokenGen(secret_key, program)

    msg = hike.tokenDec(secret_key_prime, cipher_text, tok)
    print("TokenDec message {}".format(msg))

    print()

    print('Destroying ct....')
    ct = hike.destroyEnc(cipher_text)
    decrypted_msg = hike.decrypt(secret_key, program, ct)

    print("Decrypted message {}".format(decrypted_msg))
    print()
Example #30
0
    def setup(self, a):
        a['r'] = [group.random(ZR) for _ in range(len(a['m']))]
        a['r-1'] = [r**-1 for r in a['r']]
        a['R'] = [a['g']**r for r in a['r']]
        return {'R': a['R']}

    def choose(self, b):
        b['k'] = group.random(ZR)
        b['v'] = b['R'][b['b']]**b['k']
        b['m'] = b['g']**b['k']
        return {'v': b['v']}

    def mask(self, a):
        a["m'"] = [a['v']**r1 for r1 in a['r-1']]
        return {"m'": a["m'"]}


if __name__ == "__main__":
    # Just testing
    OT = DLP(ECGroup(prime256v1))

    a, b = OT.gen_params()
    OT.gen_msgs(a, 1000)
    b.update({'b': 2})
    b.update(OT.setup(a))
    a.update(OT.choose(b))
    b.update(OT.mask(a))

    print(b["m"] == a["m'"][b["b"]])
Example #31
0
 def __init__(self, curve=prime256v1):
     super().__init__()
     self.group = ECGroup(curve)
     self.g = self.group.random(G)
Example #32
0
class Intersection(NonInteractiveSetIntersection):
    """Two-Client Set Intersect scheme"""
    client_count = 2

    def __init__(self, curve=prime256v1):
        super().__init__()
        self.group = ECGroup(curve)
        self.g = self.group.random(G)

    def setup(self, secpar):
        """Generate the clients' keys"""
        self.secpar = secpar

        sigma = self.group.random(ZR)
        msk = os.urandom(secpar // 8)

        return ((msk, sigma), (msk, 1 - sigma))

    def _phi(self, cipher, pt):
        """PRF mapping pt to a group element"""
        padding_len = 16 - (len(pt) % 16)
        pt = pt + b'\0' * padding_len

        encryptor = cipher.encryptor()
        ct = encryptor.update(pt) + encryptor.finalize()

        exponent = int.from_bytes(ct, 'big') % self.group.order()
        return self.g**exponent

    def _H(self, g):
        """Mapping of g to bytes
        
        Can be used to map a group element g to an AE key."""
        prefix = b'\x00'
        hashable = prefix + self.group.serialize(g)
        h = hashlib.sha256(hashable).digest()
        return h[:16]

    def _H_bytes(self, g):
        """Mapping of g to bytes
        
        Can be used to map a group element g to an AE nonce."""
        prefix = b'\x01'
        hashable = prefix + self.group.serialize(g)
        h = hashlib.sha256(hashable).digest()

        return h

    def encrypt(self, usk, gid, pt_set):
        """Encrypt a plaintext set under a gid using usk

        Returns a dict of ciphertexts."""
        msk, sigma = usk

        iv = gid
        cipher = Cipher(algorithms.AES(msk),
                        modes.CBC(iv),
                        backend=default_backend())

        ct_dict = {}
        for pt in pt_set:
            k = self._phi(cipher, pt)
            ct1 = self.group.serialize(k**sigma)

            # use deterministic authenticated encryption
            ae_key = self._H(k)
            ae_nonce = self._H_bytes(k)[:12]
            ae = AESGCM(ae_key)
            ct2 = (ae_nonce, ae.encrypt(ae_nonce, pt, None))

            ct_dict[ae_key] = (ct1, ct2)

        return ct_dict

    def eval(self, ct_sets):
        """Evaluates the ciphertexts for determining the cardinality of the set intersection
        
        Expects two dicts of ciphertexts."""
        pt_intersection = set()
        ct_intersection = ct_sets[0].keys() & ct_sets[1].keys()

        for k in ct_intersection:
            g1 = self.group.deserialize(ct_sets[0][k][0])
            g2 = self.group.deserialize(ct_sets[1][k][0])
            key = g1 * g2

            # decrypt using ct_sets[0]
            ae_nonce, ct = ct_sets[0][k][1]
            ae_key = self._H(key)
            ae = AESGCM(ae_key)
            pt = ae.decrypt(ae_nonce, ct, None)

            pt_intersection.add(pt)

        return pt_intersection
Example #33
0
#!/usr/bin/python3

from charm.toolbox.ecgroup import ECGroup,ZR,G
from charm.toolbox.eccurve import prime192v1

trials = 10
group = ECGroup(prime192v1)
g = group.random(G)
h = group.random(G)
i = group.random(G)

assert group.InitBenchmark(), "failed to initialize benchmark"
group.StartBenchmark(["RealTime", "CpuTime", "Mul", "Div", "Exp", "Granular"])
for a in range(trials):
	j = g * h
	k = h ** group.random(ZR)
	t = (j ** group.random(ZR)) / k
group.EndBenchmark()

msmtDict = group.GetGeneralBenchmarks()
print("<=== General Benchmarks ===>")
print("Mul := ", msmtDict["Mul"])
print("Div := ", msmtDict["Div"])
print("Exp := ", msmtDict["Exp"])
print("RealTime := ", msmtDict["RealTime"])
print("CpuTime := ", msmtDict["CpuTime"])

granDict = group.GetGranularBenchmarks()
print("<=== Granular Benchmarks ===>")
print("G mul   := ", granDict["Mul"][G])
print("G exp   := ", granDict["Exp"][G])
Example #34
0
"""This module implements the Pedila client."""

from charm.toolbox.ecgroup import ECGroup,ZR,G
from charm.toolbox.eccurve import prime256v1
from charm.core.engine.util import bytesToObject, objectToBytes

import os
import os.path

group = ECGroup(prime256v1)

class Client():
    """The Pedila client implementation. Inputs are usually JSON encoded."""
    def __init__(self, generator, public_key):
        """Expects CHARM group elements @generator and @public_key. Initializes
           an empty update token."""

        self.G = generator
        self.X = public_key

        if os.path.exists('key.b64'):
            with open('key.b64', 'rb') as keyfile:
                self.y = bytesToObject(keyfile.read(), group)
        else:
            self.y = group.random(ZR)
            with open('key.b64', 'wb') as keyfile:
                keyfile.write(objectToBytes(self.y, group))


    def do_rotation(self, a1, a2, b1, b2, g, phi):
        alpha, _ = auxiliary
Example #35
0
    S = group1.random(ZR)
    #h = group1.randomGen();
    r = group1.random()
    c = (G**S)
    ##creates commitment c
    return S, c


def create_y1(group1, R_1, g):  ##Bob creates y1 sends to Ingrid
    G = g
    r1 = R_1
    y1 = G**r1
    return y1


group1 = ECGroup(694)
g = group1.random(G)  ## generates g step 0
#print(g)
#Bob =[];
##step 1 : Bob creates a secret ti
ti = create_t(group1)
#Bob.append(ti); ## Adds ti to Bob's list
A = create_A(group1, ti, g)
## step 1
#Bob.append(A);

#Ingrid =[];
#Ingrid.appe                                                             nd(A);
## Bob sends A to Ingrid

s, com = create_com(group1, g)
Example #36
0
import time

from charm.toolbox.ecgroup import ECGroup, ZR, G
from charm.toolbox.eccurve import prime192v1, secp256k1, sect283k1, sect571k1

#192 bit group: g, h
decoded_g192 = b'\xab\xd0}\x86\xe1\x92,\xdd Ceael\x1a\xc3\xb9\xf5a\xe9K\xcd7\xa4'
decoded_h192 = b'\x00\xa3\x0brz\xea\xb0\xba\x005\t\xf9\xe9\xd2\x84\x0b\x18\x02\x18\xc2\xd7E\x13D'

group192 = ECGroup(prime192v1)
group256 = ECGroup(secp256k1)
group283 = ECGroup(sect283k1)
group571 = ECGroup(sect571k1)

g256 = group256.random(G)
h256 = group256.random(G)

#Cofactor is 4
#TODO: Just doing 8 change to 4
g283 = (group283.random(G))**(group283.init(ZR, int(4)))
h283 = (group283.random(G))**(group283.init(ZR, int(4)))

g571 = (group571.random(G))**(group571.init(ZR, int(4)))
h571 = (group571.random(G))**(group571.init(ZR, int(4)))

decoded_g256 = group256.decode(g256)
decoded_h256 = group256.decode(h256)

decoded_g283 = group283.decode(g283)
decoded_h283 = group283.decode(h283)
Example #37
0
class SchnorrZK(Protocol):
    def __init__(self, builtin_cv, common_input=None):
        Protocol.__init__(self, None)        
        verifier_states = { 2:self.verifier_state2, 4:self.verifier_state4, 6:self.verifier_state6 }
        prover_states = { 1:self.prover_state1, 3:self.prover_state3, 5:self.prover_state5 }

        verifier_trans = { 2:4, 4:[2,6] }
        prover_trans = { 1:3, 3:5, 5:1 }
        # describe the parties involved and the valid transitions
        Protocol.addPartyType(self, VERIFIER, verifier_states, verifier_trans)
        Protocol.addPartyType(self, PROVER, prover_states, prover_trans, True)

        self.group = ECGroup(builtin_cv)
        #db = {}
        Protocol.setSubclassVars(self, self.group) #, db)
        
    # PROVER states
    def prover_state1(self):
        x = self.group.random()
        r, g = self.group.random(), self.group.random(G)
        t = g ** r 
        print('prover: ',"hello to verifier.")
        Protocol.store(self, ('r',r), ('x',x))
        Protocol.setState(self, 3)
        return {'t':t, 'g':g, 'y':g ** x } # output goes to the next state.
     
    def prover_state3( self, input):
        print("state3 => ", input)
        (r, x, c) = Protocol.get(self, ['r', 'x', 'c'])
        s = r + c * x
        Protocol.setState(self, 5)
        return {'s':s}

    def prover_state5( self, input ):
        print("state5 => ", input)
        result = input.split(':')[1]
        if result == 'ACCEPTED': Protocol.setState(self, None)
        else: Protocol.setState(self, 1); return 'REPEAT'
        return None

    # VERIFIER states
    def verifier_state2(self, input):
        #print("state2 received => ", input)
        # compute challenge c and send to prover
        c = self.group.random()
        print("state2 generate c :=", c)
        Protocol.store(self, ('c',c))
        Protocol.setState(self, 4)        
        return {'c':c}

    def verifier_state4( self, input ):
        (t,g,y,c,s) = Protocol.get(self, ['t','g','y','c','s'])
        print("state4: s :=", s)
        
        if (g ** s == t * (y ** c)):
           print("SUCCESSFUL VERIFICATION!!!")
           output = "verifier : ACCEPTED!"
        else:
            print("FAILED TO VERIFY!!!")            
            output = "verifier : FAILED!"
        Protocol.setState(self, 6)
        return output
    
    def verifier_state6(self, input ):
        print("state6: => ", input)
        Protocol.setState(self, None)
        return None