def __init__(self, symbol_graph): ''' Constructor ''' # initialize CPABE object self._group = PairingGroup('SS512') self._cpabe = CPabe_BSW07(self._group) self._hyb_abe = HybridABEnc(self._cpabe, self._group) #access_policy = '(ar and bc)' #message = "hello world this is an important message." #(pk, mk) = self._hyb_abe.setup() #sk = self._hyb_abe.keygen(pk, mk, ['AR', 'BC']) #ct = self._hyb_abe.encrypt(pk, message, access_policy) #try: # result = self._hyb_abe.decrypt(pk, sk, ct) # print result #except Exception: # pass # attributes should be vertices # since its diDraph, the query of two vertices sequence matters # row and col symbol is interpreted differently self._symbol_graph = symbol_graph symbols = self._symbol_graph.get_keys() for i in symbols: # r means row attributes self._attributes.append(symbols[i] + 'r') # c means column attributes self._attributes.append(symbols[i] + 'c')
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!!!")
def decrypt(self, master_public_key, sk, cipher_matrix, vertices): ''' Decryption requires master_public_key, user secret key, and cipher ''' group = PairingGroup('SS512') cpabe = CPabe_BSW07(group) hyb_abe = HybridABEnc(cpabe, group) N = len(vertices) resMat = [None] * N for i in range(0, N): resMat[i] = [None] * N for j in range(0, N): #convert to lower case s = vertices[i].lower() s2 = vertices[j].lower() cipher = cipher_matrix.get_cell_by_symbol(s, s2) resMat[i][j] = hyb_abe.decrypt(master_public_key, sk, cipher) if resMat[i][j] == False: return False result = AdjMatrixDiGraph(mat=resMat) return SymbolDiGraphMat(vertices, G=result)
def decrypt(enc_data=None, pk=None, sk=None, pairing_group=None, debug=0): """ Decrypt encrypted data with CP-ABE using the given public and secret key. :param enc_data: encrypted data to decrypt :param pk: CP-ABE public key :param sk: CP-ABE secret key :param pairing_group: pairing group to use :param debug: if 1, prints will be shown during execution; default 0, no prints are shown :return: decrypted data """ # Check if enc_data is set if enc_data is None: logging.error('decrypt_seed_key ciphertext exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key ciphertext') raise Exception # Check if pk is set and it exists if pk is None: logging.error('[ERROR] decrypt_seed_key pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key pk_file') raise Exception # Check if sk is set and it exists if sk is None: logging.error('decrypt_seed_key sk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key sk_file') raise Exception # Decrypt data with CP-ABE and return the result cpabe = CPabe_BSW07(pairing_group) return cpabe.decrypt(pk, sk, enc_data)
def cpabe_setup(group): """Generates master key pair for the Bethencourt2007cae CP-ABE Scheme. @param group The `PairingGroup` used within the underlying crypto. @return The master public and private key pair `(pk_t, mk_t)` as defined in the CPabe_BSW07 Scheme. """ return CPabe_BSW07(group).setup()
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 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 test_charm_crypto(): # instantiate a bilinear pairing map pairing_group = PairingGroup('MNT224') cpabe = CPabe_BSW07(pairing_group) hyb_abe = HybridABEnc(cpabe, pairing_group) # run the set up (pk, msk) = hyb_abe.setup() # Public Key and Master SECRET Key # generate a key attr_list = ['U-11890454', 'D-46', 'D-46-GUEST'] key = hyb_abe.keygen(pk, msk, attr_list) serialized_pk = serialize_charm_object(pk, pairing_group) pk = deserialize_charm_object(serialized_pk, pairing_group) serialized_key = serialize_charm_object(key, pairing_group) key = deserialize_charm_object(serialized_key, pairing_group) # choose a random message msg = "Hello World" # generate a ciphertext policy_str = '(u-11890454 OR d-46 OR d-46-GUEST)' # evaluates to "((U-11890454 or D-46) or D-46-GUEST)" - see upper chars ctxt = hyb_abe.encrypt(pk, msg, policy_str) policy_str = '(u-1 AND d-46 AND d-46-GUEST)' # Re-encrypted data with new policy ctxt2 = hyb_abe.encrypt(pk, msg, policy_str) # decryption rec_msg = hyb_abe.decrypt(pk, key, ctxt).decode("utf-8") with pytest.raises(Exception): hyb_abe.decrypt(pk, key, ctxt2) assert rec_msg == msg, "Failed." # "First successfully decrypted, second not."
def cpabe_decrypt(group, mpk, deckey, ctxt): """Decrypts a ciphertext using the Bethencourt2007cae CP-ABE Scheme. The plaintext will be returned iff the policy used to generate the cipher-text can be satisfied by the set of attributes within the decryption key. @param group The `PairingGroup` used within the underlying crypto. @param mpk The Master Public Key of type `mk_t`. @param deckey The decryption key of type `sk_t`. @param ctxt The `bytearray` resulting from io.open or io.IOBytes containing the ciphertext. @return The `bytearray` containing the plaintext. @throws PebelDecryptionException If deckey cannot satisfy the policy within the ciphertext. """ cpabe = CPabe_BSW07(group) ptxt = io.BytesIO() iv = ctxt.read(AES.block_size) session_key_size = struct.unpack('<Q', ctxt.read(struct.calcsize('Q')))[0] session_key_ctxt = bytesToObject(ctxt.read(session_key_size), group) session_key = cpabe.decrypt(mpk,deckey, session_key_ctxt) if session_key: symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv) for b in read_data(bin_data=ctxt, chunksize=AES.block_size): ptxt.write(symcipher.decrypt(b)) ptxt.flush() return ptxt.getvalue() else: raise PebelDecryptionException("Unable to decrypt given cipher-text.")
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 decrypt_seed_key_len(enc_seed_key_len=None, pk_file=None, sk_file=None, debug=0): """ Decrypt encrypted seed, symmetric key and re-encryption length with ABE using the given public and secret key. :param enc_seed_key: encrypted seed, symmetric key and re-encryption length to decrypt :param pk_file: ABE public key :param sk_file: ABE secret key :param debug: if 1, prints will be shown during execution; default 0, no prints are shown :return: decrypted seed, symmetric key and number of re-encryption length """ import logging import os.path # Check if enc_seed_key is set if enc_seed_key_len is None: logging.error('decrypt_seed_key ciphertext exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key ciphertext') raise Exception # Check if pk_file is set and it exists if pk_file is None or not os.path.isfile(pk_file): logging.error('[ERROR] decrypt_seed_key pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key pk_file') raise Exception # Check if sk_file is set and it exists if sk_file is None or not os.path.isfile(sk_file): logging.error('decrypt_seed_key sk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key sk_file') raise Exception # Decrypt data with ABE pairing_group = pg.pairing_group_create('MNT224') with open(pk_file, 'rb') as f: pk = bytesToObject(f.read(), pairing_group) with open(sk_file, 'rb') as f: sk = bytesToObject(f.read(), pairing_group) # cpabe = AC17CPABE(pairing_group, 2) cpabe = CPabe_BSW07(pairing_group) enc_data = cpabe.decrypt(pk, sk, enc_seed_key_len) from re_enc_engine.const import H, SYM_KEY_DEFAULT_SIZE, SEED_LENGTH import struct # Retrieve params from decryption output file seed, key, re_enc_length = struct.unpack('%ds%dsH' % (SEED_LENGTH, SYM_KEY_DEFAULT_SIZE), enc_data) if debug: # ONLY USE FOR DEBUG print('DECRYPTED SEED = (%d) %s' % (len(seed), seed)) print('DECRYPTED KEY = (%d) %s' % (len(key), key)) print('DECRYPTED RE_ENC_LENGTH = %d' % re_enc_length) return seed, key, re_enc_length
def decrypt(data=None, pairing_group=None, pk=None, sk=None, policy=None, debug=0): """ Decrypt data using CP-ABE scheme with the given public key and policy :param data: the content to encrypt :param pairing_group: pairing group to use :param pk: public key to use for encryption :param policy: policy to apply during encryption :param debug: if 1, prints will be shown during execution; default 0, no prints are shown :return: encrypted data """ # Check if data is set if data is None: logging.error('encrypt_seed_key_len data exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len data') raise Exception # Check if pk is set if pk is None: logging.error('encrypt_seed_key_len pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len pk_file') raise Exception # Check if policy is set if policy is None: logging.error('encrypt_seed_key_len policy exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len policy') raise Exception if debug: # ONLY USE FOR DEBUG print('DATA = (%s) %s' % (type(data), data)) print('PK = (%s) %s' % (type(pk), pk)) print('POLICY = (%s) %s' % (type(policy), policy)) # Encrypt data with ABE cpabe = CPabe_BSW07(pairing_group) enc_data = cpabe.encrypt(pk, data, policy) if debug: # ONLY USE FOR DEBUG print('ENC DATA WITH POLICY = (%d) %s' % (len(enc_data), enc_data)) enc_data.pop('policy') if debug: # ONLY USE FOR DEBUG print('ENCRYPTED DATA = (%d) %s' % (len(enc_data), enc_data)) return enc_data
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 cpabe_keygen(group, msk, mpk, attributes): """Generates a decryption key for the Bethencourt2007cae CP-ABE Scheme. @param group The `PairingGroup` used within the underlying crypto. @param msk The Master Secret Key of type `mk_t`. @param mpk The Master Public Key of type `pk_t`. @param attributes The set of `str` attributes used to generate the decryption key. @return The generated decryption key (`sk_t`) as defined in the CPabe_BSW07 Scheme. """ return CPabe_BSW07(group).keygen(mpk, msk, attributes)
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 main(): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) access_policy = '((four or three) and (two or one))' message = b"hello world this is an important message." (pk, mk) = hyb_abe.setup() if debug: print("pk => ", pk) if debug: print("mk => ", mk) sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE']) if debug: print("sk => ", sk) ct = hyb_abe.encrypt(pk, message, access_policy) mdec = hyb_abe.decrypt(pk, sk, ct) assert mdec == message, "Failed Decryption!!!" if debug: print("Successful Decryption!!!")
def _load_abe_keys(self, abe_keys_file): """Load public and private abe keys""" if self.debug: print("Loading abe keys from " + abe_keys_file) with open(abe_keys_file, 'r') as f: data = json.load(f) self.abe_pk = {} self.abe_sk = {} for abe_key_pair in data.keys(): self.abe_pk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['pk']), self.pairing_group) self.abe_sk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['sk']), self.pairing_group) self.cpabe = CPabe_BSW07(self.pairing_group)
def main(): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) #access_policy = "((ADS or PVB or ME) and (720 or 168 or 24 or 1) and (SITE) and (KEEP) and (TRACK) and (LOCATE))" access_policy = "(ADS or PVB or ME) and (720 or 168 or 24 or 1) and SITE" message = "hello world this is an important message." (pk, mk) = hyb_abe.setup() if debug: print("pk => ", pk) if debug: print("mk => ", mk) sk = hyb_abe.keygen(pk, mk, ['ADS', '720', 'KEEP', 'TARGET', 'TRACK', 'NOLOCATE']) if debug: print("sk => ", sk) ct = hyb_abe.encrypt(pk, message, access_policy) mdec = hyb_abe.decrypt(pk, sk, ct) assert mdec == message, "Failed Decryption!!!" if debug: print("Successful Decryption!!!")
def cpabe_decrypt(group, mpk, deckey, ctxt): cpabe = CPabe_BSW07(group) ptxt = io.BytesIO() iv = ctxt.read(AES.block_size) session_key_size = struct.unpack('<Q', ctxt.read(struct.calcsize('Q')))[0] session_key_ctxt = bytesToObject(ctxt.read(session_key_size), group) session_key = cpabe.decrypt(mpk, deckey, session_key_ctxt) if session_key: symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv) for b in read_data(bin_data=ctxt, chunksize=AES.block_size): ptxt.write(symcipher.decrypt(b)) ptxt.flush() return ptxt.getvalue() else: raise PebelDecryptionException("Unable to decrypt given cipher-text.")
def decrypt_query(self, master_public_key, sk, cipher_matrix, queries): ''' Decryption requires master_public_key, user secret key, and cipher ''' group = PairingGroup('SS512') cpabe = CPabe_BSW07(group) hyb_abe = HybridABEnc(cpabe, group) msg = '' for query in queries: #convert to lower case s1 = query[0].lower() s2 = query[1].lower() cipher = cipher_matrix.get_cell_by_symbol(s1, s2) msg += hyb_abe.decrypt(master_public_key, sk, cipher) + " " return msg
def encrypt(message, access_policy, debug=True): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) with open("p_key.txt", "rb") as pkFile: pk = bytesToObject(pkFile.read(), groupObj) with open("m_key.txt", "rb") as mkFile: mk = bytesToObject(mkFile.read(), groupObj) ct = hyb_abe.encrypt(pk, message, access_policy) byte_msg = objectToBytes(ct, groupObj) if debug: print("pk => ", pk) print("mk => ", mk) with open("cipher.txt", "wb") as ctFile: ctFile.write(byte_msg) return byte_msg
def main(): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) getPublicKeyFromCA() with open("/home/ubuntu/catkin_ws/src/virtual_drone/p_key_adv.txt", "rb") as pkFile: pk = bytesToObject(pkFile.read(), groupObj) getSecretKeyFromCA() with open("/home/ubuntu/catkin_ws/src/virtual_drone/s_keyD1_adv.txt", "rb") as skFile: sk = bytesToObject(skFile.read(), groupObj) if debug: print("pk => ", pk) if debug: print("sk => ", sk) client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) client.bind(("", 37020)) while True: data, addr = client.recvfrom(65535) if data is not None: ct = bytesToObject(data.decode(), groupObj) msg = hyb_abe.decrypt(pk, sk, ct) if msg != None: jsonData = json.loads(msg.decode()) cmd = jsonData["uid-bcast"]["cmd"] if cmd in cmd_list: if 'takeoff' in cmd.lower(): print('[onboard-vocal-cpabe]: command take-off detected.') Popen("/home/ubuntu/catkin_ws/src/virtual_drone/mavros_offboard_takeoff_land.py", shell=True) elif 'figure eight' in cmd.lower(): print('[flask-run]: command figure-eight detected.') Popen("/home/ubuntu/catkin_ws/src/virtual_drone/mavros_offboard_figure_eight.py", shell=True) elif 'square' in cmd.lower(): print('[flask-run]: command square detected.') Popen("/home/ubuntu/catkin_ws/src/virtual_drone/mavros_offboard_square.py", shell=True) else: print('[flask-run]: command does not match.')
def abe_decrypt(enc_data=None, pk=None, sk=None, pairing_group=None, debug=0): """ Decrypt encrypted seed, symmetric key and re-encryption length with ABE using the given public and secret key. :param enc_seed_key_len: encrypted seed, symmetric key and re-encryption length to decrypt :param pk_file: ABE public key :param sk_file: ABE secret key :param debug: if 1, prints will be shown during execution; default 0, no prints are shown :return: decrypted seed, symmetric key and number of re-encryption length """ # Check if enc_data is set if enc_data is None: logging.error('decrypt_seed_key ciphertext exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key ciphertext') raise Exception # Check if pk is set and it exists if pk is None: logging.error('[ERROR] decrypt_seed_key pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key pk_file') raise Exception # Check if sk is set and it exists if sk is None: logging.error('decrypt_seed_key sk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in decrypt_seed_key sk_file') raise Exception # Decrypt data with ABE cpabe = CPabe_BSW07(pairing_group) data = cpabe.decrypt(pk, sk, enc_data) print('DEC DATA =', data) return data
def cpabe_encrypt(group, mpk, ptxt, policy): 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 _load_abe_keys(self, abe_keys_file): """ Load ABE public and secret keys from the given file :param abe_keys_file: file where keys are stored """ if self.debug: print("Loading abe keys from " + abe_keys_file) # Read file content with open(abe_keys_file, 'r') as f: data = json.load(f) # Retrieve ABE public and secret keys self.abe_pk = {} self.abe_sk = {} for abe_key_pair in data.keys(): self.abe_pk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['pk']), self.pairing_group) self.abe_sk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['sk']), self.pairing_group) # Create CP-ABE cipher self.cpabe = CPabe_BSW07(self.pairing_group)
def main(): groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) CHUNK_SIZE = 8*1024 server_socket = socket.socket() server_socket.bind(("192.168.1.146", 12346)) server_socket.listen(5) with open("p_key.txt", "rb") as pkFile: pk = bytesToObject(pkFile.read(),groupObj) with open("m_key.txt", "rb") as mkFile: mk = bytesToObject(mkFile.read(), groupObj) while True: client_socket,addr = server_socket.accept() data = client_socket.recv(CHUNK_SIZE) print (data.decode()) if data is not None: jsonData = json.loads(data) for request in jsonData: if request == "uid-attr": attribute = jsonData[request]["attr"] sk = hyb_abe.keygen(pk, mk, list(attribute.split(","))) with open("sktmp.txt", "wb") as skFile: skFile.write(objectToBytes(sk, groupObj)) with open("sktmp.txt", "rb") as skFile: client_socket.sendfile(skFile, 0) client_socket.close() os.remove("sktmp.txt") if request == "uid-pk": with open("p_key.txt", "rb") as f: client_socket.sendfile(f, 0) client_socket.close()
def keygen(sk_outfile=None, pk_file=const.ABE_PK_FILE, msk_file=const.ABE_MSK_FILE, pairing_group_curve=const.PAIRING_GROUP_CURVE, attr_list=None, debug=0): """ TODO update documentation Generate a secret key with the listed attributes using public key and master secret key. Output will be written to the file "priv_key" unless sk_outfile is set. Attributes can be non−numerical and numerical: - non−numerical attributes are simply any string of letters, digits, and underscores beginning with a letter; - numerical attributes are specified as ‘attr = N’, where N is a non−negative integer less than 2^64 and ‘attr’ is another string. The whitespace around the ‘=’ is optional. One may specify an explicit length of k bits for the integer by giving ‘attr = N#k’. Note that any comparisons in a policy given to cpabe−enc must then specify the same number of bits, e.g., ‘attr > 5#12’. The keywords ‘and’, ‘or’, and ‘of’ are reserved for the policy language of cpabe−enc and may not be used for either type of attribute. :param sk_outfile: file where private key will be saved :param pk_file: file where public key is stored :param msk_file: file where master secret key is stored :param pairing_group_curve: string representing curve to use for the pairing group :param attr_list: list of attributes related to the secret key that will be generated :param debug: if 1, prints will be shown during execution; default 0, no prints are shown """ # Check if pk_file is set and it exists if pk_file is None or not os.path.isfile(pk_file): logging.error('keygen pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in keygen pk_file') raise Exception # Check if msk_file is set and it exists if msk_file is None or not os.path.isfile(msk_file): logging.error('keygen msk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in keygen msk_file') raise Exception # Check if attr_list is set if attr_list is None: logging.error('keygen attr_list exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in keygen attr_list') raise Exception # Instantiate a bilinear pairing map with the given curve pairing_group = PairingGroup(pairing_group_curve) # CP-ABE under DLIN (2-linear) cpabe = CPabe_BSW07(pairing_group) # Read public and master secret keys from specified files with open(pk_file, 'r') as fin: pk = bytesToObject(bytes.fromhex(fin.read()), pairing_group) with open(msk_file, 'r') as fin: msk = bytesToObject(bytes.fromhex(fin.read()), pairing_group) if debug: # ONLY USE FOR DEBUG print('PK =', pk) print('MSK =', msk) print('Attr list =', attr_list) # Generate the secret key related to the given public and master secret keys and attributes list sk = cpabe.keygen(pk, msk, attr_list) if debug: # ONLY USE FOR DEBUG print('SK =', sk) print('SK BYTES =', objectToBytes(sk, pairing_group)) # Save secret key on specified output file with open(sk_outfile, 'w') as fout: fout.write(objectToBytes(sk, pairing_group).hex())
def encrypt(data=None, pairing_group=None, pk=None, policy=None, debug=0): """ Encrypt data using ABE scheme with the given public key and policy :param data: the content to encrypt :param pairing_group: pairing group to use :param pk: public key to use for encryption :param policy: policy to apply during encryption :param debug: if 1, prints will be shown during execution; default 0, no prints are shown :return: encrypted data """ #starting_time = time() * 1000.0 # Check if data is set if data is None: logging.error('encrypt_seed_key_len data exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len data') raise Exception # Check if pk is set if pk is None: logging.error('encrypt_seed_key_len pk_file exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len pk_file') raise Exception # Check if policy is set if policy is None: logging.error('encrypt_seed_key_len policy exception') if debug: # ONLY USE FOR DEBUG print('EXCEPTION in encrypt_seed_key_len policy') raise Exception if debug: # ONLY USE FOR DEBUG print('DATA = (%s) %s' % (type(data), data)) print('PK = (%s) %s' % (type(pk), pk)) print('POLICY = (%s) %s' % (type(policy), policy)) #elapsed_time = (time() * 1000.0) - starting_time #print('[{}] before CPabe_BSW07'.format(elapsed_time)) # Encrypt data with CP-ABE cpabe = CPabe_BSW07(pairing_group) #elapsed_time = (time() * 1000.0) - starting_time #print('[{}] after Pabe_BSW07'.format(elapsed_time)) enc_data = cpabe.encrypt(pk, data, policy) #elapsed_time = (time() * 1000.0) - starting_time #print('[{}] after cpabe.encrypt'.format(elapsed_time)) if debug: # ONLY USE FOR DEBUG print('ENC DATA WITH POLICY = %s' % enc_data) # Remove policy from encrypted data enc_data.pop('policy') if debug: # ONLY USE FOR DEBUG print('ENCRYPTED DATA = %s' % enc_data) #elapsed_time = (time() * 1000.0) - starting_time #print('[{}] end of abe.encrypt'.format(elapsed_time)) return enc_data
exit(0) file = 'basedir/test' metafile = 'basedir/.abebox/test' with (open(metafile)) as f: meta = json.load(f) with (open('/home/serse/.abe_keys')) as f: data = json.load(f) abe_pk = {} abe_sk = {} pairing_group = pg.pairing_group_create('MNT224') # cpabe = AC17CPABE(pairing_group, 2) cpabe = CPabe_BSW07(pairing_group) policy = '(DEPT1 and TEAM1)' for abe_key_pair in data.keys(): abe_pk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['pk']), pairing_group) abe_sk[abe_key_pair] = bytesToObject( bytes.fromhex(data[abe_key_pair]['sk']), pairing_group) with (open(file, 'rb')) as fin: for chunk in iter(lambda: fin.read(1024), ''): # print('FILE CHUNK = (%s) (%d) %s' % (type(chunk), len(chunk), chunk)) if not len(chunk): break
from config import * import requests from charm.toolbox.pairinggroup import PairingGroup from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07 from charm.adapters.abenc_adapt_hybrid import HybridABEnc from charm.core.engine.util import objectToBytes, bytesToObject policy_length = 16 key_size = 8 groupObj = PairingGroup('SS512') cpabe = CPabe_BSW07(groupObj) hybrid_abe = HybridABEnc(cpabe, groupObj) master_key_file_name = "master_key.json"