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(): 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!!!!!")
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!!!")
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!!!")
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!!!")
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!!!")
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()
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)
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)
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)
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
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)
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!")
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)
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!!!")
def main(): global group group = PairingGroup('SS512') (mpk, msk) = setup() sk = keygen(mpk, msk, "*****@*****.**") M = group.random(GT) print(M) print("\n\n\n") ct = encrypt(mpk, M, "*****@*****.**") M2 = decrypt(ct, sk) print(M2) if (M == M2): print("successful decryption!!!") else: print("failed decryption.")
def main(): groupObj = PairingGroup('MNT224') ec_kpabe = EcKPabe(groupObj) attributes = [ 'ONE', 'TWO', 'THREE', 'FOUR' ] (pk, mk, g) = ec_kpabe.setup(attributes) (r_u,Cert_u,d_u,Q_u)= ec_kpabe.register(g,mk) #DU (r_A,Cert_A,d_A,Q_A)= ec_kpabe.register(g,mk) #AA (r_cloud,Cert_cloud,d_cloud,Q_cloud)= ec_kpabe.register(g,mk) #CSP # policy = '(ONE or THREE) and (THREE or TWO)' policy = 'THREE and (ONE or TWO)' msg = b"Some Random Message" if debug: print("Encrypt under these attributes: ", attributes) ciphertext = ec_kpabe.encrypt(Q_A, msg, attributes) if debug: print(ciphertext) attrkey = ec_kpabe.keygen(policy, d_A, Q_u) (token,h) = ec_kpabe.tokengen( attrkey, d_u, Q_cloud) prodT = ec_kpabe.CLoud_decrypt(ciphertext, token, d_cloud, Q_u) rec_msg = ec_kpabe.decrypt(ciphertext,prodT,h) assert rec_msg if debug: print("rec_msg=%s" % str(rec_msg)) assert msg == rec_msg if debug: print("Successful Decryption!")
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)
def testHybridIBEnc(self): groupObj = PairingGroup('SS512') ibe = IBE_BB04(groupObj) hashID = HashIDAdapter(ibe, groupObj) hyb_ibe = HybridIBEnc(hashID, groupObj) (pk, mk) = hyb_ibe.setup() kID = '*****@*****.**' sk = hyb_ibe.extract(mk, kID) msg = b"This is a test message." ct = hyb_ibe.encrypt(pk, kID, msg) if debug: print("Ciphertext") print("c1 =>", ct['c1']) print("c2 =>", ct['c2']) decrypted_msg = hyb_ibe.decrypt(pk, sk, ct) if debug: print("Result =>", decrypted_msg) assert decrypted_msg == msg del groupObj
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!")
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")
def playground2(): print("api hit") final_response = "" res = json.loads(request.data) attributes = res['predicate'].split(' AND ') # print(res['predicate']) # print(attributes) try: group = PairingGroup('MNT159') absinst = ABS(group) trustee_public_key = absinst.trusteesetup(attributes) attribute_secret_key, attribute_public_key = absinst.authoritysetup( trustee_public_key) signing_key = absinst.generateattributes(attribute_secret_key, attributes) sign = absinst.sign((trustee_public_key, attribute_public_key), signing_key, 'message', res['predicate']) tpk = absinst.encodestr(trustee_public_key) apk = absinst.encodestr(attribute_public_key) ask = absinst.encodestr(attribute_secret_key) sign = absinst.encodestr(sign) final_response = { 'attribute_length': len(attributes), 'tpk': tpk, 'apk': apk, 'ask': ask, 'signature': sign } except Exception: final_response = {"response": "error"} # json_object = json.dumps(final_response) print(final_response) return final_response
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, transformOutputList, blindingFactor0Blinded) print(M2) if (M == M2): print("it worked")
def __init__(self, messages=None, groupObj=None, common_input=None): Protocol.__init__(self, None) receiver_states = { 2:self.receiver_init2, 4:self.receiver_transfer4, 6:self.receiver_transfer6, 8:self.receiver_transfer8 } sender_states = { 1:self.sender_init1, 3:self.sender_init3, 5:self.sender_transfer5, 7:self.sender_transfer7, 9:self.sender_transfer9 } receiver_trans = { 2:4, 4:6, 6:8 } sender_trans = { 1:3, 3:[3,5], 5:7, 7:9 } # describe the parties involved and the valid transitions Protocol.addPartyType(self, RECEIVER, receiver_states, receiver_trans) Protocol.addPartyType(self, SENDER, sender_states, sender_trans, True) # Protocol.setSerializers(self, self.serialize, self.deserialize) # make sure if groupObj == None: self.group = PairingGroup('SS512') else: self.group = groupObj # proof parameter generation if common_input == None: # generate common parameters to P and V db = {} self.__gen_setup = True else: # can be used as a sub-protocol if common_input is specified by caller db = common_input self.__gen_setup = False Protocol.setSubclassVars(self, self.group, db) if messages != None: self.M, self.sig = [], [] for i in range(0, len(messages)): self.M.append( bytes(messages[i], 'utf8') ) print("bytes =>", self.M[i],", message =>", messages[i])
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)
def __init__(self, keyManager): self.groupObj = PairingGroup('SS512') self.cpabe = CPabe_BSW07(self.groupObj) (self.public, self.master) = self.cpabe.setup() # Register with the key manager keyManager.addCipher(self)
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")
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)
def __init__(self, par, p=0): ''' initializes an ElGamal object with the number of parameters and the pairing group ''' PKEnc.__init__(self) global group self.params = par group = PairingGroup('BN254')
def encrypt_boyen(index, master_key, public_keys, private_key, message): master_key = decode(master_key) public_keys = decode(public_keys) private_key = decode(private_key) boyen = Boyen(PairingGroup('MNT224')) boyen.setup() return encode( boyen.sign(index, master_key, public_keys, private_key, message))
def __init__(self, groupObj=None): if groupObj is None: from charm.toolbox.pairinggroup import PairingGroup groupObj = PairingGroup('SS512', secparam=512) global group group = groupObj mask = 'ed27dbfb02752e0e16bc4502d6c732bc5f1cc92ba19b2d93a4e95c597ca42753e93550b52f82b6c13fb8cc0c2fc64487' self._mask = bytes.fromhex(mask)
def __init__(self, uid): self.group = PairingGroup('MNT224') self.gs_protocol = eval(GS_PROTOCOL)(self.group) self.path = f'parameters/{GS_PROTOCOL.lower()}' gpk_path = os.path.join(self.path, 'public/gpk') self.gpk = bytesToObject(open(gpk_path, 'rb').read(), self.group) sk_path = os.path.join(self.path, f'users/{uid:02d}/sk') self.sk = bytesToObject(open(sk_path, 'rb').read(), self.group)
def test(): # Just testing G = PairingGroup('MNT224') IDS = OkamotoRom(G) g = [G.random(G2), G.random(G2)] 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))
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)
def __init__(self, groupObj=False): ABEnc.__init__(self) global util, group if groupObj == False: group = PairingGroup('SS512') else: group = groupObj util = SecretUtil(groupObj, debug)
def test(number_of_attr, split_attributes): group = PairingGroup('MNT224') msg = group.random(GT) cpabe = AC17CPABE(group, 2) (public_key, master_secret_key) = cpabe.setup() 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(public_key, master_secret_key, attr_list) cypher_text = cpabe.encrypt(public_key, msg, policy) dec_msg = cpabe.decrypt(public_key, cypher_text, secret_key) if not msg == dec_msg: print('Failed decryption')
def main(): group = PairingGroup('MNT159') absinst = ABS(group) data = json.loads(sys.stdin.readline()) ask = absinst.decodestr(data['ask']) ska = absinst.generateattributes(ask,['HRD','SCHIEF']) response = {"ska":absinst.encodestr(ska)} print(json.dumps(response))
def testTamperAlg(self): key = sha1(PairingGroup('SS512').random(GT)) m = MessageAuthenticator(key) a = m.mac('hello world') m1 = MessageAuthenticator(key) m1._algorithm = "alg" # bypassing the algorithm check to verify the mac is over the alg + data a["alg"] = "alg" assert not m1.verify(a), "expected message to verify"
def deserialize_PKs(_PKs): PKs = {} PKs['group'] = PairingGroup(_PKs['curve'], secparam=_PKs['secparam']) for k in ['g', 'X', 'Y']: PKs[k] = PKs['group'].deserialize(_PKs[k]) for k in ['l', 'q']: PKs[k] = _PKs[k] return PKs
def generate_signatures_main(argv, same_signer=True): if ((len(argv) != 7) or (argv[1] == "-help") or (argv[1] == "--help")): sys.exit( "Usage: python " + argv[0] + " [# of valid messages] [# of invalid messages] [size of each message] [prefix name of each message] [name of valid output dictionary] [name of invalid output dictionary]" ) global group, prefixName group = PairingGroup(CURVE) chch.group = group hess.group = group #setup parameters numValidMessages = int(sys.argv[1]) numInvalidMessages = int(sys.argv[2]) messageSize = int(sys.argv[3]) prefixName = sys.argv[4] validOutputDictName = sys.argv[5] invalidOutputDictName = sys.argv[6] # 1. generate keys (g2, alpha, P) = hess.setup() f_mpk = open('mpk.charmPickle', 'wb') # 2. serialize the pk's pick_mpk = objectToBytes({'g2': g2, 'P': P}, group) f_mpk.write(pick_mpk) f_mpk.close() pklist = {} sklist = {} for z in range(0, numValidMessages): (pklist[z], sklist[z]) = hess.keygen(alpha, "test" + str(z) + "@email.com") f_pk = open('pk.charmPickle', 'wb') # 2. serialize the pk's pick_pk = objectToBytes(pklist, group) f_pk.write(pick_pk) f_pk.close() validOutputDict = {} validOutputDict[0] = {} validOutputDict[0]['mpk'] = 'mpk.charmPickle' validOutputDict[0]['pk'] = 'pk.charmPickle' invalidOutputDict = {} invalidOutputDict[0] = {} invalidOutputDict[0]['mpk'] = 'mpk.charmPickle' invalidOutputDict[0]['pk'] = 'pk.charmPickle' # 3. pass right arguments at the end genOutputDictFile(numValidMessages, messageSize, 'mpk.charmPickle', 'pk.charmPickle', validOutputDict, validOutputDictName, '_ValidMessage.pythonPickle', '_ValidSignature.charmPickle', True, pklist, sklist, P, g2) #genOutputDictFile(numInvalidMessages, messageSize, 'mpk.charmPickle', 'pk.charmPickle', invalidOutputDict, invalidOutputDictName, '_InvalidMessage.pythonPickle', '_InvalidSignature.charmPickle', False, pklist, sklist, P, g2) return
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
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!')
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
def setup(message): message_hash = sha256(message).digest() bit_message = bytearray_to_bits(message_hash) # block of bits n = len(bit_message) grp = PairingGroup('MNT224') vrf = VRF10(grp) (pk, sk) = vrf.setup(n) return bit_message, pk, sk, vrf
def main(): global group group = PairingGroup(secparam) (pk, msk) = setup(4) (blindingFactorYVectorBlinded, blindingFactorLVectorBlinded, sk2Blinded) = keygen(pk, msk, [2, 1, 0, 2]) M = group.random(GT) print(M) print("\n\n") CT = encrypt(M, [1, 1, 0, 1], pk) transformOutputList = transform(CT, sk2Blinded) M2 = decout(CT, sk2Blinded, transformOutputList, blindingFactorYVectorBlinded, blindingFactorLVectorBlinded) print(M2) if (M == M2): print("success") else: print("failed")
def main(): global group group = PairingGroup("SS512") (pk, msk) = setup(4) (bf0, skBlinded) = keygen(pk, msk, [2, 1, 0, 2]) M = group.random(GT) print(M) print("\n\n") CT = encrypt(M, [1, 1, 0, 1], pk) (transformOutputList, nn, yvector, lvector) = transform(CT, skBlinded) M2 = decout(transformOutputList, bf0, nn, yvector, lvector) print(M2) if (M == M2): print("success") else: print("failed")
def main(): global group group = PairingGroup('SS512') (mpk, msk) = setup() (bf0, bf8, skBlinded) = keygen(mpk, msk, "*****@*****.**") M = group.random(GT) print(M) print("\n\n\n") ct = encrypt(mpk, M, "*****@*****.**") transformOutputList = transform(ct, skBlinded) M2 = decout(transformOutputList, bf0, bf8) print(M2) if (M == M2): print("successful decryption for outsourcing!!!") else: print("failed decryption.")
def testZKPVote_oneParameter(self): groupObj = PairingGroup('BN254') params = 1 msg = [] attrs = [[]] msg.append("testmessage") attrs[0].append("testmessage") 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) = ZKP.ZKP_correctVote(c, pk_EV['g'], sk_EV, params) isCorrect = ZKP.verifyZKP_correctVote(c, m, pk_EV, ch, r, pk_EV['g'], params) assert (isCorrect) print("ZKPVote Test Result with one parameter:", isCorrect)
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)
def testHIBE_BB04(self): groupObj = PairingGroup('SS512') hibe = HIBE_BB04(groupObj) (mpk, mk) = hibe.setup() # represents public identity ID = "*****@*****.**" (pk, sk) = hibe.extract(3, mpk, mk, ID) # dID => pk, sk if debug: print("ID:%s , sk:%s" % (pk, sk)) M = groupObj.random(GT) if debug: print("M :=", M) ct = hibe.encrypt(mpk, pk, M) orig_M = hibe.decrypt(pk, sk, ct) assert orig_M == M, "invalid decryption!!!!" if debug: print("Successful DECRYPTION!!!")
def testAGHOBlind_oneParameter(self): groupObj = PairingGroup('BN254') params = 1 msg = [] msg.append("testmessage") el = ElGamal(params) agho = AGHOBlind(el) h = groupObj.random(G2) (pk_EV, sk_EV) = el.keygen() (sk_sig, pk_sig) = agho.keygen(h) (c, o) = el.encrypt(pk_EV, msg) (c_bar, P_bar, G, e, f1, f2) = agho.blind(c, pk_EV['g']) (sig_bar, z1, z2, r) = agho.sign(pk_EV['g'], sk_sig, c_bar, h, G, P_bar) sig = agho.deblindSig(sig_bar, e, f1 + f2) vf = agho.verify(pk_sig, sig, pk_EV['g'], h, c) assert (vf) print("AGHOBlind Test Result with one parameter:", vf)
def testDSE09(self): grp = PairingGroup('SS512') ibe = DSE09(grp) ID = "*****@*****.**" (mpk, msk) = ibe.setup() sk = ibe.keygen(mpk, msk, ID) if debug: print("Keygen...\nsk :=", sk) M = grp.random(GT) ct = ibe.encrypt(mpk, M, ID) if debug: print("Ciphertext...\nct :=", ct) m = ibe.decrypt(ct, sk) assert M == m, "Decryption FAILED!" if debug: print("Successful Decryption!!!")
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'
def main(): global group group = PairingGroup("SS512") (pk, msk) = setup(4) (bf0, skBlinded) = keygen(pk, msk, [2, 1, 0, 2]) M = group.random(GT) print(M) print("\n\n") CT = encrypt(M, [1, 1, 0, 1], pk) (transformOutputList, nn) = transform(CT, skBlinded) M2 = decout(transformOutputList, bf0, nn) print(M2) if (M == M2): print("success") else: print("failed")
def main(): global group group = PairingGroup("SS512") (msk, pk) = setup() S = ['THREE', 'ONE', 'TWO'] (blindingFactor0Blinded, skBlinded) = keygen(pk, msk, S) policy_str = '((ONE or THREE) and (TWO or FOUR))' M = group.random(GT) print(M) print("\n\n\n") ct = encrypt(pk, M, policy_str) (transformOutputList, policy, coeff) = transform(pk, skBlinded, S, ct) M2 = decout(pk, S, transformOutputList, blindingFactor0Blinded, policy, coeff) print(M2) if (M == M2): print("it worked")
def decrypt(public_params, ct, token, group_name='MNT159') -> bool: """ Performs the decrypt algorithm for IPE on a secret key skx and ciphertext cty. The output is the inner product <x,y>, so long as it is in the range [0,max_innerprod]. """ result = ipe.innerprod_pair(ct, token) return result == PairingGroup(group_name).init(GT, 1)