def encrypt(key, content): a = SymmetricCryptoAbstraction(extractor(key)) results = 0.0 for i in range(0, number): start = time.clock() a.encrypt(content) end = time.clock() results += end - start mean = results / number logging.info("AES encrypt: " + str(mean)) cipher = a.encrypt(content) return cipher
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 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 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 encrypt_text(self, pt, secret): try: k = extractor(secret) symcrypt = SymmetricCryptoAbstraction(k) ct = symcrypt.encrypt(pt) return ct except Exception as e: print("Unexpected error:", str(e))
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 encrypt(self, pk, M, attr_list): if debug: print('Encryption Algorithm...') k = group.random(ZR) Cs = pk**k Ci = {} for attr in attr_list: Ci[attr] = self.attribute[attr]**k symcrypt = SymmetricCryptoAbstraction(extractor(Cs)) C = symcrypt.encrypt(M) return {'C': C, 'Ci': Ci, 'attributes': attr_list}
def main(): groupObj = PairingGroup('SS512') dabe = Dabe(groupObj) GP = dabe.get_global_PP_json("./gpp/global_parameters.json") filename = "SERVER_KEY.json" pk_ser = {} with open(filename, 'r') as f: Ser_json = json.load(f) for i in (Ser_json['pk_ser']).keys(): pk_ser['V'] = groupObj.deserialize(bytes(Ser_json['pk_ser']['V'], encoding='utf-8')) pk_ser['X'] = groupObj.deserialize(bytes(Ser_json['pk_ser']['X'], encoding='utf-8')) with open('./policy.pp', 'r') as f: lists = f.readlines() policy = lists[0].rstrip('\n') with open('./message.pp', 'r') as f: pm = f.read() # symmetric key for encryption ssk = groupObj.random(GT) print("\nsymmetric key is\n") print(ssk) symcrypt = SymmetricCryptoAbstraction(extractor(ssk)) SSCT = symcrypt.encrypt(pm) filename = "SYMMETRIC_CIPHERTEXT.ct" with open(filename, 'w') as file_object: file_object.write(SSCT) #m = groupObj.init(GT, tt) # Number of keywords for index generation print("\nEncrypted search index is") num_kw = int(sys.argv[1]) keywords = [] for i in range(0, num_kw): keywords.append(sys.argv[2 + i]) Offline_CT = dabe.get_Offline_CT_json("OFFLINE_CIPHERTEXT.json") CT = dabe.online_encrypt(GP, pk_ser, Offline_CT, ssk, policy, keywords) print(CT) filename = "ENCRYPTED_INDEX.json" FullCT_json = {} for i in CT.keys(): if type(CT[i]) == dict: FullCT_json[i] = {} for j in CT[i].keys(): FullCT_json[i].update({j: str(groupObj.serialize(CT[i][j]), encoding='utf-8')}) elif i == 'policy': FullCT_json[i] = CT[i] else: FullCT_json[i] = str(groupObj.serialize(CT[i]), encoding='utf-8') with open(filename, 'w') as file_object: json.dump(FullCT_json, file_object)
def encrypt(self, pk, M, attr_list): if debug: print('Encryption Algorithm...') k = group.random(ZR); Cs = pk ** k Ci = {} for attr in attr_list: Ci[attr] = self.attribute[attr] ** k symcrypt = SymmetricCryptoAbstraction(hashPair(Cs)) C = symcrypt.encrypt(M) # HMAC # from charm.toolbox.symcrypto import MessageAuthenticator # m = MessageAuthenticator(extract_key(key)) # AuthenticatedMessage = m.mac('Hello World') return { 'C': C, 'Ci': Ci,'attributes': attr_list }
def insert(user, data, record, type_attribute): """ Insert data into a public health record. :param user: User that wants to insert data :param data: Data to be inserted :param record: Public health record in which data is inserted. :param type_attribute: The type for this record """ # Check if some arguments are correct if record is None: sys.exit("Please provide the record") if SYMKEY() in data: sys.exit("Data contains the key {}, please use a different key".format( SYMKEY())) # Load the users key user_key = load_user_key(user) # Create new symmetric key sym_crypto_key = group.random(GT) sym_crypto = SymmetricCryptoAbstraction(extract_key(sym_crypto_key)) # Encrypt symmetric key with TIPRE # and the data using the symmetric key encrypted_sym_key = pre.encrypt(get_params(), user, sym_crypto_key, user_key, type_attribute) encrypted_data = {k: sym_crypto.encrypt(v) for k, v in data.items()} encrypted_data[SYMKEY()] = encrypted_sym_key # Store the data try: data_helper.save(user, type_attribute, encrypted_data, record) print("Data is inserted into record \'{}\' by \'{}\'".format( record, user)) print("Data to insert into record:\n{}".format(data)) except RecordAlreadyExists as e: print(e)
def requestIdentityBasedPrivateKey(self): """ Setup a local PKG only for this Device to be able to do initialization with a PKG. Set the KeyLocator to the ID of the requesting Device. Append the TemporaryMasterPublicKey to the Interest. Interest: Name: /ndn/no/ntnu/initDevice/<nonce>/<tempMasterPublicKey> Selector: KeyLocator = ID Send the Interest """ self.initRequestStart = time.clock() ID = self.deviceName.toUri() # Make each init unique with a session self.initSession = str(int(round(util.getNowMilliseconds() / 1000.0))) a = SymmetricCryptoAbstraction(self.presharedKey) message = {"ID": ID, "nonce": self.initSession} cipher = a.encrypt(str(message)) cipherEncoded = base64.b64encode(cipher) logging.info("Cipher encoded: " + str(cipherEncoded)) name = Name(self.baseName).append("pkg").append("initDevice").append( self.initSession) interest = Interest(name) # interest.setMinSuffixComponents(6) keyLocator = KeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.setKeyName(Name(self.deviceName).append(cipherEncoded)) interest.setKeyLocator(keyLocator) logging.info("Expressing interest name: " + name.toUri()) self.face.expressInterest(interest, self.onInitData, self.onTimeout)
def onInterest(self, prefix, interest, transport, registeredPrefixId): """ Interest: Name: /ndn/no/ntnu/<device>/sensorPull/<nonce> Selector: KeyLocator = ID The ID of the requesting Device is stored in KeyLocator in the Interest, and the TemporaryMasterPublicKey to the device is sent in the Interest Name as shown above. Encrypt a symmetric key with the MasterPublicKey and the ID. Encrypt the SensorData with symmetric encryption, using the symmetric key. Data: Content: master_public_key to PKG ibeKey = ibe(randomKey) cipher = encrypt(sensorData, randomKey) Sign the Data and send. :param Name prefix: :param Interest interest: :param Transport transport: An object of a subclass of Transport to use for communication. :param Name registeredPrefixId: """ self.ibs_scheme.verifyInterest(self.signature_master_public_key, interest, self.onVerifiedInterest, self.onVerifyInterestFailed) ID = "" if interest.getKeyLocator().getType() == KeyLocatorType.KEYNAME: ID = interest.getKeyLocator().getKeyName().toUri() keyName = interest.getName() session = keyName.get(keyName.size() - 1).toEscapedString() data = Data(interest.getName()) contentData = "This should be sensordata blablabla" # Symmetric key for encryption self.key = self.ibe_scheme.getRandomKey() # Identity-Based Encryption of symmetric key identityBasedEncryptedKey = self.ibe_scheme.encryptKey( self.master_public_key, ID, self.key) identityBasedEncryptedKey = str( serializeObject(identityBasedEncryptedKey, self.ibe_scheme.group)) # Master Public Key identityBasedMasterPublicKey = str( serializeObject(self.master_public_key, self.ibe_scheme.group)) # Signature Master Public Key identityBasedSignatureMasterPublicKey = str( serializeObject(self.signature_master_public_key, self.ibs_scheme.group)) # Symmetric AES encryption of contentData a = SymmetricCryptoAbstraction(extractor(self.key)) encryptedMessage = a.encrypt(contentData) message = messageBuf_pb2.Message() message.identityBasedMasterPublicKey = identityBasedMasterPublicKey message.identityBasedSignatureMasterPublicKey = identityBasedSignatureMasterPublicKey message.identityBasedEncryptedKey = identityBasedEncryptedKey message.encryptedMessage = encryptedMessage message.encAlgorithm = messageBuf_pb2.Message.AES message.ibeAlgorithm = self.ibe_scheme.algorithm message.ibsAlgorithm = self.ibs_scheme.algorithm message.nonce = session message.timestamp = int(round(util.getNowMilliseconds() / 1000.0)) message.type = messageBuf_pb2.Message.SENSOR_DATA content = message.SerializeToString() metaInfo = MetaInfo() metaInfo.setFreshnessPeriod(30000) # 30 seconds data.setContent(Blob(content)) data.setMetaInfo(metaInfo) self.ibs_scheme.signData(self.signature_master_public_key, self.signature_private_key, self.deviceName, data) #self.keyChain.sign(data, self.certificateName) encodedData = data.wireEncode() logging.info("Encrypting with ID: " + ID) transport.send(encodedData.toBuffer()) logging.info("Sent encrypted Data")
def enc(k1, k2, msg): a1 = SymmetricCryptoAbstraction(k1.to_bytes(16, byteorder='big')) a2 = SymmetricCryptoAbstraction(k2.to_bytes(16, byteorder='big')) c0 = a1.encrypt(msg.to_bytes(16, byteorder='big')) c1 = a2.encrypt(c0) return c1
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 groupObj = PairingGroup('SS512') symKey = groupObj.random(GT) a1 = SymmetricCryptoAbstraction(sha1(symKey)) with open('/Users/cirnotxm/down/pk','rb') as f: msg1 = f.read() ct = a1.encrypt(msg1) cpabe = CPabe09(groupObj) (msk, pk) = cpabe.setup() pol = '((ONE or THREE) and (TWO or FOUR))' with open('/Users/cirnotxm/down/msk','wb') as fm: fm.write(str(msk)) with open('/Users/cirnotxm/down/mpk','wb') as fp: fp.write(str(pk)) with open('/Users/cirnotxm/down/info','wb') as fi: fi.write(ct) print('Acces Policy: %s' % pol) cipher = cpabe.encrypt(pk, symKey, pol) print("\nCiphertext...") print cipher
debug = 0 groupObj = PairingGroup('SS512') pk = groupObj.random(GT) if debug: print pk a = SymmetricCryptoAbstraction(sha1(pk)) try: f = open('/Users/cirnotxm/down/charm.dmg', 'rb') ff = f.read() ct = a.encrypt(ff) if debug: print ct ffe = open('/Users/cirnotxm/down/jiami', 'wb') ffe.write(ct) fpk = open('/Users/cirnotxm/down/pk', 'wb') fpk.write(groupObj.serialize(pk)) finally: ffe.close() f.close()
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
def sym_encrypt(plaintext, key): serial_pt = objectToBytes(plaintext, PairingGroup('SS512')) encrypter = SymmetricCryptoAbstraction(extractor(key)) return encrypter.encrypt(serial_pt)
def encrypt(message, key1, key2): k1 = SymmetricCryptoAbstraction(key1) k2 = SymmetricCryptoAbstraction(key2) c0 = k1.encrypt(message) c1 = k2.encrypt(c0) return c1
if debug: print fileName print fileUrl print pol groupObj = PairingGroup('SS512') AES_pk = groupObj.random(GT) if debug: print AES_pk a = SymmetricCryptoAbstraction(sha1(AES_pk)) try: f = open(fileUrl, "rb") ptext = f.read() ct = a.encrypt(ptext) ctf = tempUrl + fileName if debug: print ctf fr = open(ctf, "wb") fr.write(ct) except: print "Error" finally: f.close() fr.close() cpabe = CPabe09(groupObj) (mk, pk) = cpabe.setup() cipher = cpabe.encrypt(pk, AES_pk, pol)
def SE_Encrypt (key, data): #crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter = lambda : os.urandom(16)) #crypto.encrypt(data) SE=SymmetricCryptoAbstraction (key, AES, MODE_CBC) SE.encrypt (data)
print("\n============= Original Text =============\n") print_byte_array(file_pt[:15]) print("...", end=" ") print("LENGTH OF ORIG FILE", len(file_pt)) # BENCHMARKING: Measure how long the encryption/decryption takes. startTime = time.time() print("\n============ Encrypted Text =============\n") # SETUP SYMM CRYPTO: by default algo is AES in CBC mode symcrypt = SymmetricCryptoAbstraction(secret) # ENCRYPT PLAIN TEXT FROM THE INPUT FILE file_ct = symcrypt.encrypt(file_pt) print("Encryption finished...") print("LENGTH OF ENC FILE", len(file_ct)) print("\n============ Encrypted Key =============\n") # ENCRYPT THE SYMM KEY BY USING CPABE PAIRING-BASED ALGO aes_key_pt = r print("AES key to be encrypted =>", aes_key_pt) aes_key_ct = cpabe.encrypt(cloud_pk, aes_key_pt, access_policy) print("\nEncrypt...\n", aes_key_ct) # DEBUG & VALIDATE THE CIPHER TEXT group.debug(aes_key_ct)
def encrypt(k1, k2, msg): a1 = SymmetricCryptoAbstraction(h(k1)) a2 = SymmetricCryptoAbstraction(h(k2)) c = a2.encrypt(a1.encrypt(msg)) return c
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 enc(k1, k2, msg): a1 = SymmetricCryptoAbstraction(k1) a2 = SymmetricCryptoAbstraction(k2) c0 = a1.encrypt(msg) c1 = a2.encrypt(c0) return c1
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)
debug = 0 groupObj = PairingGroup('SS512') pk = groupObj.random(GT) if debug :print pk a = SymmetricCryptoAbstraction(sha1(pk)) try: f = open('/Users/cirnotxm/down/charm.dmg','rb') ff = f.read() ct = a.encrypt(ff) if debug :print ct ffe = open('/Users/cirnotxm/down/jiami','wb') ffe.write(ct) fpk = open('/Users/cirnotxm/down/pk','wb') fpk.write(groupObj.serialize(pk)) finally: ffe.close() f.close()
if debug : print fileName print fileUrl print pol groupObj = PairingGroup('SS512') AES_pk = groupObj.random(GT) if debug: print AES_pk a = SymmetricCryptoAbstraction(sha1(AES_pk)) try: f = open(fileUrl, "rb") ptext = f.read() ct = a.encrypt(ptext) ctf = tempUrl + fileName; if debug: print ctf fr = open(ctf, "wb") fr.write(ct) except: print "Error" finally: f.close() fr.close() cpabe = CPabe09(groupObj) (mk, pk) = cpabe.setup()
if __name__ == '__main__': from charm.toolbox.pairinggroup import PairingGroup, GT, extract_key from charm.toolbox.symcrypto import SymmetricCryptoAbstraction group = PairingGroup('SS512', secparam=1024) pre = TIPRE(group) ID1 = "Alice" ID2 = "Bob" msg = b'Message to encrypt' type_attribute = group.random(ZR) symcrypto_key = group.random(GT) symcrypto = SymmetricCryptoAbstraction(extract_key(symcrypto_key)) 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