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 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(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 testHybridABEnc(self): 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 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
hyb_abe = HybridABEnc(cpabe, groupObj) (pk, mk) = hyb_abe.setup() access_policy = '((four or three) and (two or one))' sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE']) print(sk) plaintext = "Bounty Name: EMR Functional Testing" ciphertext = hyb_abe.encrypt(pk, plaintext, access_policy) print(ciphertext) ciphertext["c1"]["C"] = groupObj.serialize(ciphertext["c1"]["C"]) for key in ciphertext["c1"]["Cy"]: ciphertext["c1"]["Cy"][key] = groupObj.serialize( ciphertext["c1"]["Cy"][key]) ciphertext["c1"]["C_tilde"] = groupObj.serialize( ciphertext["c1"]["C_tilde"]) for key in ciphertext["c1"]["Cyp"]: ciphertext["c1"]["Cyp"][key] = groupObj.serialize( ciphertext["c1"]["Cyp"][key]) ciphertext2 = ciphertext ciphertext2["c1"]["C"] = groupObj.deserialize(ciphertext["c1"]["C"]) for key in ciphertext2["c1"]["Cy"]: ciphertext2["c1"]["Cy"][key] = groupObj.deserialize( ciphertext2["c1"]["Cy"][key]) ciphertext2["c1"]["C_tilde"] = groupObj.deserialize( ciphertext2["c1"]["C_tilde"]) for key in ciphertext2["c1"]["Cyp"]: ciphertext2["c1"]["Cyp"][key] = groupObj.deserialize( ciphertext2["c1"]["Cyp"][key]) print(hyb_abe.decrypt(pk, sk, ciphertext2) == plaintext)
#print(json.dumps(pk['g'], cls='pairingElement')) print(json.dumps({'g' : 1}, cls='pairingElement')) exit() #print("pk => ", pk, "\n") #print ("\n\n",pk["g"], "\n", pk["g2"], "\n",pk["h"], "\n",pk["f"], "\n",pk["e_gg_alpha"], "\n" ) #print ("\n\n---\n") print("mk => ", mk, "\n") sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE']) #print("sk => ", sk, "\n") ct = hyb_abe.encrypt(pk, message, access_policy) #print("ct => ", ct, "\n") mdec = hyb_abe.decrypt(pk, sk, ct) assert mdec == message, "Failed Decryption!!!" print("Successful Decryption!!!", "\n") print('end') class pairingElement(json.JSONEncoder): def default(self, obj): if isinstance(obj, pairingElement): # for i in obj: # print(i) obj = "pairingElement" else: obj = super(pairingElement, self).default(obj)
from charm.toolbox.pairinggroup import PairingGroup from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07 from charm.adapters.abenc_adapt_hybrid import HybridABEnc debug = True 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!!!")
kevin_attributes = ['BUSINESSSTAFF', 'STRATEGYTEAM', 'EXECUTIVELEVEL7'] print(sara_attributes) print(kevin_attributes) sara_sk = hybrid_abe.keygen(pk, mk, sara_attributes) sara_sk = objectToBytes(sara_sk, groupObj) if debug: print("sara_sk => ", sara_sk) kevin_sk = hybrid_abe.keygen(pk, mk, kevin_attributes) kevin_sk = objectToBytes(kevin_sk, groupObj) if debug: print("kevin_sk => ", kevin_sk) try: sara_plaintext = hybrid_abe.decrypt(pk, bytesToObject(sara_sk,groupObj), bytesToObject(ciphertext,groupObj)) if debug: print("sara_plaintext: " + str(sara_plaintext)) assert sara_plaintext != data except Exception as e: print("Sara can't decrypt ciphertext") traceback.print_exc() finally: print("Decrypting using Sara's private key finished") try: kevin_plaintext = hybrid_abe.decrypt(pk, bytesToObject(kevin_sk,groupObj), bytesToObject(ciphertext,groupObj)) if debug: print("kevin_plaintext: " + str(kevin_plaintext,'utf-8')) assert kevin_plaintext == data
from charm.toolbox.pairinggroup import PairingGroup from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07 from charm.adapters.abenc_adapt_hybrid import HybridABEnc import json import pickle if __name__ == "__main__": groupObj = PairingGroup('MNT224') cpabe = CPabe_BSW07(groupObj) hyb_abe = HybridABEnc(cpabe, groupObj) (pk, mk) = hyb_abe.setup() print("*********************************************") for key in pk.keys(): print(key + ": " + str(pk.get(key))) print("*********************************************") print("*********************************************") access_policy = '((FOUR or three) and (two or one))' plaintext = "Bounty Name: EMR Functional Testing" attr_list = ['ONE', 'FOUR'] ciphertext = hyb_abe.encrypt(pk, plaintext, access_policy) sk = hyb_abe.keygen(pk, mk, attr_list) try: dt = hyb_abe.decrypt(pk, sk, ciphertext).decode('utf-8') except: print("failed to decrypt") else: if (dt == plaintext): print(dt)
class WrapperCpabeBSW07(Wrapper): ''' wrapper implementation class to call cp-ABE BSW07 with object-to-bytes keys ''' curve = None __debug = 4 """int: debug""" groupObj = None """PairingGroup: groupObj""" cpabe = None """HybridABEnc: cpabe""" def __init__(self, curve): global DEBUG try: self.__debug = DEBUG except: pass self.curve = curve self.groupObj = PairingGroup(self.curve) cpabe = CPabe_BSW07(self.groupObj) self.cpabe = HybridABEnc(cpabe, self.groupObj) #@list(str, str) def setup(self): (PK, MK) = self.cpabe.setup() serPK = objectToBytes(PK, self.groupObj) serMK = objectToBytes(MK, self.groupObj) return (serPK, serMK) # @Input(pk_t, sk_t, ct_t) # @Output(serPK, serMK) def keygen(self, serPK, serMK, attributeList): if attributeList is None \ or not(isinstance( attributeList, list)): raise Exception("attributeList must be set and a list!") PK = bytesToObject(serPK, self.groupObj) MK = bytesToObject(serMK, self.groupObj) SK = self.cpabe.keygen(PK, MK, attributeList) serSK = objectToBytes(SK, self.groupObj) return serSK def encrypt(self, serPK, M, accessStructure): PK = bytesToObject(serPK, self.groupObj) return self.cpabe.encrypt(PK, M, accessStructure) def decrypt(self, serPK, serSK, CT): PK = bytesToObject(serPK, self.groupObj) SK = bytesToObject(serSK, self.groupObj) return self.cpabe.decrypt(PK, SK, CT) def getDEK(self): """selects a new DEK from G1""" return sha1(self.groupObj.random(G1)) 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 refreshSK(self, serSK, conversionFactor): ''' refreshes the SK by the conversion_factor return newSerSK ''' #{ 'D':D, 'Dj':D_j, 'Djp':D_j_pr, 'S':S } SK = bytesToObject(serSK, self.groupObj) SK['D'] = SK['D'] * conversionFactor return objectToBytes(SK, self.groupObj)