def setup(pk_outfile=const.ABE_PK_FILE, msk_outfile=const.ABE_MSK_FILE, pairing_group_curve=const.PAIRING_GROUP_CURVE, debug=0): """ Generate CP-ABE public and master secret key and store them in the given files. :param pk_outfile: file where public key will be saved :param msk_outfile: file where master secret key will be saved :param pairing_group_curve: string representing curve to use for the pairing group :param debug: if 1, prints will be shown during execution; default 0, no prints are shown """ # Instantiate a bilinear pairing map with the given curve pairing_group = PairingGroup(pairing_group_curve) # CP-ABE cpabe = CPabe_BSW07(pairing_group) # Create public and master secret keys (pk, msk) = cpabe.setup() if debug: # ONLY USE FOR DEBUG print('CP-ABE PUBLIC KEY =', pk) print('CP-ABE MASTER SECRET KEY =', msk) # Save keys on given output files with open(pk_outfile, 'w') as fout: fout.write(objectToBytes(pk, pairing_group).hex()) with open(msk_outfile, 'w') as fout: fout.write(objectToBytes(msk, pairing_group).hex())
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('===========================================================')
def main(): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) (pk, mk) = hyb_abe.setup() with open("p_key.txt", "wb") as pkFile: pkFile.write(objectToBytes(pk, groupObj)) with open("m_key.txt", "wb") as mkFile: mkFile.write(objectToBytes(mk, groupObj)) #attr_list[0] is for drone-one skD1 = hyb_abe.keygen(pk, mk, attr_list[0]) with open("s_keyD1.txt", "wb") as skD1File: skD1File.write(objectToBytes(skD1, groupObj)) #attr_list[0] is for drone-one skD2 = hyb_abe.keygen(pk, mk, attr_list[1]) with open("s_keyD2.txt", "wb") as skD2File: skD2File.write(objectToBytes(skD2, groupObj)) if debug: print("pk => ", pk) if debug: print("mk => ", mk) if debug: print("skD1 => ", skD1) if debug: print("skD2 => ", skD2)
def setup(self): (PK, MK) = self.cpabe.setup() serPK = objectToBytes(PK, self.groupObj) serMK = objectToBytes(MK, self.groupObj) return (serPK, serMK)
def generate_group(): last_group = 0 file_address = './database/group_counter.txt' try: file = open(file_address, 'r') last_group = int(file.read()) except IOError: pass finally: file = open(file_address, 'w') file.write(str(last_group + 1)) file.close() group = PairingGroup('MNT224') number_of_slaves = int(request.form['number_of_slaves']) shortSig = ShortSig(group) (global_public_key, global_master_secret_key, user_secret_keys) = shortSig.keygen(number_of_slaves) print('\n\nglobal_public_key : ', global_public_key) print('\n\nuser_secret_keys : ', user_secret_keys) # user_secret_keys_json = json.dumps(user_secret_keys) group_address = SHA256.new( data=str(global_public_key).encode('utf-8')).hexdigest() global_public_key_bytes = objectToBytes(global_public_key, group) global_public_key_str = global_public_key_bytes.decode() global_master_secret_key_bytes = objectToBytes(global_master_secret_key, group) global_master_secret_key_str = global_master_secret_key_bytes.decode() user_secret_keys_str = dict() for i in user_secret_keys: user_secret_key_bytes = objectToBytes(user_secret_keys[i], group) user_secret_key_str = user_secret_key_bytes.decode() user_secret_keys_str[str(i)] = user_secret_key_str user_secret_keys_str = json.dumps(user_secret_keys_str) group_dict = { "global_public_key": global_public_key_str, "global_master_secret_key": global_master_secret_key_str, "group_address": str(group_address), "group_id": last_group, "last_slave": 0, "number_of_slaves": number_of_slaves, "user_secret_keys": user_secret_keys_str } file_group_address = './database/' + str(last_group) with open(file_group_address, 'w') as f: group_json = json.dumps(group_dict) f.write(str(group_json)) response = { "global_public_key": str(global_public_key), "global_master_secret_key": str(global_master_secret_key), "group_address": str(group_address), "group_id": last_group } return jsonify(group_dict), 200
def genOutputDictFile(numCount, messageSize, keyName, outputDict, outputDictName, outputMsgSuffix, outputSigSuffix, isValid, *signVars): for index in range(0, numCount): if (index != 0): outputDict[index] = {} outputDict[index]['pk'] = keyName message = genNewMessage(messageSize) # inputs change for each scheme sig = genValidSignature(message, *signVars) f_message = open(prefixName + str(index) + outputMsgSuffix, 'wb') outputDict[index]['message'] = prefixName + str(index) + outputMsgSuffix if isValid == False: # make signature effectively invalid message = genBadMessage(message, messageSize) pickle.dump(message, f_message) f_message.close() f_sig = open(prefixName + str(index) + outputSigSuffix, 'wb') outputDict[index]['sig'] = prefixName + str(index) + outputSigSuffix pick_sig = objectToBytes(sig, group) f_sig.write(pick_sig) f_sig.close() dict_pickle = objectToBytes(outputDict, group) f = open(outputDictName, 'wb') f.write(dict_pickle) f.close() del dict_pickle del f
def store(self, recordType, msg): if recordType.lower() == "general": ID = self.General[0] elif recordType.lower() == "medical": ID = self.Medical[0] elif recordType.lower() == "training": ID = self.Training[0] else: print("Please enter the correct record type") return ct = self.pre.encrypt(self.params, ID, msg) # Serialise the ct for storage in MySql using appropriate charm API for each element type # Differentiate between the Integer element and the PairingGroup elements (Otherwise cannot seialise) # After serialisation, type is byte db = Database() ctI = serialize(ct['C']['C']) # type of ctI is Integer. Use serialise API del ct['C']['C'] ctPg = objectToBytes(ct, self.group) # type of ctPG is PairingGroup. Use objectToBytes API ################### #MD: Todo: Add date to signature ###################### # Get the mastser public key from the SignKeys table # mPK_bytes = db.getSignPubKey("master") # bytes of the master public key # mPK = bytesToObject(mPK_bytes, self.signGroup) # de-serialize the key before usage date = time.strftime("%Y-%m-%d %H:%M:%S") signature = objectToBytes(self.waters.sign(self.masterPK, self.signK, ''.join(msg + date)), self.signGroup) db.insertRecord(ID, ctI, ctPg, signature, date, self.ID) db.done()
def genOutputDictFile(numCount, messageSize, keyName, outputDict, outputDictName, outputMsgSuffix, outputSigSuffix, isValid, *signVars): for index in range(0, numCount): if (index != 0): outputDict[index] = {} outputDict[index]['pk'] = keyName message = genNewMessage(messageSize) # inputs change for each scheme sig = genValidSignature(message, *signVars) f_message = open(prefixName + str(index) + outputMsgSuffix, 'wb') outputDict[index]['message'] = prefixName + str( index) + outputMsgSuffix if isValid == False: # make signature effectively invalid message = genBadMessage(message, messageSize) pickle.dump(message, f_message) f_message.close() f_sig = open(prefixName + str(index) + outputSigSuffix, 'wb') outputDict[index]['sig'] = prefixName + str(index) + outputSigSuffix pick_sig = objectToBytes(sig, group) f_sig.write(pick_sig) f_sig.close() dict_pickle = objectToBytes(outputDict, group) f = open(outputDictName, 'wb') f.write(dict_pickle) f.close() del dict_pickle del f
def authority(request): if (request.is_ajax()): name = request.GET.get('name', False) attr_list = request.GET.getlist('list', False) attr_list = [x.encode('UTF8') for x in attr_list] print name, attr_list if name and attr_list: (private, master) = hyb_abe.setup() decoder = hyb_abe.keygen(private, master, attr_list) print "---------------------------------------------" print "The Attribute List is:" print attr_list print "---------------------------------------------" print "The public parameters PK are:" print private print "---------------------------------------------" print "The private key D is:" print decoder decoder_b = objectToBytes(decoder, groupObj) private_b = objectToBytes(private, groupObj) try: a = Authority.objects.get(app_name=name) except ObjectDoesNotExist: a = Authority(app_name=name, attr_list=attr_list, p_key=private_b, d_key=decoder_b) a.save() json_res = {'msg': 'Success!'} else: json_res = {'msg': 'Failure.'} return HttpResponse(json.dumps(json_res), content_type='application/json') return render(request, 'authority.html');
def _dump_meta(self, metafile): """ Dump the meta information on the metafile :param metafile: file where meta information will be saved :return: encrypted meta information """ if self.debug: print("dumping metadata on file ", metafile) # Encrypt symmetric key pairing group element with CP-ABE enc_el = abe.encrypt(self.meta['el'], self.pairing_group, next(iter(self.abe_pk.values())), self.meta['policy'], self.debug) # Prepare encrypted data enc_meta = { 'policy': self.meta['policy'], 'nonce': self.meta['nonce'].hex(), 'enc_el': objectToBytes(enc_el, self.pairing_group).hex(), 'chunk_size': self.meta['chunk_size'], 'random_size': self.meta['random_size'], 're_encs': self.meta['re_encs'] } # Check if there is re-encryption information if len(enc_meta['re_encs']): # Retrieve ABE public key re_enc_op = enc_meta['re_encs'][0] key_pair_label = re_enc_op['pk'] pk = self.abe_pk[key_pair_label] #print('DUMP ENC META PRE ABE', re_enc_op) # Encrypt seed enc_seed = objectToBytes( abe.encrypt(re_enc_op['enc_seed'], self.pairing_group, pk, re_enc_op['policy'], self.debug), self.pairing_group) # Encrypt symmetric key enc_key = objectToBytes( abe.encrypt(re_enc_op['enc_key'], self.pairing_group, pk, re_enc_op['policy'], self.debug), self.pairing_group) # Add re-encryption information to encrypted meta information enc_meta['re_encs'][0]['enc_seed'] = hexlify(enc_seed).decode() enc_meta['re_encs'][0]['enc_key'] = hexlify(enc_key).decode() enc_meta['re_encs'][0]['iv'] = hexlify(re_enc_op['iv']).decode() #print('DUMP ENC META POST ABE', enc_meta['re_encs'][0]) # Write encrypted information with open(metafile, 'w') as f: json.dump(enc_meta, f) return enc_meta
def serialize_key(self): result_str = self.serialize_matrices() g1bytes = objectToBytes(self.g1, self.group) g2bytes = objectToBytes(self.g2, self.group) result_str = result_str + "\n" + str(len(g1bytes)) + " " + str( len(g2bytes)) return result_str, g1bytes + g2bytes
def verifier2(self, g, y, z, t, u): c = group.hash( objectToBytes(y, group) + objectToBytes(t, group) + objectToBytes(u, group), ZR) if (y**c) * t == pair(g, u)**z: return 1 else: return 0
def prover2(self, g, y, x, u): r = group.random(ZR) t = pair(g, u)**r c = group.hash( objectToBytes(y, group) + objectToBytes(t, group) + objectToBytes(u, group), ZR) z = c * x + r return {'z': z, 't': t, 'y': y}
def encrypt(self, key, plaintext): encryptor = AES.new( objectToBytes(key, self.group)[:32], AES.MODE_CBC, 'This is an IV456') plaintext_bytes = objectToBytes(plaintext, self.group) #seriously, why do I have to do the padding... while len(plaintext_bytes) % 16 != 0: plaintext_bytes = plaintext_bytes + b'\x00' return encryptor.encrypt(plaintext_bytes)
def serialize(s): storage = {} storage['n'] = s['n'] storage['master_public_key'] = objectToBytes(s['master_public_key'], group) storage['master_key'] = objectToBytes(s['master_key'], group) storage['plain'] = objectToBytes(s['plain'], group) storage['cipher'] = objectToBytes(s['cipher'], group) return storage
def serialize(s): storage = {} storage['n'] = s['n'] storage['param'] = objectToBytes(s['param'], kac.group) storage['e_g1_g2'] = objectToBytes(s['e_g1_g2'], kac.group) storage['key'] = objectToBytes(s['key'], kac.group) storage['plain'] = objectToBytes(s['plain'], kac.group) storage['cipher'] = objectToBytes(s['cipher'], kac.group) return storage
def __init__(self, k, t, secret, sk, pk, participantids, participantkeys, group, symflag, recv_function, send_function, sid=1, seed=None): # Random polynomial coefficients constructed in the form #[c x x^2 ... x^t] # This is structured so that t+1 points are needed to reconstruct the polynomial ONE = group.random(ZR) * 0 + 1 self.witnesses = {} self.t = t self.k = k self.group = group self.sid = sid self.poly = list(group.random(ZR, count=t + 1, seed=seed)) self.poly[0] = ONE * secret self.polyhat = list(group.random(ZR, count=t + 1, seed=seed)) self.participantids = participantids self.participantkeys = participantkeys self.sharedkeys = {} for j in participantids: self.sharedkeys[j] = self.participantkeys[j]**sk self.pc = PolyCommitPed(t=t, pk=pk, group=group, symflag=symflag) self.commitment = self.pc.commit(self.poly, self.polyhat) self.shares = {} self.encryptedshares = {} for j in participantids: self.shares[j] = f(self.poly, j) self.encryptedshares[j] = self.encrypt(self.sharedkeys[j], self.shares[j]) #for j in participantids[:t+1]: for j in participantids: self.witnesses[j] = self.pc.create_witness(self.poly, self.polyhat, j) message = {} message['commit'] = objectToBytes(self.commitment, self.group) message['witnesses'] = objectToBytes(self.witnesses, self.group) message['shares'] = self.encryptedshares message['dealer'] = k message['polyhat'] = objectToBytes(self.polyhat, self.group) reliablebroadcast(sid, pid=k, N=k + 1, f=t, leader=k, input=str(message), receive=recv_function, send=send_function)
def serialize(s): storage = {} storage['n'] = s['n'] storage['param'] = objectToBytes(s['param'], group) storage['e_g1_g2'] = objectToBytes(s['e_g1_g2'], group) storage['key'] = objectToBytes(s['key'], group) storage['plain'] = objectToBytes(s['plain'], group) storage['cipher'] = objectToBytes(s['cipher'], group) return storage
def policy(request, p_id): user = Policy.objects.get(pk=int(p_id)) appname = "privateBook" statuses_decrypted = [] if request.method == 'POST': content = request.POST.get('status', False) if content: try: auth = Authority.objects.get(app_name=appname) except ObjectDoesNotExist: auth = False if auth: private = bytesToObject(auth.p_key, groupObj) decoder = bytesToObject(auth.d_key, groupObj) encrypt = hyb_abe.encrypt(private, str(content), str(user.policy)) print "-----------------------------------------------------" print "The status update is:" print content print "-----------------------------------------------------" print "Encrypted data, E is:" print encrypt print "--------------------------" print "And it is stored as:" print objectToBytes(encrypt, groupObj) print "-----------------------------------------------------" print "The decryption key is:" print decoder encrypt_b = objectToBytes(encrypt, groupObj) p = PostedData(p_id=int(p_id), status=encrypt_b) p.save() else: return render(request, 'policy.html', {'msg': 'The authority has not created any keys for you to encrypt your data!', 'id': p_id, 'name': user.name}) return HttpResponseRedirect('') else: return render(request, 'policy.html', {'msg': 'You didn\'t enter a status. Please try again.', 'id': p_id, 'name': user.name}) try: auth = Authority.objects.get(app_name=appname) except ObjectDoesNotExist: auth = False if auth: statuses = PostedData.objects.filter(p_id=int(p_id)) for s in statuses: status_cipher = bytesToObject(s.status, groupObj) private = bytesToObject(auth.p_key, groupObj) decoder = bytesToObject(auth.d_key, groupObj) try: status_pair = (hyb_abe.decrypt(private, decoder, status_cipher), s.posted) except: status_pair = ("Your status could not be displayed: this service does not support your privacy policy!", s.posted) statuses_decrypted.append(status_pair) if statuses_decrypted: context = {'statuses': statuses_decrypted, 'id': p_id, 'name': user.name} else: context = {'id': p_id, 'name': user.name} return render(request, 'policy.html', context)
def getStorageSize(storage): public = {} public['master_public_key'] = objectToBytes(storage['master_public_key'], group) public['cipher'] = objectToBytes(storage['cipher'], group) public['n'] = storage['n'] private = {} private['master_key'] = objectToBytes(storage['master_key'], group) # private['plain'] = objectToBytes(storage['plain'], group) return getsizeof(pickle.dumps(public)), getsizeof(pickle.dumps(private))
def decrypt(self, key, ciphertext): decryptor = AES.new(objectToBytes(key, self.group)[:32], AES.MODE_CBC, 'This is an IV456') plaintext_bytes = decryptor.decrypt(ciphertext) #now we need to strip the padding off the end #if it's stupid but it works... elementsize = len(objectToBytes(self.group.random(ZR), self.group)) paddingsize = (16 -elementsize%16)%16 #print len(plaintext_bytes) #plaintext_bytes = plaintext_bytes[:len(plaintext_bytes) - paddingsize] #print len(plaintext_bytes) return bytesToObject(plaintext_bytes, self.group)
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.")
def main(): userID = "test_user" key_file_user = "******" user_assigned_attr = ['attr3', 'attr4'] groupObj = PairingGroup('SS512') cpabe = IDABE.IDABE(groupObj) gpfile = "global.param" cpabe.setupGP(gpfile) user_attr_list = [] attr_dict = cpabe.read_attr_dict("attributes_map.json") for attr in user_assigned_attr: user_attr_list.append(attr_dict[attr]) cpabe.external_delegate("org3.sk", key_file_user, userID, user_attr_list, "pk.param") if debug: ctxt_filename = "ctxt.json" # the example AES key which will be encrypted by ABE scheme symk = groupObj.random(GT) rand_key_bytes = objectToBytes(symk, cpabe.group) key = sha256(rand_key_bytes).digest() cipher = charm.toolbox.symcrypto.AuthenticatedCryptoAbstraction(key) # the example message to be encrypted by AES msg = "test message" ciphertext = cipher.encrypt(msg) access_policy = '((attr1 and attr2) or (attr2 and attr3) or (attr3 and attr4) or (attr5 and attr6))' for attr, num in attr_dict.items(): access_policy = access_policy.replace(attr, num) # revoked users revID1 = cpabe.group.hash("orgx", ZR) revID2 = cpabe.group.hash("orgy", ZR) revID3 = cpabe.group.hash("orgz", ZR) revIDlist_u = [revID1, revID2, revID3] # revoked authorities non_revIDlist_a = ['org1', 'org2', 'org3'] cpabe.encrypt("pk.param", symk, access_policy, revIDlist_u, non_revIDlist_a, ctxt_filename) rec_msg = cpabe.decrypt_file(ctxt_filename, key_file_user) if rec_msg: assert symk == rec_msg, "FAILED DECRYPTION" print("decryption successful") dec_key_bytes = objectToBytes(rec_msg, cpabe.group) deckey = sha256(dec_key_bytes).digest() deccipher = charm.toolbox.symcrypto.AuthenticatedCryptoAbstraction( deckey) print("decrypted message is ", deccipher.decrypt(ciphertext).decode('UTF_8'))
def main(store, abe_keys_outfile): # Instantiate a bilinear pairing map. 'MNT224' represents an asymmetric curve with 224-bit base field. pairing_group = pg.pairing_group_create('MNT224') # CP-ABE cpabe = CPabe_BSW07(pairing_group) # Run the setup algorithm (pk, msk) = cpabe.setup() # Generate a user secret key user_attr_list = ['DEPT1', 'TEAM1'] user_key = cpabe.keygen(pk, msk, user_attr_list) # Generate keys data structure #policy_str = '((PATIENT and SMART-1032702) or (PRACTITIONER and SMART-PRACTITIONER-72004454))' #print("---------- PK ----------") #print(pk) #print("---------- MSK (needed only for debug)----------") #print(msk) #print("---------- SK ----------") #print(user_key) data = { hashlib.sha256(objectToBytes(pk, pairing_group)).hexdigest(): { 'pk': objectToBytes(pk, pairing_group).hex(), #'msk': msk, 'sk': objectToBytes(user_key, pairing_group).hex(), } } ## print(json.dumps(data)) ###### # abe_keys_file = str(Path.home()) + '/.abe_keys.json' # Ask if keys have to be saved if not store: store = True if input("Should I write them on your " + abe_keys_outfile + "[Y/N]? ").lower() == 'y' else False if store: with open(abe_keys_outfile, 'w') as f: json.dump(data, f) print("ABE keys have been saved in", abe_keys_outfile) else: print("Could we at least be friend?")
def send_recsharemsg(self): if not self.recshare: print "Can not send Rec-Share message, I have not received enough ready messages" return None recsharemsg = {} recsharemsg['type'] = 'recshare' recsharemsg['id'] = self.nodeid recsharemsg['polypoint'] = objectToBytes(self.interpolatedpolyatzero, self.group) recsharemsg['polyhatpoint'] = objectToBytes( self.interpolatedpolyhatatzero, self.group) recsharemsg['polywitness'] = objectToBytes( self.interpolatedzerowitness, self.group) return json.dumps(recsharemsg)
def validation(self, pw, t, n): nc, ns = n c0 = self._client.get_validation(t, pw, nc) payload = {'c0': objectToBytes(c0, group), 'ns': objectToBytes(ns, group)} response = self._requestobj.get("%s/validate" % self._endpoint, params=payload, verify = False) document = response.json() return self._client.do_validation(t, pw, ns, nc, bytesToObject(document['c1'], group), bytesToObject(document['proof'], group), document['result'])
def test1(client, p, nonce, key_client, key_p): group_object = PairingGroup('SS512') shared_key = group_object.random(GT) crypter_a = SymmetricCryptoAbstraction( extractor(bytesToObject(key_client, group_object))) crypter_b = SymmetricCryptoAbstraction( extractor(bytesToObject(key_p, group_object))) package_b = crypter_b.encrypt( objectToBytes([shared_key, serialize_endpoint(client)], group_object)) package_a = crypter_a.encrypt( objectToBytes([ Conversion.OS2IP(nonce), shared_key, serialize_endpoint(p), package_b ], group_object)) return package_a
def _add_initial_re_encs_info(self, initial_re_encs_num=0): """ Add initial re-encryption information to meta information :param initial_re_encs_num: number of re-encryptions that will be initially applied to new files """ # Add information about initial re-encryptions to apply to metafile if initial_re_encs_num > 0: # Create re-encryption params pk = objectToBytes(next(iter(self.abe_pk.values())), self.pairing_group) # TODO CHANGE FOR REAL USE policy = '(DEPT1 and TEAM1)' # TODO CHANGE FOR REAL USE seed = pg.hash_chain(self.pairing_group, self.last_seed_pg_elem, self.max_re_encs_num - initial_re_encs_num, self.cached_seeds, False) key = pg.hash_chain(self.pairing_group, self.last_key_pg_elem, self.max_re_encs_num - initial_re_encs_num, self.cached_keys, False) re_enc_length = const.RE_ENC_LENGTH # Add re-encryption params to metadata file self.meta['re_encs'].append({ 'pk': hashlib.sha256(pk).hexdigest(), # SHA256 of public key as hex 'policy': policy, 'enc_seed': seed, 'enc_key': key, 'iv': self.root_iv, 're_enc_length': re_enc_length, 're_encs_num': initial_re_encs_num })
def find_patient_footprint(self, data, sickuid): signature = data[SIGNATURE_INDEX].strip() msg = f'{data[BUILDING_INDEX].strip()}||{data[TIMESTAMP_INDEX].strip()}' identifier = objectToBytes(self.oracle.open(msg, signature), self.oracle.group) identity = self.oracle.dic[identifier] return (sickuid.count(identity) > 0), identity
def parallel_search(self, query): self.parallel = 1 processes = cpu_count() data_set_split = [] query_filename = "query" query_bytes = objectToBytes(query, self.predinstance.group) for j in range(processes): start = ceil(j * self.num_records / processes) end = ceil((j + 1) * self.num_records / processes) if end > self.num_records: end = self.num_records data_set_split.append((start, end)) overall_return_list = [] (matrix_str, generator_bytes) = self.serialize_key() with Pool(processes) as p: with concurrent.futures.ProcessPoolExecutor(processes) as executor: future_list = { executor.submit(self.augment_search, self.vector_length, self.predicate_scheme, self.group_name, matrix_str, generator_bytes, query_bytes, self.public_parameters, start, end) for (start, end) in data_set_split } for future in concurrent.futures.as_completed(future_list): res = future.result() if res is not None and len(res) > 0: overall_return_list = overall_return_list + res return overall_return_list
def addKey(self, ID1, ID2, rk): keystring = ID1 + ":" + ID2 n = serialize(rk['N']) r = objectToBytes(rk['R'], self.group) self.reEncryptionKeys[keystring] = rk
def revokeAuthorisedEntity(self, EntityID, HealthRecordType): # First check if this entity is authorised db = Database() date = time.strftime("%Y-%m-%d %H:%M:%S") rows = db.getAuthorisedEntities(self.ID, HealthRecordType, date) #Get all authorised entities that are authorised after 1999 if rows: for row in rows: if EntityID == row[0]: found = True # Found the entity for this specific recordType. Check signature DateStart = row[1] signature = bytesToObject(bytes(row[2], 'utf-8'), self.signGroup) if(self.verifySig(self.ID, DateStart, ''.join(self.ID + EntityID + HealthRecordType), signature)): # Valid signature found, now revoke it by setting the DateEnd to today and re-signing # First we need to wait 1 second otherwise the script is too fast! time.sleep(1) DateEnd = time.strftime("%Y-%m-%d %H:%M:%S") # mPK_bytes = db.getSignPubKey("master") # bytes of the master public key # mPK = bytesToObject(mPK_bytes, self.signGroup) # de-serialize the key before usage signature = objectToBytes(self.waters.sign(self.masterPK, self.signK, ''.join(self.ID + EntityID + HealthRecordType + DateEnd)), self.signGroup) db.revokeAuthorisedEntity(self.ID, EntityID, HealthRecordType, DateEnd, signature) print("Access for ", EntityID, " to write to ", HealthRecordType, " successfully revoked.") else: print("INVALID signature on authorisations") if found == False: print("Authorisation for ", EntityID, " to write to ", self.ID, "'s ", HealthRecordType, " data not found") else: print("Error: no authorisations found for ", self.ID, "'s ", HealthRecordType, " data!") db.done()
def kpabe_encrypt(group, mpk, ptxt, attributes): """Encrypts a plaintext using the Lewmko2008rws KP-ABE Scheme. @param group The `PairingGroup` used within the underlying crypto. @param mpk The master public key of type `mk_t`. @param ptxt The `bytearray` resulting from io.open or `io.IOBytes` containing the plaintext. @param attributes The set of `str` attributes used to encrypt the plaintext. @return The encrypted data returned as a `bytearray`. """ kpabe = KPabe(group) session_key = group.random(GT) session_key_ctxt = kpabe.encrypt(mpk, session_key, [a.upper() for a in attributes]) ctxt = io.BytesIO() iv = Random.new().read(AES.block_size) symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv) ctxt.write(bytes(iv)) session_key_ctxt_b = objectToBytes(session_key_ctxt, group) ctxt.write(struct.pack('Q' ,len(session_key_ctxt_b))) ctxt.write(session_key_ctxt_b) for b in read_data(bin_data=ptxt, chunksize=AES.block_size): ctxt.write(symcipher.encrypt(b)) ctxt.flush() return ctxt.getvalue()
def kpabe_encrypt(group, mpk, ptxt, attributes): """Encrypts a plaintext using the Lewmko2008rws KP-ABE Scheme. @param group The `PairingGroup` used within the underlying crypto. @param mpk The master public key of type `mk_t`. @param ptxt The `bytearray` resulting from io.open or `io.IOBytes` containing the plaintext. @param attributes The set of `str` attributes used to encrypt the plaintext. @return The encrypted data returned as a `bytearray`. """ kpabe = KPabe(group) session_key = group.random(GT) session_key_ctxt = kpabe.encrypt(mpk, session_key, [a.upper() for a in attributes]) ctxt = io.BytesIO() iv = Random.new().read(AES.block_size) symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv) ctxt.write(bytes(iv)) session_key_ctxt_b = objectToBytes(session_key_ctxt, group) ctxt.write(struct.pack('Q', len(session_key_ctxt_b))) ctxt.write(session_key_ctxt_b) for b in read_data(bin_data=ptxt, chunksize=AES.block_size): ctxt.write(symcipher.encrypt(b)) ctxt.flush() return ctxt.getvalue()
def encode_data(self, data): try: enc_data = utils.objectToBytes(data, self._groupObj) except: print('!!!__ERROR__!!! Ошибка encode_data') return {'!!!__ERROR__!!! Ошибка encode_data'} return enc_data
def encrypt_time_space(list_n): iterations = 1 private = public = 0 encrypt_timings = [] aggregate_time = [] aggregate_size = [] private_space = [] public_space = [] for n in list_n: start = time.clock() for i in xrange(iterations): storage = generate_ciphertext_keys(n) end = time.clock() no_of_bits = len(list(bin(n)[2:]))+1 kpabe = KPabe(group) encrypt_timings.append((n, (end-start)/iterations)) policy = policy_less_than('A', n+1, no_of_bits) + " and " + policy_more_than_equal('A', 1, no_of_bits) start = time.clock() for i in xrange(iterations): secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() aggregate_size.append((n, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) aggregate_time.append((end-start)/iterations) public, private = getStorageSize(storage) private_space.append((n, private)) public_space.append((n, public)) return encrypt_timings, aggregate_time, public_space, private_space, aggregate_size
def decryption_time(storage, q_list): iterations = 1 timings = [] aggregate_time = [] aggregate_size = [] no_of_bits = len(list(bin(storage['n'])[2:]))+1 kpabe = KPabe(group) for q in q_list: check = True timing = 0.0 gen_timing = 0.0 for i in xrange(iterations): more_than_equal, less_than = generate_range(storage, q) start = time.clock() policy = policy_less_than('A', less_than, no_of_bits) + " and " + policy_more_than_equal('A', more_than_equal, no_of_bits) secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() gen_timing += end-start cipher_text = storage['cipher'][more_than_equal:less_than] plain_text = storage['plain'][more_than_equal:less_than] start = time.clock() result = [kpabe.decrypt(ct, secret_key) for ct in cipher_text] end = time.clock() timing+=end-start if (plain_text!=result): check = False aggregate_time.append((q, gen_timing/iterations)) aggregate_size.append((q, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) if (check==True): timings.append((q, timing/iterations)) else: timings.append((q, 'error')) return timings
def calculate_aggregate_size(list_q, n): kpabe = KPabe(group) more_than = 1 iterations = 1 aggregate_size = [] aggregate_time = [] storage = {} storage['n'] = n no_of_bits = len(list(bin(n)[2:]))+1 storage['master_public_key'], storage['master_key'] = kpabe.setup() for q in list_q: gen_timing = 0.0 for i in xrange(iterations): more_than_equal, less_than = generate_range(storage, q) policy = policy_less_than('A', less_than, no_of_bits) + " and " + policy_more_than_equal('A', more_than_equal, no_of_bits) start = time.clock() secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() gen_timing += end-start aggregate_size.append((q, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) aggregate_time.append((q, (gen_timing)/iterations)) return aggregate_time, aggregate_size
def decryption_time(storage, q_list, decrypt_type=3): iterations = 1 kac = KAC() kac.n = storage['n'] kac.e_g1_g2 = storage['e_g1_g2'] timings = [] extract_time = [] aggregate_size = [] for q in q_list: check = True timing = 0.0 gen_timing = 0.0 for i in xrange(iterations): S = generateS(storage, q) # S = sorted(random.sample(xrange(1, storage['n']), q)) Q = S start = time.clock() K_s = kac.extract(storage['key']['msk'], S, storage['param']) end = time.clock() gen_timing += end-start # start_frame = S[0] # end_frame = S[len(S)-1]+1 # ct = storage['cipher'][start_frame:end_frame] # plain = storage['plain'][start_frame:end_frame] plain = [] ct = [] for i in Q: ct.append(storage['cipher'][i]) plain.append(storage['plain'][i]) start = time.clock() if (decrypt_type==1): result = [kac.decrypt(K_s, S, j, storage['cipher'][j], storage['param']) for j in S] elif (decrypt_type==2): result = kac.decrypt_set(K_s, S, Q, ct, storage['param']) elif (decrypt_type==3): result = kac.decrypt_range(K_s, S, start_frame, end_frame, ct, storage['param']) elif (decrypt_type==4): result = kac.decrypt_general(K_s, S, Q, ct, storage['param']) end = time.clock() timing += end-start if (result!=plain): check = false extract_time.append((q, gen_timing/iterations)) aggregate_size.append((q, getsizeof(pickle.dumps(objectToBytes(K_s, group))))) if (check==True): timings.append((q, timing/iterations)) else: timings.append((q, 'error')) # print timings # return extrchainact_time, aggregate_size, timings return extract_time, aggregate_size, timings
def calculate_aggregate_size(list_q, n): kpabe = KPabe(group) more_than = 1 iterations = 10 aggregate_size = [] aggregate_time = [] storage = {} storage['n'] = n no_of_bits = len(list(bin(n)[2:])) + 1 storage['master_public_key'], storage['master_key'] = kpabe.setup() for q in list_q: gen_timing = 0.0 for i in xrange(iterations): more_than_equal, less_than = generate_range(storage, q) policy = policy_less_than( 'A', less_than, no_of_bits) + " and " + policy_more_than_equal( 'A', more_than_equal, no_of_bits) start = time.clock() secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() gen_timing += end - start aggregate_size.append( (q, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) aggregate_time.append((q, (gen_timing) / iterations)) return aggregate_time, aggregate_size
def sign(self, msg, time_period): if GS_PROTOCOL == "ShortSig": signature = self.gs_protocol.sign(self.gpk, self.sk, msg) elif GS_PROTOCOL == "VLRSig": signature = self.gs_protocol.sign(self.gpk, self.sk, time_period, msg) return objectToBytes(signature, self.group)
def encrypt_time_space(list_n): iterations = 1 private = public = 0 encrypt_timings = [] aggregate_time = [] aggregate_size = [] private_space = [] public_space = [] for n in list_n: start = time.clock() for i in xrange(iterations): storage = generate_ciphertext_keys(n) end = time.clock() no_of_bits = len(list(bin(n)[2:])) + 1 kpabe = KPabe(group) encrypt_timings.append((n, (end - start) / iterations)) policy = policy_less_than( 'A', n + 1, no_of_bits) + " and " + policy_more_than_equal( 'A', 1, no_of_bits) start = time.clock() for i in xrange(iterations): secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() aggregate_size.append( (n, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) aggregate_time.append((end - start) / iterations) public, private = getStorageSize(storage) private_space.append((n, private)) public_space.append((n, public)) return encrypt_timings, aggregate_time, public_space, private_space, aggregate_size
def cpabe_encrypt(group, mpk, ptxt, policy): """Encrypts a plain-text using the Bethencourt2007cae CP-ABE Scheme. @param group The `PairingGroup` used within the underlying crypto. @param mpk The Master Public Key of type `pk_t`. @param ptxt The `bytearray` resulting from io.open or io.IOBytes containing the plaintext. @param policy The `str` policy used to encrypt the plaintext. @return The encrypted data returned as a `bytearray`. """ cpabe = CPabe_BSW07(group) session_key = group.random(GT) session_key_ctxt = cpabe.encrypt(mpk, session_key, policy) ctxt = io.BytesIO() iv = Random.new().read(AES.block_size) symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv) ctxt.write(bytes(iv)) session_key_ctxt_b = objectToBytes(session_key_ctxt, group) ctxt.write(struct.pack('<Q', len(session_key_ctxt_b))) ctxt.write(session_key_ctxt_b) for b in read_data(bin_data=ptxt, chunksize=AES.block_size): ctxt.write(symcipher.encrypt(b)) ctxt.flush() return ctxt.getvalue()
def store_private_keys(decrypt_key, secret_key, user, password): wc = WebClient("https://[fd00:638:a000:b101::2b75]/", requests) m, t, n = wc.enrollment(user + password) #phe-registration m_bytes = objectToBytes(m, group) decrypt_key = decrypt_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption(m_bytes)) secret_key = secret_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption(m_bytes)) if not os.path.exists(user): os.mkdir(user) write_byte(user + '/m', m_bytes) #TO TEST WITHOUT PHE imap_path = 'IMAP/' + user if not os.path.exists(imap_path): os.mkdir(imap_path) write_byte(imap_path + '/private_key.key', decrypt_key) write_object(imap_path + '/n', n) write_object(imap_path + '/t', t) smtp_path = 'SMTP/' + user if not os.path.exists(smtp_path): os.mkdir(smtp_path) write_byte(smtp_path + '/private_key.key', secret_key) write_object(smtp_path + '/n', n) write_object(smtp_path + '/t', t)
def decryption_time(storage, q_list): iterations = 5 timings = [] aggregate_time = [] aggregate_size = [] no_of_bits = len(list(bin(storage['n'])[2:]))+1 kpabe = KPabe(group) for q in q_list: print "q" print q check = True timing = 0.0 gen_timing = 0.0 for i in xrange(iterations): # print "iterations" # print i more_than_equal, less_than = generate_range(storage, q) print "more_than_equal" print more_than_equal print "less_than" print less_than start = time.clock() policy = policy_less_than('A', less_than, no_of_bits) + " and " + policy_more_than_equal('A', more_than_equal, no_of_bits) print "policy" print policy secret_key = kpabe.keygen(storage['master_public_key'], storage['master_key'], policy) end = time.clock() gen_timing += end-start cipher_text = storage['cipher'][more_than_equal:less_than] plain_text = storage['plain'][more_than_equal:less_than] start = time.clock() assert group.InitBenchmark(), "failed to initialize benchmark" group.StartBenchmark(["Mul", "Exp", "Pair", "Div", "Granular"]) result = [kpabe.decrypt(ct, secret_key) for ct in cipher_text] group.EndBenchmark() end = time.clock() msmtDict = group.GetGeneralBenchmarks() print("<=== General Benchmarks ===>") print("Results := ", msmtDict) timing+=end-start if (plain_text!=result): check = False aggregate_time.append((q, gen_timing/iterations)) aggregate_size.append((q, getsizeof(pickle.dumps(objectToBytes(secret_key, group))))) if (check==True): timings.append((q, timing/iterations)) else: timings.append((q, 'error')) return timings
def broadcastEncapList(sockfd, addr): broadcast(sock, "1000001"+str(len(encapsulations))) time.sleep(1) print "Client {}, on {} connected".format(userdata[sockfd], addr) for j in xrange(0,len(encapsulations)): time.sleep(0.1) broadcast(sock, objectToBytes(encapsulations[j], groupObj)) print('Send encapsulation number {} of {}'.format(j+1,len(encapsulations)))
def refresh(self, serPK, serMK): """ return tupel: (serPK', serMK', conversionFactor) """ PK = bytesToObject(serPK, self.groupObj) MK = bytesToObject(serMK, self.groupObj) newAlpha = self.groupObj.random(ZR) PK['e_gg_alpha'] = pair(PK['g'], PK['g2'] ** newAlpha) g2_newAlpha = PK['g2'] ** newAlpha conversionFactor = ((g2_newAlpha / MK['g2_alpha']) ** ~(MK['beta'])) MK['g2_alpha'] =g2_newAlpha newSerPK = objectToBytes(PK, self.groupObj) newSerMK = objectToBytes(MK, self.groupObj) return (newSerPK, newSerMK, conversionFactor)
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 handleNewConnection(): sockfd, addr = server_socket.accept() userdata[sockfd] = 'Anonymous {}'.format(len(userdata)) #send the room policy sockfd.send(roomPolicy) #send pk and group sockfd.send(objectToBytes(pk,groupObj)) #send key using a attr set sockfd.send(objectToBytes(cpabe.keygen(pk, msk, attr_dict[i]),groupObj)) #receive the encapsulation encap = bytesToObject(sockfd.recv(RECV_BUFFER), groupObj) #save it encapsulations.append(encap) entities.append(addr) broadcastEncapList(sockfd, addr) broadcast(sockfd, "[server] {} entered room\n".format(userdata[sockfd])) print 'Users in the room: {}\n\n'.format(str(userdata.values()))
def testECGroup(self): groupObj = ECGroup(prime192v1) p=groupObj.random() data={'p':p,'String':"foo",'list':[p,{},1,1.7, b'dfa',]} x=objectToBytes(data,groupObj) data2=bytesToObject(x,groupObj) self.assertEqual(data,data2)
def testIntegerGroup(self): self.maxDiff=None groupObj = IntegerGroup() p = integer(148829018183496626261556856344710600327516732500226144177322012998064772051982752493460332138204351040296264880017943408846937646702376203733370973197019636813306480144595809796154634625021213611577190781215296823124523899584781302512549499802030946698512327294159881907114777803654670044046376468983244647367) 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 authoriseEntity(self, EntityID, HealthRecordType): db = Database() # Create the tuple and sign it # mPK_bytes = db.getSignPubKey("master") # bytes of the master public key # mPK = bytesToObject(mPK_bytes, self.signGroup) # de-serialize the key before usage date = time.strftime("%Y-%m-%d %H:%M:%S") signature = objectToBytes(self.waters.sign(self.masterPK, self.signK, ''.join(self.ID + EntityID + HealthRecordType + date)), self.signGroup) db.insertAuthorisation(self.ID, EntityID, HealthRecordType, date, signature) db.done()
def rkGenPKenc(self, params, skid, public_key): X = group.random(GT) Xbytes = objectToBytes( X, group) enc = pkenc.encrypt(public_key, Xbytes) rk = {'R1':enc, 'R2':(1/(skid['skid']))*group.hash(X,G1)} if(debug): print("\nRe-encryption key =>" ) print(rk) return rk
def setUp(self): print('PREENC...') self.pool = pre_enc(10) #printpool(self.pool) from charm.core.engine.util import objectToBytes print('key: ' + objectToBytes(self.pool['key'],PairingGroup('SS512'))) print('C.I. ENCRYPT...') self.enc_data = encrypt(policy_str=pol,pool=self.pool,data='the dude abides') print('enc_data = ', self.enc_data)
def encAES(self, m): if self.dek is None: raise Exception('DEK is null, cannot encrypt') a = AuthenticatedCryptoAbstraction(bytes(self.dek, "utf-8")) CT_AES = a.encrypt(m) groupObj = PairingGroup('SS512') return objectToBytes(CT_AES, groupObj)
def shutdown(): group = state['groupObj'] del state['gp']['H'] del state['dabe'] del state['groupObj'] del state['hyb_abema'] ret = util.objectToBytes(state, group) return ret
def aggregate_key_size(aggregate_key): ag = {} if (aggregate_key[0] is not None): ag['K_s'] = objectToBytes(aggregate_key[0], group) ag['S'] = {} ag['S']['start_frame'] = min(aggregate_key[1]) ag['S']['end_frame'] = max(aggregate_key[1]) ag['tree_cover'] = list(aggregate_key[2]) # print getsizeof(pickle.dumps(ag['tree_cover'])) return getsizeof(pickle.dumps(ag))