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, Ti) = transform(skBlinded, ct, dfaM) origM = decout(transformOutputList, blindingFactor0Blinded, Ti, dfaM) print("rec M :", origM) assert M == origM, "failed decryption" print("SUCCESSFUL DECRYPTION!!!")
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)
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 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 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 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 __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 __init__(self, group = "SS512"): self._group = PairingGroup(group) self._cpabe = CPabe09(self._group) self._hybrid_abe = HybridABEnc(self._cpabe, self._group) # TODO: Master keys should be generated once and stored securely # somewhere else. self._master_secret, self._master_public = self._cpabe.setup()
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, 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 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 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 __init__(self, groupObj=False): ABEnc.__init__(self) global util, group if groupObj == False: group = PairingGroup('SS512') else: group = groupObj util = SecretUtil(groupObj, debug)
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 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 revokedTest(): print("RUN revokedTest") groupObj = PairingGroup('SS512') dac = DACMACS(groupObj) GPP, GMK = dac.setup() users = {} # public user data authorities = {} authorityAttributes = ["ONE", "TWO", "THREE", "FOUR"] authority1 = "authority1" dac.setupAuthority(GPP, authority1, authorityAttributes, authorities) alice = {'id': 'alice', 'authoritySecretKeys': {}, 'keys': None} alice['keys'], users[alice['id']] = dac.registerUser(GPP) bob = {'id': 'bob', 'authoritySecretKeys': {}, 'keys': None} bob['keys'], users[bob['id']] = dac.registerUser(GPP) for attr in authorityAttributes[0:-1]: dac.keygen(GPP, authorities[authority1], attr, users[alice['id']], alice['authoritySecretKeys']) dac.keygen(GPP, authorities[authority1], attr, users[bob['id']], bob['authoritySecretKeys']) k = groupObj.random(GT) policy_str = '((ONE or THREE) and (TWO or FOUR))' CT = dac.encrypt(GPP, policy_str, k, authorities[authority1]) TK1a = dac.generateTK(GPP, CT, alice['authoritySecretKeys'], alice['keys'][0]) PT1a = dac.decrypt(CT, TK1a, alice['keys'][1]) TK1b = dac.generateTK(GPP, CT, bob['authoritySecretKeys'], bob['keys'][0]) PT1b = dac.decrypt(CT, TK1b, bob['keys'][1]) assert k == PT1a, 'FAILED DECRYPTION (1a)!' assert k == PT1b, 'FAILED DECRYPTION (1b)!' print('SUCCESSFUL DECRYPTION 1') # revoke bob on "ONE" attribute = "ONE" UK = dac.ukeygen(GPP, authorities[authority1], attribute, users[alice['id']]) dac.skupdate(alice['authoritySecretKeys'], attribute, UK['KUK']) dac.ctupdate(GPP, CT, attribute, UK['CUK']) TK2a = dac.generateTK(GPP, CT, alice['authoritySecretKeys'], alice['keys'][0]) PT2a = dac.decrypt(CT, TK2a, alice['keys'][1]) TK2b = dac.generateTK(GPP, CT, bob['authoritySecretKeys'], bob['keys'][0]) PT2b = dac.decrypt(CT, TK2b, bob['keys'][1]) assert k == PT2a, 'FAILED DECRYPTION (2a)!' assert k != PT2b, 'SUCCESSFUL DECRYPTION (2b)!' print('SUCCESSFUL DECRYPTION 2')
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 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()
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 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)
def generate_signatures_main(argv): 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('BN256') chp.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 # (pk, sk, g) = bls.keygen() g2 = chp.setup() (pk, sk) = chp.keygen(g2) t1, t2, t3 = 'one', 'two', 'three' f_mpk = open('mpk.charmPickle', 'wb') # 2. serialize the pk's pick_mpk = objectToBytes({ 'pk': pk, 'g2': g2, 't1': t1, 't2': t2, 't3': t3 }, group) f_mpk.write(pick_mpk) f_mpk.close() validOutputDict = {} validOutputDict[0] = {} validOutputDict[0]['pk'] = 'mpk.charmPickle' invalidOutputDict = {} invalidOutputDict[0] = {} invalidOutputDict[0]['pk'] = 'mpk.charmPickle' # 3. pass right arguments at the end genOutputDictFile(numValidMessages, messageSize, 'mpk.charmPickle', validOutputDict, validOutputDictName, '_ValidMessage.pythonPickle', '_ValidSignature.charmPickle', True, pk, sk, g2, t1, t2, t3) genOutputDictFile(numInvalidMessages, messageSize, 'mpk.charmPickle', invalidOutputDict, invalidOutputDictName, '_InvalidMessage.pythonPickle', '_InvalidSignature.charmPickle', False, pk, sk, g2, t1, t2, t3) return
def abe_key_extract(sym_key): """ Function to extract abe pairing element from the symmetric key string :param sym_key: symmetric key :return: return abe pairing element that corresponds to symmetric key string """ groupObj = PairingGroup('SS512') abe_key = groupObj.deserialize(sym_key) return abe_key
def setUp(self): group = PairingGroup('SS512') public_key_scheme = RSAPublicKey() self.subject = BaseSerializer(group, public_key_scheme) self.implementations = [ DACMACS13Implementation(), RD13Implementation(), RW15Implementation(), TAAC12Implementation() ] # type: List[BaseImplementation]
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)
def __init__(self, param_id, debug): """Конструктор класс Атрибуты: param_id параметры эллиптической кривой: {SS512, SS1024, MNT159, MNT201, MNT224}. debug вывод дополнительной информации. """ self.group = PairingGroup(param_id) self.debug = debug
def __init__(self): 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) gmsk_path = os.path.join(self.path, 'gm/gmsk') self.gmsk = bytesToObject(open(gmsk_path, 'rb').read(), self.group) dic_path = os.path.join(self.path, 'gm/identity.pkl') self.dic = pickle.load(open(dic_path, 'rb'))
def test_speed_of_idp_user_lookup(): grp = PairingGroup('MNT224') h = grp.hash('yelp', G1) start = time.time() for i in range(0, 100000): r = grp.random() result = h ** r end = time.time() print("Time for IdP to look up a user's gamma among 100k users: ") print(end-start)
def main(): """Wrapper function to decrypt a ciphertext file using the Bethencourt2007cae CP-ABE Scheme. """ parser = argparse.ArgumentParser( description="Decrypts a given ciphertext, with name <fname>.cpabe," " using the provided decryption key.") parser.add_argument('--mpk', required=True, dest='mpk', type=str, help="The name of the Public Parameters." + " Default: %(default)s") parser.add_argument('--ctxt', required=True, dest='ctxt', type=str, help="The name of the file containing the" + " ciphertext to be decrypted.") parser.add_argument('--dkey', required=True, dest='dkey', type=str, help="The name of the file containing the" + " decryption key") args = parser.parse_args() if not args.ctxt.endswith(".cpabe"): print("Ciphertext needs to end with .cpabe") sys.exit(-1) ptxt_fname = args.ctxt.replace(".cpabe", ".prime") group = PairingGroup('SS512') mpk = read_key_from_file(args.mpk, group) dkey = read_key_from_file(args.dkey, group) try: raw = cpabe_decrypt(group, mpk, dkey, io.open(args.ctxt, 'rb')) except PebelDecryptionException as e: print("Unable to decrypt ciphertext: {}".format(e)) sys.exit(-1) else: with io.open(ptxt_fname, 'wb') as ptxt: for b in raw: ptxt.write(bytes([b])) ptxt.flush()
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('BN256') hw.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 (g1, g2) = hw.setup() ilist = {} (ilist[0], pk, sk) = hw.keygen(g1, g2) f_mpk = open('mpk.charmPickle', 'wb') # 2. serialize the pk's pick_mpk = objectToBytes({'pk': pk, 'g1': g1, 'g2': g2}, group) f_mpk.write(pick_mpk) f_mpk.close() # 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, pk, sk, ilist) genOutputDictFile(numInvalidMessages, messageSize, 'mpk.charmPickle', 'pk.charmPickle', invalidOutputDict, invalidOutputDictName, '_InvalidMessage.pythonPickle', '_InvalidSignature.charmPickle', False, pk, sk, ilist) return