def testPairing(self):
        trials = 10
        trials2 = trials * 3
        group = PairingGroup("SS512")
        g = group.random(G1)
        h = group.random(G1)
        i = group.random(G2)

        self.assertTrue(group.InitBenchmark())
        group.StartBenchmark(["RealTime", "Exp", "Pair"])
        for a in range(trials):
            j = g * h
            k = i**group.random(ZR)
            t = (j**group.random(ZR)) / h
            n = pair(h, i)
        group.EndBenchmark()

        msmtDict = group.GetGeneralBenchmarks()
        self.assertTrue(isSaneBenchmark(msmtDict))

        self.assertTrue(group.InitBenchmark())

        group.StartBenchmark(["CpuTime", "Mul", "Pair"])
        for a in range(trials2):
            j = g * h
            k = i**group.random(ZR)
            n = pair(h, i)
        group.EndBenchmark()

        msmtDict = group.GetGeneralBenchmarks()
        del group
        self.assertTrue(isSaneBenchmark(msmtDict))
Ejemplo n.º 2
0
    def testPairing(self):    
        trials = 10
        trials2 = trials * 3 
        group = PairingGroup("SS512")
        g = group.random(G1)
        h = group.random(G1)
        i = group.random(G2)

        self.assertTrue(group.InitBenchmark())
        group.StartBenchmark(["RealTime", "Exp", "Pair"])
        for a in range(trials):
            j = g * h 
            k = i ** group.random(ZR)
            t = (j ** group.random(ZR)) / h 
            n = pair(h, i)
        group.EndBenchmark()
       
        msmtDict = group.GetGeneralBenchmarks()
        self.assertTrue(isSaneBenchmark(msmtDict))        

        self.assertTrue(group.InitBenchmark())
        
        group.StartBenchmark(["CpuTime", "Mul", "Pair"])
        for a in range(trials2):
            j = g * h 
            k = i ** group.random(ZR)
            n = pair(h, i)
        group.EndBenchmark()
        
        msmtDict = group.GetGeneralBenchmarks()
        del group
        self.assertTrue(isSaneBenchmark(msmtDict))        
Ejemplo n.º 3
0
def test2():
    client = UdpEndPoint()
    p = UdpEndPoint()
    group_object = PairingGroup('SS512')
    key_client = group_object.random(GT)
    key_p = group_object.random(GT)
    nonce = OpenSSLRand().getRandomBits(128)
    server_crypter_a = SymmetricCryptoAbstraction(extractor(key_client))
    server_crypter_b = SymmetricCryptoAbstraction(extractor(key_p))
    c_package_a = test1(client, p, nonce,
                        objectToBytes(key_client, group_object),
                        objectToBytes(key_p, group_object))
    print('===========================================================')
    print(c_package_a)
    key_package_a = server_crypter_a.decrypt(c_package_a)
    key_package_a = bytesToObject(key_package_a, group_object)
    key_package_b = server_crypter_b.decrypt(key_package_a[3])
    key_package_b = bytesToObject(key_package_b, group_object)
    print('===========================================================')
    i = 1
    for thing in key_package_a:
        print(str(i) + '.', thing)
        i += 1
    print('===========================================================')
    j = 1
    for thing in key_package_b:
        print(str(j) + '.', thing)
        j += 1
    print('===========================================================')
Ejemplo n.º 4
0
 def init(self, kappa):
     group = PairingGroup(kappa)
     p, g1 = (group.order(), group.random(G1))
     x1, x2, y1, y2 = [group.random(ZR) for i in range(4)]
     g2 = g1**(x1 / x2)
     z = g1**x1
     u1 = g1**y1
     u2 = g2**y2
     setup.GetKeypairs()
Ejemplo n.º 5
0
 def __init__(self, kappa):
     group = PairingGroup(kappa)
     p, g1 = (group.order(), group.random(G1))
     x1, x2, y1, y2 = [group.random(ZR) for i in range(4)]
     g2 = g1**(x1 / x2)
     z = g1**x1
     u1 = g1**y1
     u2 = g2**y2
     self.pk = PublicKeys(group, p, g1, g2, z, u1, u2)
     self.sk = PrivateKeys(x1, x2, y1, y2)
Ejemplo n.º 6
0
def ibcKeySize():
    group = PairingGroup('SS512')
    g1 = group.random(G1)
    g2 = group.random(G2)
    gt = group.random(GT)
    logging.info("G1:" + str(g1) + ", length: " +
                 str(len(Blob(objectToBytes(g1, group)))) + " bytes.")
    logging.info("G2:" + str(g2) + ", length: " +
                 str(len(Blob(objectToBytes(g2, group)))) + " bytes.")
    logging.info("GT:" + str(gt) + ", length: " +
                 str(len(Blob(objectToBytes(gt, group)))) + " bytes.")
Ejemplo n.º 7
0
def schnorr_NIZK():
    # setup
    start = time.time()
    grp = PairingGroup('MNT224')
    ps = PS01(grp)
    end = time.time()
    print("Setup time elapse: ")
    print(end - start)
    # keygen
    start = time.time()
    (pk, sk) = ps.keygen(2)
    end = time.time()
    print("KeyGen over two attributes time elapse: ")
    print(end - start)
    # generate a secret
    secret = grp.random()
    # NIZK Schnorr prover
    start = time.time()
    na = grp.random()
    a = pk['Y1'][0] ** na
    # deterministic nb
    m = hashlib.sha256()
    m.update(grp.serialize(pk['Y1'][0]))
    m.update(grp.serialize(a))
    m.update(grp.serialize(pk['Y1'][0] ** secret))
    m.update(b'userid') # replaced with real values
    nb = m.digest()
    nb = grp.hash(nb)
    # r
    r = na + nb * secret
    end = time.time()
    print("NIZK Schnorr on one attribute Prover time elapse: ")
    print(end - start)
    # NIZK Schnorr verifier
    start = time.time()
    m = hashlib.sha256()
    m.update(grp.serialize(pk['Y1'][0]))
    m.update(grp.serialize(a))
    m.update(grp.serialize(pk['Y1'][0] ** secret))
    m.update(b'userid')  # replaced with real values
    nb = m.digest()
    nb = grp.hash(nb)
    lh = pk['Y1'][0] ** r
    rh = a * (pk['Y1'][0] ** secret) ** nb
    end = time.time()
    print("NIZK Schnorr Verifier time elapse: ")
    print(end - start)
    if lh == rh:
        print('check success')
    else:
        print('lh:=', lh)
        print('rh:=', rh)
Ejemplo n.º 8
0
def main(argv):
    HOST, PORT = "", 8090
    party_info = {}
    if argv[1] == '-p':
        print("Operating as prover...")
        prover_sock = socket(AF_INET, SOCK_STREAM)
        prover_sock.connect((HOST, PORT))
        prover_sock.settimeout(15)
        user = '******'
        party_info['socket'] = prover_sock
    elif argv[1] == '-v':
        print("Operating as verifier...")
        svr = socket(AF_INET, SOCK_STREAM)
        svr.bind((HOST, PORT))
        svr.listen(1)
        verifier_sock, addr = svr.accept()
        print("Connected by ", addr)
        user = '******'
        party_info['socket'] = verifier_sock
    else:
        print("ERROR!")
        exit(-1)

    group = PairingGroup('a.param')
    party_info['party'] = user
    party_info['setting'] = group
    # statement: '(h = g^x) and (j = g^y)'

    if (user == 'prover'):
        g = group.random(G1)
        x, y = group.random(ZR), group.random(ZR)
        pk = {'h': g**x, 'g': g, 'j': g**y}
        sk = {'x': x, 'y': y}
        #    pk = {'h':g**x, 'g':g}
        #    sk = {'x':x, 'y':y}
        result = executeIntZKProof(pk, sk, '(h = g^x) and (j = g^y)',
                                   party_info)
        print("Results for PROVER =>", result)

    elif (user == 'verifier'):
        # verifier shouldn't have this information
        #    pk = {'h':1, 'g':1, 'j':1}
        #    sk = {'x':1, 'y':1}
        pk = {'h': 1, 'g': 1, 'j': 1}
        sk = {'x': 1}
        result = executeIntZKProof(pk, sk, '(h = g^x) and (j = g^y)',
                                   party_info)
        print("Results for VERIFIER =>", result)
Ejemplo n.º 9
0
 def testZKPVoteInLib_moreParameters(self):
     groupObj = PairingGroup('BN254')
     params = 2
     msg = []
     attrs = []
     attr1 = []
     attr2 = []
     msg.append("testmessage")
     msg.append("female")
     attr1.append("testmessage")
     attr2.append("male")
     attr2.append("female")
     attrs.append(attr1)
     attrs.append(attr2)
     el = ElGamal(params)
     agho = AGHOBlind(el)
     (pk_EV, sk_EV) = el.keygen()
     h = groupObj.random(G2)
     (c, o) = el.encrypt(pk_EV, msg)
     m = el.decrypt(pk_EV, sk_EV, c, attrs)
     (ch, r) = el.ZKPsk(c, pk_EV['g'], sk_EV)
     isCorrect = el.ZKPsk_verify(c, msg, pk_EV, ch, r, pk_EV['g'])
     assert (isCorrect)
     print("ZKPVote Test Result from Library with more parameters:",
           isCorrect)
Ejemplo n.º 10
0
def main():
    global group
    group = PairingGroup(secparam)
    
    userFuncs2.groupObj = group
    builtInFuncs.util = SecretUtil(group, verbose=False)

    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four or three) and (two or one))'
    print("Attributes =>", attrs); print("Policy =>", access_policy)

    (mk, pk) = setup()

    sk = keygen(pk, mk, attrs)
    print("sk :=>", sk)

    rand_msg = group.random(GT)
    print("msg =>", rand_msg)
    ct = encrypt(pk, rand_msg, access_policy)
    print("\nCiphertext...\n")
    group.debug(ct)

    rec_msg = decrypt(pk, sk, ct)
    print("\nDecrypt...\n")
    print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    print("Successful Decryption!!!")
Ejemplo n.º 11
0
def main():
    group = PairingGroup('MNT160')
    max_attributes = 6
    required_overlap = 4
    ibe = IBE_SW05_LUC(group)
    (master_public_key, master_key) = ibe.setup(max_attributes,
                                                required_overlap)
    private_identity = [
        'insurance', 'id=2345', 'oncology', 'doctor', 'nurse', 'JHU'
    ]  #private identity
    public_identity = [
        'insurance', 'id=2345', 'doctor', 'oncology', 'JHU', 'billing', 'misc'
    ]  #public identity for encrypt
    (pub_ID_hashed, secret_key) = ibe.extract(master_key, private_identity,
                                              master_public_key,
                                              required_overlap, max_attributes)
    msg = group.random(GT)
    cipher_text = ibe.encrypt(master_public_key, public_identity, msg,
                              max_attributes)
    decrypted_msg = ibe.decrypt(master_public_key, secret_key, cipher_text,
                                pub_ID_hashed, required_overlap)
    print("msg:  ", msg)
    print("decrypted_msg:  ", decrypted_msg)
    assert msg == decrypted_msg, "failed decryption!"
    print("Successful Decryption!")
Ejemplo n.º 12
0
    def testIBE_BB04(self):
        # initialize the element object so that object references have global scope
        groupObj = PairingGroup('MNT224')
        ibe = IBE_BB04(groupObj)
        (params, mk) = ibe.setup()

        # represents public identity
        kID = groupObj.random(ZR)
        key = ibe.extract(mk, kID)

        M = groupObj.random(GT)
        cipher = ibe.encrypt(params, kID, M)
        m = ibe.decrypt(params, key, cipher)

        assert m == M, "FAILED Decryption!"
        if debug: print("Successful Decryption!! M => '%s'" % m)
Ejemplo n.º 13
0
    def test_basic(self):

        curve = 'SS512'
        group = PairingGroup(curve)
        g1 = group.random(G1)
        g2 = g1
        gT = pair(g1, g2)
        MM_SS512 = MM_GROUP(G=group, g1=g1, g2=g2, gT=gT)

        # Define security parameters
        n = 6
        d = 2

        mscheme = MM(MM_SS512)

        ps = BenignPS(mscheme)

        D = mscheme.sample(n, d) >> G1

        pk, sk = ps.gen(D)
        r = mscheme.sample(d)
        u = D * r
        pi = ps.prove(pk, u, r)

        self.assertEqual(True, ps.verify(sk, u, pi), "Should be equal")

        r = mscheme.sample(d)
        pi2 = ps.peval(pk, u, pi, r)
        u = u + D * r
        self.assertEqual(True, ps.verify(sk, u, pi2), "Should be equal")
Ejemplo n.º 14
0
def main():
    global group
    #group = PairingGroup(secparam)
    group = PairingGroup("SS512")

    alphabet = ['a', 'b']
    dfa = DFA("ab*a", alphabet)
    builtinFuncs_dfa.DFAObj = dfa
    dfaM = dfa.constructDFA()

    (mpk, msk) = setup(alphabet)

    Q, S, T, q0, F = dfaM

    (blindingFactor0Blinded, skBlinded) = keygen(mpk, msk, Q, T, F)
    w = dfa.getSymbols("abbba")
    M = group.random(GT)
    print("M :", M)
    ct = encrypt(mpk, w, M)

    (transformOutputList, l, Ti, transformOutputListForLoop) = transform(skBlinded, ct, dfaM)
    origM = decout(dfaM, transformOutputList, blindingFactor0Blinded, l, Ti, transformOutputListForLoop)


    print("rec M :", origM)
    assert M == origM, "failed decryption"
    print("SUCCESSFUL DECRYPTION!!!") 
Ejemplo n.º 15
0
def main():
    # instantiate a bilinear pairing map
    # pairing_group = PairingGroup('MNT224')
    pairing_group = PairingGroup("SS512")
    print("start")
    # AC17 CP-ABE under DLIN (2-linear)
    cpabe = BSW07(pairing_group, 2)

    # run the set up
    (pk, msk) = cpabe.setup()

    # generate a key
    attr_list = ['ONE', 'TWO', 'THREE']
    key = cpabe.keygen(pk, msk, attr_list)

    # choose a random message
    msg = pairing_group.random(GT)
    print(msg)
   
    # generate a ciphertext
    policy_str = '((ONE and THREE) and (TWO OR FOUR))'
    ctxt = cpabe.encrypt(pk, msg, policy_str)
    print(ctxt)

    # decryption
    rec_msg = cpabe.decrypt(pk, ctxt, key)
    print(rec_msg)
    if debug:
        if rec_msg == msg:
            print ("Successful decryption.")
        else:
            print ("Decryption failed.")
Ejemplo n.º 16
0
def main():
    global group
    group = PairingGroup("SS512")

    alphabet = {'a', 'b'}
    dfa = DFA("ab*a", alphabet)
    dfaM = dfa.constructDFA()

    fe = FE_DFA(group, dfa)

    (mpk, msk) = fe.setup(alphabet)
    if debug: print("mpk :=>", mpk, "\n\n")

    sk = fe.keygen(mpk, msk, dfaM)
    if debug: print("sk :=>", sk)

    w = dfa.getSymbols("abba")
    w1 = dfa.getSymbols("aba")
    M = group.random(GT)
    ct = fe.encrypt(mpk, w, M)

    # Explicitly override the string with another valid string
    ct[1] = w1
    print w1 == w

    origM = fe.decrypt(sk, ct)
    assert M == origM, "failed decryption!"
    if debug: print("Successful Decryption!!!!!")
Ejemplo n.º 17
0
def main():
    global group
    group = PairingGroup(secparam)

    userFuncs2.groupObj = group
    builtInFuncs.util = SecretUtil(group, verbose=False)

    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four or three) and (two or one))'
    print("Attributes =>", attrs)
    print("Policy =>", access_policy)

    (mk, pk) = setup()

    sk = keygen(pk, mk, attrs)
    print("sk :=>", sk)

    rand_msg = group.random(GT)
    print("msg =>", rand_msg)
    ct = encrypt(pk, rand_msg, access_policy)
    print("\nCiphertext...\n")
    group.debug(ct)

    rec_msg = decrypt(pk, sk, ct)
    print("\nDecrypt...\n")
    print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    print("Successful Decryption!!!")
Ejemplo n.º 18
0
def main():
    global group
    group = PairingGroup('SS512')

    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four or three) and (two or one))'
    #print("Attributes =>", attrs); print("Policy =>", access_policy)

    (mk, pk) = setup()

    sk = keygen(pk, mk, attrs)
    #print("sk :=>", sk)

    rand_msg = group.random(GT)
    print("msg =>", rand_msg)
    ct = encrypt(pk, rand_msg, access_policy)
    #print("\n\nCiphertext...\n")
    group.debug(ct)

    rec_msg = decrypt(pk, sk, ct)
    #print("\n\nDecrypt...\n")
    print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    print("Successful Decryption!!!")
Ejemplo n.º 19
0
def main(num=5):
	pol = generatePolicy(num)
	attr_list = generateAttrList(num)

	#Get the eliptic curve with the bilinear mapping feature needed.
	groupObj = PairingGroup('SS512')
	
	cpabe = RW13(groupObj)
	(msk, pk) = cpabe.setup()
	
	if debug: print('Acces Policy: %s' % pol)
	if debug: print('User credential list: %s' % attr_list)
	m = groupObj.random(GT)
	
	cpkey = cpabe.keygen(pk, msk, attr_list)
	if debug: print("\nSecret key: %s" % attr_list)
	if debug:groupObj.debug(cpkey)
	cipher = cpabe.encrypt(pk, m, pol)
	
	if debug: print("\nCiphertext...")
	if debug:groupObj.debug(cipher)
	orig_m = cpabe.decrypt(pk, cpkey, cipher)
	
	assert m == orig_m, 'FAILED Decryption!!!'
	if debug: print('Successful Decryption!')
	del groupObj
Ejemplo n.º 20
0
def main():
    global group
    group = PairingGroup(secparam)

    alphabet = ['a', 'b']
    dfa = DFA("ab*a", alphabet)
    builtinFuncs_dfa.DFAObj = dfa
    dfaM = dfa.constructDFA()

    (mpk, msk) = setup(alphabet)

    (blindingFactor0Blinded, skBlinded) = keygen(mpk, msk, dfaM)
    w = dfa.getSymbols("abba")
    M = group.random(GT)
    print("M :", M)
    ct = encrypt(mpk, w, M)

    transformOutputList = transform(skBlinded, ct)
    origM = decout(skBlinded, ct, transformOutputList, blindingFactor0Blinded, blindingFactorKendList1Blinded)



    print("rec M :", origM)
    assert M == origM, "failed decryption"
    print("SUCCESSFUL DECRYPTION!!!") 
def main():
    #Get the eliptic curve with the bilinear mapping feature needed.
    groupObj = PairingGroup('SS512')

    cpabe = CPabe09(groupObj)
    (msk, pk) = cpabe.setup()
    pol = '((ONE or THREE) and (TWO or FOUR))'
    attr_list = ['THREE', 'ONE', 'TWO']

    if debug: print('Acces Policy: %s' % pol)
    if debug: print('User credential list: %s' % attr_list)
    m = groupObj.random(GT)

    print('message:%s' % m)
    # individual's secret key (cpkey) is generated for each individual by AA using the individual's attribute list (attr_list)
    cpkey = cpabe.keygen(pk, msk, attr_list)
    if debug: print("\nSecret key: %s" % attr_list)
    if debug: groupObj.debug(cpkey)
    cipher = cpabe.encrypt(pk, m, pol)

    if debug: print("\nCiphertext...")
    if debug: groupObj.debug(cipher)
    orig_m = cpabe.decrypt(pk, cpkey, cipher)

    assert m == orig_m, 'FAILED Decryption!!!'
    if debug: print('Successful Decryption!')
    del groupObj
Ejemplo n.º 22
0
    def testDabe(self):
        groupObj = PairingGroup('SS512')

        dabe = Dabe(groupObj)
        GP = dabe.setup()

        #Setup an authority
        auth_attrs = ['ONE', 'TWO', 'THREE', 'FOUR']
        (SK, PK) = dabe.authsetup(GP, auth_attrs)
        if debug: print("Authority SK")
        if debug: print(SK)

        #Setup a user and give him some keys
        gid, K = "bob", {}
        usr_attrs = ['THREE', 'ONE', 'TWO']
        for i in usr_attrs:
            dabe.keygen(GP, SK, i, gid, K)
        if debug: print('User credential list: %s' % usr_attrs)
        if debug: print("\nSecret key:")
        if debug: groupObj.debug(K)

        #Encrypt a random element in GT
        m = groupObj.random(GT)
        policy = '((one or three) and (TWO or FOUR))'
        if debug: print('Acces Policy: %s' % policy)
        CT = dabe.encrypt(PK, GP, m, policy)
        if debug: print("\nCiphertext...")
        if debug: groupObj.debug(CT)

        orig_m = dabe.decrypt(GP, K, CT)

        assert m == orig_m, 'FAILED Decryption!!!'
        if debug: print('Successful Decryption!')
Ejemplo n.º 23
0
    def test_basic(self):
        # create a MM_GROUP on Curve MNT159
        curve = 'MNT159'
        group = PairingGroup(curve)
        g1 = group.random(G1)
        g2 = group.random(G2)
        gT = pair(g1, g2)
        MM_SS512 = MM_GROUP(G=group, g1=g1, g2=g2, gT=gT)

        # Define security parameters
        k = 2
        D3_2_MDDH = DK_MDDH(k, MM_SS512)

        mscheme = MM(MM_SS512)
        scheme = FFHR19(mscheme, k, D3_2_MDDH)

        pk, sk = scheme.keygen()
        msg = mscheme.sample(1, gtype=G1)
        c = scheme.encrypt(pk, msg)
        m = scheme.decrypt(pk, sk, c)
        self.assertEqual(m, msg, "Should be equal")

        c2 = scheme.rand(pk, c)
        m = scheme.decrypt(pk, sk, c2)
        self.assertEqual(m, msg, "Should be after rand too")
Ejemplo n.º 24
0
def main():   
    groupObj = PairingGroup('SS512')

    cpabe = CPabe_BSW07(groupObj)
    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four or three) and (three or one))'
    if debug:
        print("Attributes =>", attrs); print("Policy =>", access_policy)

    (pk, mk) = cpabe.setup()

    sk = cpabe.keygen(pk, mk, attrs)
    print("sk :=>", sk)

    rand_msg = groupObj.random(GT)
    if debug: print("msg =>", rand_msg)
    ct = cpabe.encrypt(pk, rand_msg, access_policy)
    if debug: print("\n\nCiphertext...\n")
    groupObj.debug(ct)

    rec_msg = cpabe.decrypt(pk, sk, ct)
    if debug: print("\n\nDecrypt...\n")
    if debug: print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    if debug: print("Successful Decryption!!!")
Ejemplo n.º 25
0
    def testIBE_BB04(self):
        # initialize the element object so that object references have global scope
        groupObj = PairingGroup('MNT224')
        ibe = IBE_BB04(groupObj)
        (params, mk) = ibe.setup()

        # represents public identity
        kID = groupObj.random(ZR)
        key = ibe.extract(mk, kID)

        M = groupObj.random(GT)
        cipher = ibe.encrypt(params, kID, M)
        m = ibe.decrypt(params, key, cipher)

        assert m == M, "FAILED Decryption!"
        if debug: print("Successful Decryption!! M => '%s'" % m)
Ejemplo n.º 26
0
    def testIBE_SW05_LUC(self):
        # initialize the element object so that object references have global scope
        groupObj = PairingGroup('SS512')
        n = 6
        d = 4
        ibe = IBE_SW05_LUC(groupObj)
        (pk, mk) = ibe.setup(n, d)
        if debug:
            print("Parameter Setup...")
            print("pk =>", pk)
            print("mk =>", mk)

        w = ['insurance', 'id=2345', 'oncology', 'doctor', 'nurse',
             'JHU']  #private identity
        wPrime = [
            'insurance', 'id=2345', 'doctor', 'oncology', 'JHU', 'billing',
            'misc'
        ]  #public identity for encrypt

        (w_hashed, sk) = ibe.extract(mk, w, pk, d, n)

        M = groupObj.random(GT)
        cipher = ibe.encrypt(pk, wPrime, M, n)
        m = ibe.decrypt(pk, sk, cipher, w_hashed, d)

        assert m == M, "FAILED Decryption: \nrecovered m = %s and original m = %s" % (
            m, M)
        if debug: print("Successful Decryption!! M => '%s'" % m)
Ejemplo n.º 27
0
def main():
    #Get the eliptic curve with the bilinear mapping feature needed.
    groupObj = PairingGroup('SS512')

    cpabe = CPabe09(groupObj)
    (msk, pk) = cpabe.setup()
    pol = '((ONE or THREE) and (TWO or FOUR))'
    attr_list = ['THREE', 'ONE', 'TWO']

    if debug: print('Acces Policy: %s' % pol)
    if debug: print('User credential list: %s' % attr_list)
    m = groupObj.random(GT)

    cpkey = cpabe.keygen(pk, msk, attr_list)
    if debug: print("\nSecret key: %s" % attr_list)
    if debug:groupObj.debug(cpkey)
    cipher = cpabe.encrypt(pk, m, pol)

    if debug: print("\nCiphertext...")
    if debug:groupObj.debug(cipher)
    orig_m = cpabe.decrypt(pk, cpkey, cipher)

    assert m == orig_m, 'FAILED Decryption!!!'
    if debug: print('Successful Decryption!')
    del groupObj
    def testCPabe_BSW07(self):
        groupObj = PairingGroup('SS512')

        cpabe = CPabe_BSW07(groupObj)
        attrs = ['ONE', 'TWO', 'THREE']
        access_policy = '((four or three) and (three or one))'
        if debug:
            print("Attributes =>", attrs)
            print("Policy =>", access_policy)

        (pk, mk) = cpabe.setup()

        sk = cpabe.keygen(pk, mk, attrs)

        rand_msg = groupObj.random(GT)
        if debug: print("msg =>", rand_msg)
        ct = cpabe.encrypt(pk, rand_msg, access_policy)
        if debug: print("\n\nCiphertext...\n")
        groupObj.debug(ct)

        rec_msg = cpabe.decrypt(pk, sk, ct)
        if debug: print("\n\nDecrypt...\n")
        if debug: print("Rec msg =>", rec_msg)

        assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
        if debug: print("Successful Decryption!!!")
Ejemplo n.º 29
0
def basicTest2():
    '''Month-based attributes are used'''
    print("RUN basicTest2")
    groupObj = PairingGroup('SS512')
    tbpre = TBPRE(groupObj)
    attributes = ["ONE", "TWO", "THREE", "FOUR"]
    MK, PK, s, H = tbpre.setup(attributes)

    users = {}  # public

    alice = {'id': 'alice'}
    alice['sku'], users[alice['id']] = tbpre.registerUser(PK, H)

    year = {'year': "2014", 'month': '2'}

    for attr in attributes[0:-1]:
        tbpre.keygen(MK, PK, H, s, alice, users[alice['id']], attr, year)

    k = groupObj.random(GT)

    policy = [['ONE', 'THREE'],
              ['TWO', 'FOUR']]  # [['ONE' and 'THREE'] or ['TWO' and 'FOUR']]
    currentDate = {'year': "2014", 'month': "2", 'day': "15"}

    CT = tbpre.encrypt(PK, policy, k)
    CTt = tbpre.reencrypt(PK, H, s, CT, currentDate)
    PT = tbpre.decrypt(CTt, alice)

    assert k == PT, 'FAILED DECRYPTION!'
    print('SUCCESSFUL DECRYPTION')
Ejemplo n.º 30
0
def main():
    global group
    group = PairingGroup("SS512")

    alphabet = ['a', 'b']
    dfa = DFA("ab*a", alphabet)
    builtinFuncs_dfa.DFAObj = dfa
    dfaM = dfa.constructDFA()

    (mpk, msk) = setup(alphabet)

    Q, S, T, q0, F = dfaM

    (blindingFactor0Blinded, skBlinded) = keygen(mpk, msk, Q, T, F)
    w = dfa.getSymbols("abbba")
    M = group.random(GT)
    print("M :", M)
    ct = encrypt(mpk, w, M)

    (transformOutputList, Ti) = transform(skBlinded, ct, dfaM)
    origM = decout(transformOutputList, blindingFactor0Blinded, Ti, dfaM)


    print("rec M :", origM)
    assert M == origM, "failed decryption"
    print("SUCCESSFUL DECRYPTION!!!") 
Ejemplo n.º 31
0
def main():
    global group
    group = PairingGroup("SS512")

    max_attributes = 6
    required_overlap = 4
    #(master_public_key, master_key) = setup(max_attributes, required_overlap)
    (master_public_key, master_key) = setup(max_attributes)
    private_identity = [
        'insurance', 'id=2345', 'oncology', 'doctor', 'nurse', 'JHU'
    ]  #private identity
    public_identity = [
        'insurance', 'id=2345', 'doctor', 'oncology', 'JHU', 'billing', 'misc'
    ]  #public identity for encrypt
    (blindingFactor0Blinded,
     skBlinded) = extract(master_key, private_identity, master_public_key,
                          required_overlap, max_attributes)
    msg = group.random(GT)
    cipher_text = encrypt(master_public_key, public_identity, msg,
                          max_attributes)
    #decrypted_msg = decrypt(master_public_key, secret_key, cipher_text, required_overlap)
    (transformOutputList, SKeys, SLen) = transform(master_public_key,
                                                   skBlinded, cipher_text,
                                                   required_overlap)
    decrypted_msg = decout(master_public_key, required_overlap,
                           transformOutputList, blindingFactor0Blinded, SKeys,
                           SLen)

    print("msg:  ", msg)
    print("decrypted_msg:  ", decrypted_msg)
    assert msg == decrypted_msg, "failed decryption!"
    print("Successful Decryption!")
Ejemplo n.º 32
0
def test():
    # Just testing
    G = PairingGroup('SS512')
    IDS = OkamotoEph(G)

    g = G.random(G1, 2)
    sk = G.random(ZR, 2)
    pk = g[0]**sk[0] * g[1]**sk[1]

    p = {'sk': sk, 'g': g}
    v = {'pk': pk, 'g': g}

    v.update(IDS.commit(p))
    p.update(IDS.challenge(v))
    v.update(IDS.answer(p))
    print(IDS.verify(v))
Ejemplo n.º 33
0
def main():
    groupObj = PairingGroup('SS512')

    cpabe = TrapAC(groupObj)
    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four AND two) OR (three AND one))'
    valid_attr = ['ONE', 'THREE']  # attribute in period time
    if debug:
        print("Attributes =>", attrs)
        print("Policy =>", access_policy)

    (pk, mk) = cpabe.setup()

    sk = cpabe.keygen(pk, mk, attrs)
    # print("sk :=>", sk)

    rand_msg = groupObj.random(GT)
    if debug: print("msg =>", rand_msg)
    ct = cpabe.encrypt(pk, rand_msg, access_policy)
    if debug: print("\n\nCiphertext...\n")
    groupObj.debug(ct)
    rect = cpabe.proxy_decrypt(pk, sk, ct, valid_attr)
    if debug: print("\n\nproxy_decrypt...\n")

    rec_msg = cpabe.decrypt(pk, sk, rect)
    if debug: print("\n\nDecrypt...\n")
    if debug: print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    if debug: print("Successful Decryption!!!")
Ejemplo n.º 34
0
def main():
    global group
    group = PairingGroup("SS512")

    attrs = ["ONE", "TWO", "THREE"]
    access_policy = "((four or three) and (two or one))"
    # print("Attributes =>", attrs); print("Policy =>", access_policy)

    (mk, pk) = setup()

    sk = keygen(pk, mk, attrs)
    # print("sk :=>", sk)

    rand_msg = group.random(GT)
    print("msg =>", rand_msg)
    ct = encrypt(pk, rand_msg, access_policy)
    # print("\n\nCiphertext...\n")
    group.debug(ct)

    rec_msg = decrypt(pk, sk, ct)
    # print("\n\nDecrypt...\n")
    print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    print("Successful Decryption!!!")
Ejemplo n.º 35
0
def main():
    groupObj = PairingGroup('SS512')

    dabe = Dabe(groupObj)
    GP = dabe.setup()

    #Setup an authority
    auth_attrs= ['ONE', 'TWO', 'THREE', 'FOUR']
    (SK, PK) = dabe.authsetup(GP, auth_attrs)
    if debug: print("Authority SK")
    if debug: print(SK)

    #Setup a user and give him some keys
    gid, K = "bob", {}
    usr_attrs = ['THREE', 'ONE', 'TWO']
    for i in usr_attrs: dabe.keygen(GP, SK, i, gid, K)
    if debug: print('User credential list: %s' % usr_attrs)
    if debug: print("\nSecret key:")
    if debug: groupObj.debug(K)

    #Encrypt a random element in GT
    m = groupObj.random(GT)
    policy = '((one or three) and (TWO or FOUR))'
    if debug: print('Acces Policy: %s' % policy)
    CT = dabe.encrypt(PK, GP, m, policy)
    if debug: print("\nCiphertext...")
    if debug: groupObj.debug(CT)

    orig_m = dabe.decrypt(GP, K, CT)

    assert m == orig_m, 'FAILED Decryption!!!'
    if debug: print('Successful Decryption!')
def basicTest():
    print("RUN basicTest")
    groupObj = PairingGroup('SS512')
    maabe = MAABE(groupObj)
    GPP, GMK = maabe.setup()

    users = {}  # public user data
    authorities = {}

    authorityAttributes = ["ONE", "TWO", "THREE", "FOUR"]
    authority1 = "authority1"

    maabe.setupAuthority(GPP, authority1, authorityAttributes, authorities)

    alice = {'id': 'alice', 'authoritySecretKeys': {}, 'keys': None}
    alice['keys'], users[alice['id']] = maabe.registerUser(GPP)

    for attr in authorityAttributes[0:-1]:
        maabe.keygen(GPP, authorities[authority1], attr, users[alice['id']],
                     alice['authoritySecretKeys'])

    k = groupObj.random(GT)

    policy_str = '((ONE or THREE) and (TWO or FOUR))'

    CT = maabe.encrypt(GPP, policy_str, k, authorities[authority1])

    PT = maabe.decrypt(GPP, CT, alice)

    # print "k", k
    # print "PT", PT

    assert k == PT, 'FAILED DECRYPTION!'
    print('SUCCESSFUL DECRYPTION')
Ejemplo n.º 37
0
def main():
	global benchmarkResult, options

	options=parse_args()

	# SS512 : a symmertic curve with a 512-bit base field
	# MNT159 : an asymmetric curve with a 159-bit based field
	groupObj = PairingGroup ('SS512')
	generator = groupObj.random(G1)
	# for optimization 
	assert generator.initPP(), "failed to init pre-computation table"

	# initialize key server and user objects
	ks = KS (groupObj, generator)
	user = User (groupObj, generator)

	# set up key server
	pk=ks.setup()

	if options.output_file is not None:
		rf=open(options.output_file, "w")
	else:
		rf=sys.stdout
	rf.write ("#KB\tN.KS\tN.kss\tD1\tD2\tHash\tSE\tGroup\tKS\tTo.\tTo.(CR)\tTo.(SE)\n")

	sys.stderr.write ("Run experiment...\n")

	if options.file_size > 0:
		file_size=[options.file_size]

	for fsize in file_size:
		# generate sample file
		create_file (sample_file, fsize)

		benchmarkResult={}
		for count in range (0,options.trials, 1):
			# compute a hash for a file
			h=user.computeHash(sample_file)

			# generate tag and decryption key
			t_F, dk_F = user.generate_key_and_tag(pk, h, ks)
		
			# encrypt a file
			C1,C2,C3=user.encrypt (t_F,pk,sample_file,h)


		delay_Hash=round(benchmarkResult['Hash']*1000/options.trials,2)
		delay_SE=round(benchmarkResult['SE']*1000/options.trials,2)
		delay_Group=round(benchmarkResult['Group']*1000/options.trials,2)
		delay_KS=round(benchmarkResult['KS']*1000/options.trials,2)
		delay_total=round(delay_Hash+delay_SE+delay_Group+delay_KS,2)
		delay_total_cr=round(delay_Hash+delay_Group+delay_KS,2)
		delay_total_SE=delay_SE

		rf.write("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}\n".format(\
			int(fsize/1024), options.num_of_KS, options.num_of_kss, options.KS_delay1, options.KS_delay2,\
			delay_Hash, delay_SE, delay_Group, delay_KS,delay_total,delay_total_cr,delay_total_SE))
			
	rf.close()
Ejemplo n.º 38
0
def benchmark():
    groupObj1 = PairingGroup('MNT224')
    groupObj2 = PairingGroup('MNT224')
    ekpabe = EKPabe(groupObj1)
    kpabe = KPabe(groupObj2)

    t1_s = 0
    t1_k = 0
    t1_e = 0
    t1_d = 0
    t2_s = 0
    t2_k = 0
    t2_e = 0
    t2_d = 0

    attributes = ['ONE', 'TWO', 'THREE', 'FOUR']
    policy = 'THREE and (ONE or TWO)'
    msg1 = b"Some Random Message"
    msg2 = groupObj2.random(GT)

    for b in range(4):
        start = clock()
        (epk, emk) = ekpabe.setup(attributes)
        t1_s += clock() - start

        start = clock()
        (pk, mk) = kpabe.setup()
        t2_s += clock() - start

        start = clock()
        emykey = ekpabe.keygen(epk, emk, policy)
        t1_k += clock() - start

        start = clock()
        mykey = kpabe.keygen(pk, mk, policy)
        t2_k += clock() - start

        for i in range(50):
            start = clock()
            eciphertext = ekpabe.encrypt(epk, msg1, attributes)
            t1_e += clock() - start

            start = clock()
            ciphertext = kpabe.encrypt(pk, msg2, attributes)
            t2_e += clock() - start

            start = clock()
            erec_msg = ekpabe.decrypt(eciphertext, emykey)
            t1_d += clock() - start

            start = clock()
            rec_msg = kpabe.decrypt(ciphertext, mykey)
            t2_d += clock() - start

            assert msg1 == erec_msg
            assert msg2 == rec_msg

    print("yct14 s=%s k=%s e=%s d=%s" % (t1_s, t1_k, t1_e, t1_d))
    print("lsw08 s=%s k=%s e=%s d=%s" % (t2_s, t2_k, t2_e, t2_d))
Ejemplo n.º 39
0
def test(number_of_attr, split_attributes):
    group = PairingGroup('SS512')
    msg = group.random(GT)

    g1, g2 = group.random(G1), group.random(G2)
    alpha, a = group.random(), group.random()
    cpabe = CPabe09(group)
    (master_secret_key, master_public_key) = cpabe.setup(g1, g2, alpha, a)

    attr_list = ['ATTR' + str(n) for n in range(number_of_attr)]
    policy = '(' + ' and '.join(attr_list[:split_attributes]) + \
        ') and (' + ' or '.join(attr_list[split_attributes:]) + ')'

    secret_key = cpabe.keygen(master_public_key, master_secret_key, attr_list)
    cypher_text = cpabe.encrypt(master_public_key, msg, policy)

    decrypted_msg = cpabe.decrypt(master_public_key, secret_key, cypher_text)
Ejemplo n.º 40
0
 def MsgTestAESCBCSeperate(self, msg):
     groupObj = PairingGroup('SS512')
     ran = groupObj.random(GT)
     a = AuthenticatedCryptoAbstraction(sha1(ran))
     ct = a.encrypt(msg)
     b = AuthenticatedCryptoAbstraction(sha1(ran))
     dmsg = b.decrypt(ct)
     assert msg == dmsg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
Ejemplo n.º 41
0
def main(argv):
    HOST, PORT = "", 8090
    party_info = {}
    if argv[1] == '-p':
        print("Operating as prover...")
        prover_sock = socket(AF_INET, SOCK_STREAM)
        prover_sock.connect((HOST, PORT))
        prover_sock.settimeout(15)
        user = '******'
        party_info['socket'] = prover_sock
    elif argv[1] == '-v':
        print("Operating as verifier...")
        svr = socket(AF_INET, SOCK_STREAM)
        svr.bind((HOST, PORT))
        svr.listen(1)
        verifier_sock, addr = svr.accept()
        print("Connected by ", addr)
        user = '******'
        party_info['socket'] = verifier_sock
    else:
        print("ERROR!")
        exit(-1)

    group = PairingGroup('a.param')
    party_info['party'] = user
    party_info['setting'] = group
    # statement: '(h = g^x) and (j = g^y)'

    if(user == 'prover'):
        g = group.random(G1)
        x,y = group.random(ZR), group.random(ZR)
        pk = {'h':g ** x, 'g':g, 'j':g**y}
        sk = {'x':x, 'y':y}
    #    pk = {'h':g**x, 'g':g}
    #    sk = {'x':x, 'y':y}
        result = executeIntZKProof(pk, sk, '(h = g^x) and (j = g^y)', party_info)
        print("Results for PROVER =>", result)

    elif(user == 'verifier'):
        # verifier shouldn't have this information
    #    pk = {'h':1, 'g':1, 'j':1}
    #    sk = {'x':1, 'y':1} 
        pk = {'h':1, 'g':1, 'j':1}
        sk = {'x':1}
        result = executeIntZKProof(pk, sk, '(h = g^x) and (j = g^y)', party_info)
        print("Results for VERIFIER =>", result)
Ejemplo n.º 42
0
class Context:
    def __init__(self):
        self.group = PairingGroup('MNT159')

        self.g1 = self.group.random(G1)
        self.g2 = self.group.random(G2)

        self.gt = pair(self.g1, self.g2)
Ejemplo n.º 43
0
    def testPairingGroup(self):    
        groupobj = PairingGroup('SS512')
        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)
Ejemplo n.º 44
0
 def MsgTestAESCBCSeperate(self,msg):
     groupObj = PairingGroup('SS512')
     ran = groupObj.random(GT)
     a =  AuthenticatedCryptoAbstraction(sha1(ran))
     ct = a.encrypt(msg)        
     b =  AuthenticatedCryptoAbstraction(sha1(ran))
     dmsg = b.decrypt(ct);
     assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
Ejemplo n.º 45
0
def tes():
    group = PairingGroup('SS512')
    g, gp = group.random(G1), group.random(G2)
    alpha, beta = group.random(ZR), group.random(ZR)
    # initialize pre-processing for generators
    print g,gp
    g.initPP()
    gp.initPP()

    print gp
    print g

    e_gg_alpha = pair(g, gp ** alpha)
    e_gg_alpha2 = pair(g,gp) ** alpha
    if e_gg_alpha == e_gg_alpha2:
        print 'true'
    else:
        print 'false'
Ejemplo n.º 46
0
class AttributeAuthority:
	'''
	The attribtue authority class that encapsulates the master key used to generate
	the single public key and user private keys
	'''

	def __init__(self):
		self.groupObj = PairingGroup('SS512') # MNT224, SS512, MNT159, SS1024
		self.cpabe = CPabe_BSW07(self.groupObj)
		(self.public, self.master) = self.cpabe.setup()
		# later functionality would include a thread that periodically updates the keys when needed

	def set(self, master, public):
		self.master = master
		self.public = public

	def getValues(self):
		return (self.master, self.public)

	def generateUserKey(self, attributes):
		return self.cpabe.keygen(self.public, self.master, attributes)

	def getPublicKey(self):
		return self.public

	def encrypt(self, plaintext, policy):
		#return self.cpabe.encrypt(self.public, plaintext, policy)
		key = self.groupObj.random(GT)
		c1 = self.cpabe.encrypt(self.public, key, policy)

        # instantiate a symmetric enc scheme from this key
		cipher = AuthenticatedCryptoAbstraction(sha1(key))
		c2 = cipher.encrypt(plaintext)
		return { 'c1':c1, 'c2':c2 }

	def decrypt(self, sKey, ciphertext):
		#return self.cpabe.decrypt(self.public, sKey, ciphertext)
		c1, c2 = ciphertext['c1'], ciphertext['c2']
		success = True

		# TODO: we need to supress the print statement that comes out of this guy, to avoid unnecessary events
		try:
			key = self.cpabe.decrypt(self.public, sKey, c1)
			if (key == False):
				success = False
		except: 
			success = False

		# Try to perform the encryption if we were able to recover the key
		plaintext = None
		if (success == True):
			cipher = AuthenticatedCryptoAbstraction(sha1(key))
			plaintext = cipher.decrypt(c2)
		return (success, plaintext)
Ejemplo n.º 47
0
def main():

    group = PairingGroup('MNT224', secparam=1024)    
    ibe = IBE_Chen12_z(group)
    (master_public_key, master_secret_key) = ibe.setup()
    ID = '*****@*****.**'
    private_key = ibe.extract(master_secret_key, ID)
    msg = group.random(GT)
    cipher_text = ibe.encrypt(master_public_key, ID, msg)
    decryptedMSG = ibe.decrypt(master_public_key, private_key, cipher_text)
    print (decryptedMSG==msg)
Ejemplo n.º 48
0
def CPABE():
    group = PairingGroup('SS512')
    cpabe = CPabe_BSW07(group)
    (pk,mk) = cpabe.setup()
    policy = 'ID1 or ID2 or ID3'
    asl =['ID1']
    msg = group.random(GT)
    ct = cpabe.encrypt(pk,msg,policy)
    sk = cpabe.keygen(pk,mk,asl)
    plaintext = cpabe.decrypt(pk,sk,ct)
    print plaintext
    print msg
Ejemplo n.º 49
0
def main():
    group = PairingGroup('MNT224')
    waters_hash = Waters(group)
    ibe = IBE_N04_z(group)
    (master_public_key, master_key) = ibe.setup()

    ID = "*****@*****.**"
    secret_key = ibe.extract(master_key, ID)
    msg = group.random(GT)
    cipher_text = ibe.encrypt(master_public_key, ID, msg)
    decrypted_msg = ibe.decrypt(master_public_key, secret_key, cipher_text)
    assert msg == decrypted_msg, "invalid decryption"
    if debug: print("Successful Decryption!")
Ejemplo n.º 50
0
 def testInterleave(self):
     trials = 10
     trials2 = trials * 3 
     group1 = PairingGroup("MNT224")
     group2 = PairingGroup("MNT224")
     
     g = group1.random(G1)
     h = group1.random(G1)
     i = group1.random(G2)
     
     self.assertTrue(group1.InitBenchmark())
     self.assertTrue(group2.InitBenchmark())
     group1.StartBenchmark(["RealTime", "Exp", "Pair", "Div", "Mul"])
     for a in range(trials):
         j = g * h 
         k = i ** group1.random(ZR)
         t = (j ** group1.random(ZR)) / h 
         n = pair(h, i)
     group1.EndBenchmark()
     msmtDict = group1.GetGeneralBenchmarks()
     del group1, group2
     self.assertTrue(isSaneBenchmark(msmtDict))
Ejemplo n.º 51
0
def main():

    #group = PairingGroup('MNT159', secparam=1024)    
    G = PairingGroup('SS512')

    ibe = IBE_BB04_m(G)
    (master_public_key, master_secret_key) = ibe.setup()
    ID = '*****@*****.**'
    private_key = ibe.extract(master_secret_key, ID)
    msg = G.random(GT)
    cipher_text = ibe.encrypt(master_public_key, ID, msg)
    decryptedMSG = ibe.decrypt(master_public_key, private_key, cipher_text)
    print (decryptedMSG==msg)
Ejemplo n.º 52
0
def main():
    global group
    group = PairingGroup(secparam)

    gpk = setup()
    (msk, pk) = authsetup(gpk, ['ONE', 'TWO', 'THREE', 'FOUR'])
    sk = keygen(gpk, msk, "*****@*****.**", ['ONE', 'TWO', 'THREE'])
    M = group.random(GT)
    ct = encrypt(pk, gpk, M, '((four or three) and (two or one))')
    M2 = decrypt(sk, ct)
    #'''
    print(M)
    print("\n\n\n")
    print(M2)
Ejemplo n.º 53
0
def keygen(pk, msk, S):
    group = PairingGroup('SS512')

    attributes = [unicode(a) for a in S]
    z = group.random()
    r = group.random()
    alpha = msk['alpha']
    K0 = ((pk['g'] ** alpha) * (pk['w'] ** r)) ** (1/z)
    K1 = pk['g'] ** (r/z)
    K_x_2, K_x_3 = {},{}
    for attr in attributes:
        ri = group.random()
        K_x_2[attr] = pk['g'] ** (ri/z)
        K_x_2[attr] = objectToBytes(K_x_2[attr], group)
        K_x_3[attr] = ((((pk['u'] ** group.hash(unicode(attr),ZR))) * pk['h']) ** (ri/z)) * (pk['v'] ** (-r/z))
        K_x_3[attr] = objectToBytes(K_x_3[attr], group)
    ik = {'S':S,
          'K0':objectToBytes(K0, group),
          'K1':objectToBytes(K1, group),
          'Ki2':K_x_2,
          'Ki3':K_x_3}
    sk = objectToBytes(z, group)
    return {'ik':ik, 'sk':sk}
Ejemplo n.º 54
0
 def testCommitment_GS08(self):
     groupObj = PairingGroup('SS512')
     cm = Commitment_GS08(groupObj)
    
     pk = cm.setup()
     if debug: 
         print("Public parameters...")
         print("pk =>", pk)
     
     m = groupObj.random(G1)
     if debug: print("Committing 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!!!")
Ejemplo n.º 55
0
def pre_enc(P, pk=None, pool=None):
    group = PairingGroup('SS512')
    if pk is None:
        pk = getPK(stsConfig['TS_ip'],stsConfig['api_getPK'])
    if type(pk['g']) == type(''):
        pk = dictToObject(pk_dict=pk, group=group)
    if pool is None or not pool.has_key('s') or not pool.has_key('key') or not pool.has_key('C0'):
        pool = {'components':[]}
        s = group.random()
        pool['s'] = s
        pool['key'] = pk['eggalpha'] ** s
        pool['C0'] = pk['g'] ** s

    for j in range(P):
        component = {}
        component['lambda_prime_j'] = group.random()
        component['t_j'] = group.random()
        component['x_j'] = group.random()
        component['C_j_1'] = (pk['w'] ** component['lambda_prime_j']) * (pk['v'] ** component['t_j'])
        component['C_j_2'] = ((pk['u'] ** component['x_j']) * pk['h']) ** (-component['t_j'])
        component['C_j_3'] = pk['g'] ** component['t_j']
        pool['components'].append(component)
        
    return pool
Ejemplo n.º 56
0
def main():
    group = PairingGroup('MNT160')
    max_attributes = 6
    required_overlap = 4
    ibe = IBE_SW05_LUC(group)
    (master_public_key, master_key) = ibe.setup(max_attributes, required_overlap)
    private_identity = ['insurance', 'id=2345', 'oncology', 'doctor', 'nurse', 'JHU'] #private identity
    public_identity = ['insurance', 'id=2345', 'doctor', 'oncology', 'JHU', 'billing', 'misc'] #public identity for encrypt
    (pub_ID_hashed, secret_key) = ibe.extract(master_key, private_identity, master_public_key, required_overlap, max_attributes)
    msg = group.random(GT)
    cipher_text = ibe.encrypt(master_public_key, public_identity, msg, max_attributes)
    decrypted_msg = ibe.decrypt(master_public_key, secret_key, cipher_text, pub_ID_hashed, required_overlap)
    print("msg:  ", msg)
    print("decrypted_msg:  ", decrypted_msg)
    assert msg == decrypted_msg, "failed decryption!"
    print("Successful Decryption!")
Ejemplo n.º 57
0
def main():
    global group
    group = PairingGroup("SS512")

    (mpk, mk) = setup(5, 32)
    (pkBlinded, blindingFactor0Blinded, skBlinded) = keygen(mpk, mk, "test")
    M = group.random(GT)
    print(M)
    print("\n\n\n")
    ct = encrypt(mpk, pkBlinded, M)
    transformOutputList = transform(pkBlinded, skBlinded, ct)
    M2 = decout(pkBlinded, skBlinded, ct, transformOutputList, blindingFactor0Blinded)
    print(M2)

    if (M == M2):
        print("it worked")
Ejemplo n.º 58
0
    def testIBE_CKRS(self):
        groupObj = PairingGroup('SS512')
        ibe = IBE_CKRS(groupObj)
        (mpk, msk) = ibe.setup()

        # represents public identity
        ID = "*****@*****.**"
        sk = ibe.extract(mpk, msk, ID)

        M = groupObj.random(GT)
        ct = ibe.encrypt(mpk, ID, M)
        m = ibe.decrypt(mpk, sk, ct)
        if debug: print('m    =>', m)

        assert m == M, "FAILED Decryption!"
        if debug: print("Successful Decryption!!! m => '%s'" % m)
Ejemplo n.º 59
0
def main():
    global group
    group = PairingGroup(secparam)

    (mpk, msk) = setup(5, 32)
    (blindingFactord0Blinded, skBlinded) = extract(mpk, msk, "test")
    M = group.random(GT)
    print(M)
    print("\n\n\n")
    ct = encrypt(mpk, M, "test")
    transformOutputList = transform(skBlinded, ct)
    M2 = decout(skBlinded, ct, transformOutputList, blindingFactord0Blinded)
    print(M2)

    if M == M2:
        print("it worked")