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 decrypt(key, cipher): a = SymmetricCryptoAbstraction(extractor(key)) results = 0.0 for i in range(0, number): start = time.clock() a.decrypt(content) end = time.clock() results += end - start mean = results / number logging.info("AES decrypt: " + str(mean)) content = a.decrypt(cipher) return content
def main(): groupObj = PairingGroup('SS512') dabe = Dabe(groupObj) TP = dabe.get_Trapdoor_json("TRAPDOOR.json") par_filelist = get_files("./PARTIAL_CIPHERTEXT") if len(par_filelist) == 0: return des = "./PLAINTEXT/" if os.path.exists(des): shutil.rmtree(des) os.mkdir(des) for i in par_filelist: Par_CT = dabe.get_Par_CT_json(i) orig_m = dabe.full_decrypt(TP, Par_CT) #print("\nSymmetric key is") #print(orig_m) symcrypt = SymmetricCryptoAbstraction(extractor(orig_m)) filename = "./MATCHED_FILE/SYMMETRIC_CIPHERTEXT_" + ( i.split('_'))[3].split('.')[0] + ".ct" with open(filename, 'r') as f: cm = f.read() pm = symcrypt.decrypt(cm) #print(str(pm, encoding = 'utf-8')) filename = "./PLAINTEXT/SYMMETRIC_PLAINTEXT_" + ( i.split('_'))[3].split('.')[0] + ".pp" with open(filename, 'w') as file_object: file_object.write(str(pm, encoding='utf-8'))
def read(user, record): """ Function to read some public health record, from a given user. Returns all parts of the record. :param user: User public key that wants to read the health record :param record: Public health record to be read """ # Get the record from the file system and load the key data = data_helper.load(user, record) user_key = load_user_key(user) # Decrypt the symmetric key using the TIPRE key sym_crypto_key = pre.decrypt(get_params(), user_key, data[SYMKEY()]) # Setup symmetric crypto sym_crypto = SymmetricCryptoAbstraction(extract_key(sym_crypto_key)) # Attempt to decrypt all columns and return decrypted_record = { k: sym_crypto.decrypt(v) for k, v in data.items() if k != SYMKEY() } return decrypted_record
def MsgTestAESCBCSeperate(self, msg): groupObj = PairingGroup('SS512') ran = groupObj.random(GT) a = SymmetricCryptoAbstraction(sha1(ran)) ct = a.encrypt(msg) b = SymmetricCryptoAbstraction(sha1(ran)) dmsg = b.decrypt(ct) assert msg == dmsg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
def decrypt_text(self, ct, secret): try: k = extractor(secret) symcrypt = SymmetricCryptoAbstraction(k) text = symcrypt.decrypt(ct) return text except Exception as e: print("Unexpected error:", str(e))
def MsgTestAESCBCSeperate(self,msg): groupObj = PairingGroup('SS512') ran = groupObj.random(GT) a = SymmetricCryptoAbstraction(sha1(ran)) ct = a.encrypt(msg) b = SymmetricCryptoAbstraction(sha1(ran)) dmsg = b.decrypt(ct); assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
def ible(pre, ID, msg, k, master_key, params, log_file): if type(msg) != bytes: raise "Message type error: msg should be bytes." # switch for display #debug = True debug = False if debug: print("\nThe original message is: \n", msg) # Generate the Sym Cipher initilized by k symCipher = SymmetricCryptoAbstraction(k) # Symmetric Encrypt: AES(CTR) default t1 = time.time() ct = symCipher.encrypt(msg) t2 = time.time() t_aes = (t2 - t1) * 1000 log = '{0:.4f}'.format(t_aes) + "\t" # Generate private keys for ID sk1 = pre.keyGen(master_key, ID) # Encrypt 'Sym k' using ID t1 = time.time() ck = pre.encrypt_jet(params, ID, k) t2 = time.time() t_ibe = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_ibe) + "\t" # decryption using sk1 t1 = time.time() dk = pre.decrypt_jet(params, sk1, ck) t2 = time.time() t_ibd = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_ibd) + "\t" if debug: print("\nThe decrypted key is:\n", dk) # Transmit dk and ct to the receipt # ........ # Sym decrypt using the IBD output decipher = SymmetricCryptoAbstraction(dk) t1 = time.time() dmsg = decipher.decrypt(ct) t2 = time.time() t_aes2 = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_aes2) + "\n" if debug: print("\nThe decrypted message is:\n", dmsg) assert dmsg == msg, 'o: =>%s\nm: =>%s' % (msg, dmsg) # output log log_file.write(log)
def decrypt(self, C, D): policy = util.createPolicy(D['policy']) attrs = util.prune(policy, C['attributes']) if attrs == False: return False coeff = util.getCoefficients(policy) Z = {} prodT = 1 for i in range(len(attrs)): x = attrs[i].getAttribute() y = attrs[i].getAttributeAndIndex() Z[y] = C['Ci'][x]**D['Du'][x] prodT *= Z[y]**coeff[y] symcrypt = SymmetricCryptoAbstraction(extractor(prodT)) return symcrypt.decrypt(C['C'])
# print pk+"\n" # print cipher+"\n" mk = bytesToObject(mk, groupObj) pk = bytesToObject(pk, groupObj) cipher = bytesToObject(cipher, groupObj) sk = cpabe.keygen(pk, mk, asl) print sk try: plaintext = cpabe.decrypt(pk, sk, cipher) except: print "Error" if plaintext != False: a = SymmetricCryptoAbstraction(sha1(plaintext)) with open(fileUrl, "rb") as f: cloudfile = f.read() file = a.decrypt(cloudfile) with open(fileUrl, "wb") as re: re.write(file) else: print "Dcrypto Fail!" del groupObj #os.remove(configUrl)
def decrypt(self, C, prodT,h): symcrypt = SymmetricCryptoAbstraction(hashPair(prodT*h)) return symcrypt.decrypt(C['C'])
from charm.toolbox.pairinggroup import PairingGroup, GT from charm.core.math.pairing import hashPair as sha1 from charm.schemes.abenc.abenc_waters09 import CPabe09 from charm.toolbox.symcrypto import SymmetricCryptoAbstraction, AuthenticatedCryptoAbstraction, MessageAuthenticator asl = ['ONE', 'TWO'] groupObj = PairingGroup('SS512') cpabe = CPabe09(groupObj) with open('/Users/cirnotxm/down/info', 'rb') as f: info = f.read() cpkey = cpabe.keygen(pk, msk, asl) with open('/Users/cirnotxm/down/cipk', 'r') as f2: ciphertext = f2.read() ciphertext = eval(ciphertext) print ciphertext prig_msg = cpabe.decrypt(pk, cpkey, ciphertext) a2 = SymmetricCryptoAbstraction(sha1(orig_symKey)) plaintext = a2.decrypt(info) print plaintext
def dec(k1, k2, ct): a1 = SymmetricCryptoAbstraction(k1.to_bytes(16, byteorder='big')) a2 = SymmetricCryptoAbstraction(k2.to_bytes(16, byteorder='big')) m0 = a2.decrypt(ct) m1 = a1.decrypt(m0) return m1
from charm.toolbox.pairinggroup import PairingGroup, ZR, G1, G2, GT, pair, extract_key from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction, SymmetricCryptoAbstraction from charm.core.math.pairing import hashPair as extractor group = PairingGroup("SS512") msg = b"This is a secret message that is larger than the group elements and has to be encrypted symmetrically" print("original msg\n", msg) r = group.random(G1) print("random num\n", r) # key = extractor(r) key = extract_key(r) print("symmetric key\n", key) symcrypt = SymmetricCryptoAbstraction( key) # or SymmetricCryptoAbstraction without authentication # by default algo is AES in CBC mode # encryption ciphertext = symcrypt.encrypt(msg) print("ciphertext\n", ciphertext) # decryption recoveredMsg = symcrypt.decrypt(ciphertext) print("recovered msg\n", recoveredMsg) assert msg == recoveredMsg
from charm.core.math.pairing import hashPair as sha1 from charm.schemes.abenc.abenc_waters09 import CPabe09 from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator asl= ['ONE','TWO'] groupObj = PairingGroup('SS512') cpabe = CPabe09(groupObj) with open('/Users/cirnotxm/down/info','rb') as f: info = f.read() cpkey = cpabe.keygen(pk,msk,asl) with open('/Users/cirnotxm/down/cipk','r') as f2: ciphertext = f2.read() ciphertext = eval(ciphertext) print ciphertext prig_msg = cpabe.decrypt(pk,cpkey,ciphertext) a2 = SymmetricCryptoAbstraction(sha1(orig_symKey)) plaintext = a2.decrypt(info) print plaintext
def hibre(pre, ID1, ID2, msg, k, master_key, params, log_file): if type(msg) != bytes: raise "Message type error: msg should be bytes." # switch for display #debug = True debug = False if debug: print("\nThe original message is: \n", msg) # Generate IBE private keys for IDs sk1 = pre.keyGen(master_key, ID1) sk2 = pre.keyGen(master_key, ID2) # Generate the Sym Cipher initilized by k symCipher = SymmetricCryptoAbstraction(k) # Symmetric Encrypt the message: AES(CTR) default t1 = time.time() ct = symCipher.encrypt(msg) t2 = time.time() t_aes = (t2 - t1) * 1000 log = '{0:.4f}'.format(t_aes) + "\t" # Generate Re-Key (1-->2), using sk1 and ID2 t1 = time.time() rk = pre.rkGen(params, sk1, ID2) t2 = time.time() t_grk = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_grk) + "\t" # IBE the sym key using ID1: IBE1 t1 = time.time() ck = pre.encrypt_jet(params, ID1, k) t2 = time.time() t_kibe = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_kibe) + "\t" # Re-encrypt using Re-Key t1 = time.time() ck2 = pre.reEncrypt_jet(params, rk, ck) t2 = time.time() t_kre = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_kre) + "\t" # IBD using sk2 to get sym key t1 = time.time() dk = pre.decrypt_jet(params, sk2, ck2) t2 = time.time() t_kibd = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_kibd) + "\t" # Sym decrypt using the IBD output # Generate sym cipher using the output key decipher = SymmetricCryptoAbstraction(dk) t1 = time.time() dmsg = decipher.decrypt(ct) t2 = time.time() t_aes2 = (t2 - t1) * 1000 log += '{0:.4f}'.format(t_aes2) + "\n" if debug: print("\nThe decrypted message is:\n", dmsg) assert dmsg == msg, 'o: =>%s\nm: =>%s' % (msg, dmsg) log_file.write(log)
def MsgtestAESCBC(self,msg): groupObj = PairingGroup('SS512') a = SymmetricCryptoAbstraction(sha1(groupObj.random(GT))) ct = a.encrypt(msg) dmsg = a.decrypt(ct); assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
def decrypt(cryptogram, key1, key2): k1 = SymmetricCryptoAbstraction(key1) k2 = SymmetricCryptoAbstraction(key2) m0 = k2.decrypt(cryptogram) m1 = k1.decrypt(m0) return m1
def MsgtestAESCBC(self, msg): groupObj = PairingGroup('SS512') a = SymmetricCryptoAbstraction(sha1(groupObj.random(GT))) ct = a.encrypt(msg) dmsg = a.decrypt(ct) assert msg == dmsg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
aes_key_ct_recovered) print("Pxy Decrypt...") print("Intermediate decryption =>", intmed_value) # USER DECRYPTS THE AES KEY BY USING INTMD VALUE recovered_aes_key = cpabe.user_decrypt(cloud_pk, sk_u, intmed_value) print("\nUser Decrypt...") print("Recovered message =>", recovered_aes_key) print("\n============ Decrypted Text =============\n") # RECOVER THE AES SYMM ENCRYPTION CONFIGURATION rec_secret = extractor(recovered_aes_key) rec_symcrypt = SymmetricCryptoAbstraction(rec_secret) rec_file_pt = rec_symcrypt.decrypt(read_file_ct) print_byte_array(rec_file_pt[:15]) print("...") print("\nLENGTH OF DEC FILE", len(rec_file_pt)) # OUTPUT THE RECOVERED FILE PLAINTEXT outputFileObj = open(outputFilename, 'wb') outputFileObj.write(bytes(rec_file_pt)) outputFileObj.close() # DISPLAY THE FINAL OUTCOME if rec_file_pt == file_pt: print("Demonstration Succeeded!") else:
def decrypt(k1, k2, ctx): a1 = SymmetricCryptoAbstraction(h(k1)) a2 = SymmetricCryptoAbstraction(h(k2)) expansion_ratio = a1.decrypt((a2.decrypt(ctx)).decode("utf-8")) return expansion_ratio
bytest_text = symcrypto.encrypt(msg) (master_secret_key, params) = pre.setup() # Run by trusted party, someone needs to handle the master secret key id1_secret_key = pre.keyGen(master_secret_key, ID1) id2_secret_key = pre.keyGen(master_secret_key, ID2) # Run by delegator (id_name_1), encrypt the sym key ciphertext = pre.encrypt(params, ID1, symcrypto_key, id1_secret_key, type_attribute) # Directly decrypt ciphertext by the same party plain = pre.decrypt(params, id1_secret_key, ciphertext) print('Symmetric key directly decrypted by party 1: {}\n'.format(plain)) # # Run by delegator (id_name_1) create reencryption key for ID2, used by the proxy re_encryption_key = pre.rkGen(params, id1_secret_key, ID2, type_attribute) # Run by the proxy, uses the re encryption key generated by ID1 ciphertext2 = pre.reEncrypt(params, re_encryption_key, ciphertext) # Run by the delegatee (id_name_2), retrieve the secrey key symcrypto_key_decrypted = pre.decrypt(params, id2_secret_key, ciphertext2) print('Symmetric key decrypted by party 2: {}'.format(symcrypto_key_decrypted)) # Use the secrey key to decrypt a msg symcrypto = SymmetricCryptoAbstraction(extract_key(symcrypto_key_decrypted)) decrypted_ct = symcrypto.decrypt(bytest_text) print('Decrypted: {}'.format(decrypted_ct))
def onInitData(self, interest, data): """ Data: Content: master_public_key to PKG ibeKey = ibe(randomKey) cipher = encrypt(PrivateKey, randomKey) Decrypt the symmetric key with the TemporaryMasterPublicKey and the device ID. Use the symmetric key to decrypt the PrivateKey. Device is now added to the PKG :param Interest interest: :param Data data: """ message = messageBuf_pb2.Message() message.ParseFromString(data.getContent().toRawStr()) # TODO: Compare session if not self.initSession == message.nonce: logging.warning("Nonce is not equal!") # SignatureMasterPublicKey signatureMasterPublicKeyDict = ast.literal_eval( message.identityBasedSignatureMasterPublicKey) self.signature_master_public_key = deserializeObject( signatureMasterPublicKeyDict, self.ibs_scheme.group) # Verify signature self.ibs_scheme.verifyData(self.signature_master_public_key, data, self.onVerifiedData, self.onVerifyDataFailed) if (message.type == messageBuf_pb2.Message.INIT): if (message.encAlgorithm == messageBuf_pb2.Message.AES): # Check if IBS algorithm is the same if not (self.ibs_scheme.algorithm == message.ibsAlgorithm): logging.error("IBS algorithm doesnt match! Receiver: " + self.ibs_scheme.algorithm + ", Sender: " + message.ibsAlgorithm) # Check if IBE algorithm is the same if not (self.ibe_scheme.algorithm == message.ibeAlgorithm): logging.error("IBE algorithm doesnt match! Receiver: " + self.ibe_scheme.algorithm + ", Sender: " + message.ibeAlgorithm) #Decrypt encryptedMessage # PrivateKeys a = SymmetricCryptoAbstraction(self.presharedKey) privateKeyEncoded = a.decrypt(message.encryptedPK) signaturePrivateKeyEncoded = a.decrypt(message.encryptedSPK) self.private_key = bytesToObject(privateKeyEncoded, self.ibe_scheme.group) self.signature_private_key = bytesToObject( signaturePrivateKeyEncoded, self.ibs_scheme.group) # MasterPublicKey masterPublicKeyDict = ast.literal_eval( message.identityBasedMasterPublicKey) self.master_public_key = deserializeObject( masterPublicKeyDict, self.ibe_scheme.group) logging.info( "Initialization success! PrivateKeys, MasterPublicKeys received." ) self.initRequestEnd = time.clock() logging.info("Initialization time: " + str(self.initRequestEnd - self.initRequestStart))
def dec(k1, k2, ct): a1 = SymmetricCryptoAbstraction(k1) a2 = SymmetricCryptoAbstraction(k2) m0 = a2.decrypt(ct) m1 = a1.decrypt(m0) return m1
def onData(self, interest, data): """ Data: Content: master_public_key to PKG ibeKey = ibe(randomKey) cipher = encrypt(PrivateKey, randomKey) Decode the master_public_key and compare it to the device.master_public_key (if they match, they trust the same PKG) Decrypt the symmetric key, and decrypt the cipher Sensor Data reveiced! :param Interest interest: :param Data data: """ self.ibs_scheme.verifyData(self.signature_master_public_key, data, self.onVerifiedData, self.onVerifyDataFailed) message = messageBuf_pb2.Message() message.ParseFromString(data.getContent().toRawStr()) # TODO: compare nonce session = message.nonce if (message.type == messageBuf_pb2.Message.SENSOR_DATA): if (message.encAlgorithm == messageBuf_pb2.Message.AES): # Check if IBS algorithm is the same if not (self.ibs_scheme.algorithm == message.ibsAlgorithm): logging.error("IBS algorithm doesnt match! Receiver: " + self.ibs_scheme.algorithm + ", Sender: " + message.ibsAlgorithm) #Compare signature_master_public_key signatureMasterPublicKeyDict = ast.literal_eval( message.identityBasedSignatureMasterPublicKey) messageSignatureMPK = deserializeObject( signatureMasterPublicKeyDict, self.ibs_scheme.group) if not (self.signature_master_public_key == messageSignatureMPK): logging.error("SignatureMasterPulicKey does not match!") # Check if IBE algorithm is the same if not (self.ibe_scheme.algorithm == message.ibeAlgorithm): logging.error("IBE algorithm doesnt match! Receiver: " + self.ibe_scheme.algorithm + ", Sender: " + message.ibeAlgorithm) #Compare master_public_key masterPublicKeyDict = ast.literal_eval( message.identityBasedMasterPublicKey) messageMPK = deserializeObject(masterPublicKeyDict, self.ibe_scheme.group) if not (self.master_public_key == messageMPK): logging.error("MasterPulicKey does not match!") #Decrypt identityBasedEncrypedKey identityBasedEncryptedKeyDict = ast.literal_eval( message.identityBasedEncryptedKey) identityBasedEncryptedKey = deserializeObject( identityBasedEncryptedKeyDict, self.ibe_scheme.group) key = self.ibe_scheme.decryptKey(self.master_public_key, self.private_key, identityBasedEncryptedKey) #Decrypt encryptedMessage a = SymmetricCryptoAbstraction(extractor(key)) data = a.decrypt(message.encryptedMessage) # Use data from device to something .. logging.info("Data received: " + str(data)) self.dataRequestEnd = time.clock() logging.info("Request and receive data time: " + str(self.dataRequestEnd - self.dataRequestStart))
def sym_decrypt(ciphertext, key): decrypter = SymmetricCryptoAbstraction(extractor(key)) serial_pt = decrypter.decrypt(ciphertext) return bytesToObject(serial_pt, PairingGroup('SS512'))
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction, AuthenticatedCryptoAbstraction, MessageAuthenticator from charm.toolbox.pairinggroup import PairingGroup, GT from charm.core.math.pairing import hashPair as sha1 debug = 0 groupObj = PairingGroup('SS512') try: f = open('/Users/cirnotxm/down/pk', 'rb') pk = f.read() a = SymmetricCryptoAbstraction(sha1(groupObj.deserialize(pk))) ffe = open('/Users/cirnotxm/down/jiami', 'rb') ct = ffe.read() de = a.decrypt(ct) fpk = open('/Users/cirnotxm/down/jiemi.dmg', 'wb') fpk.write(de) finally: ffe.close() f.close() fpk.close()
# print pk+"\n" # print cipher+"\n" mk = bytesToObject(mk,groupObj) pk = bytesToObject(pk,groupObj) cipher = bytesToObject(cipher,groupObj) sk = cpabe.keygen(pk,mk,asl) print sk try: plaintext = cpabe.decrypt(pk,sk,cipher) except: print "Error" if plaintext!=False : a = SymmetricCryptoAbstraction(sha1(plaintext)) with open(fileUrl,"rb") as f: cloudfile = f.read() file = a.decrypt(cloudfile) with open(fileUrl,"wb") as re: re.write(file) else: print "Dcrypto Fail!" del groupObj #os.remove(configUrl)