def myRSADecrypt(RSACipher, C, IV, t, path, pTK, sig): from cryptography.hazmat.primitives.asymmetric import padding with open(pTK, "rb") as key_file: prk = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend()) pub = prk.public_key() pub.verify( sig, RSACipher, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) newK = prk.decrypt( RSACipher, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) key = newK[0:32] hKey = newK[32:] pt = myfileDecryptHMAC(C, IV, t, key, hKey, path) return pt
def decrypt_object_with_RSA(private_key, password, encrypted_object): import base64 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.primitives import hashes #Decrypt private key _private_key = serialization.load_pem_private_key( private_key, password=password, backend=default_backend()) wrapped_object = {} if 'iv' in encrypted_object: wrapped_object['iv'] = encrypted_object['iv'] else: _log.error("No IV in encrypted object, encrypted_object={}".format( encrypted_object)) return None if 'ciphertext' in encrypted_object: wrapped_object['ciphertext'] = encrypted_object['ciphertext'] else: _log.error( "No ciphertext in encrypted object, encrypted_object={}".format( encrypted_object)) return None #Decrypt symmetric key wrapped_object['symmetric_key'] = _private_key.decrypt( base64.b64decode(encrypted_object['encrypted_symmetric_key']), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #Unwrap the plaintext using symmetric cryptography plaintext = unwrap_object_with_symmetric_key(wrapped_object) return plaintext
def myRSAEncrypt(path, pTK, pTK2): from cryptography.hazmat.primitives.asymmetric import padding C, IV, t, key, hKey, fExt = myfileEncryptHMAC(path) newK = key + hKey with open(pTK, "rb") as key_file: pk = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) with open(pTK2, "rb") as key_file: prk = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend()) RSACipher = pk.encrypt( newK, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) sig = prk.sign( RSACipher, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) return RSACipher, C, IV, t, fExt, sig
def MyRSAEncrypt(filepath, RSA_Publickey_filepath): (C, IV, tag, EncKey, HMACKey, ext) = MyFileEncryptMAC(filepath) key = EncKey + HMACKey #loads public key with open(RSA_Publickey_filepath, 'rb') as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) #encrypts key to make RSACipher RSACipher = public_key.encrypt( key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) key_file.write(RSACipher) key_file.close() ''' encData = {"C": C.decode('cp437'), "RSACipher": RSACipher.decode('cp437'),"EncKey": EncKey.decode('cp437'), "IV": IV.decode('cp437'), "ext": ext, "tag": tag.decode('cp437')} filename, ext = separateFileName(filepath) filenameJSON = filename + ".json" writeJSON(encData, filenameJSON) #delete original file os.remove(filepath) ''' return (RSACipher, C, IV, tag, ext)
def encryptAs(pt, pubkey): ciphertext = pubkey.encrypt( bytes(pt), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return ciphertext
def encrypt_object_with_RSA(certificate, plaintext, unencrypted_data=None): """ Encrypts an object using hybrid cryptography -certificate: PEM certificate -plaintext: string to be encrypted -unencrypted_data: data that will not be encrypted, but appended, e.g., usefull for debugging """ import base64 from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.primitives import hashes #Wrap plaintext with a symmetric key wrapped_object = wrap_object_with_symmetric_key(plaintext) #Extract public key from certificate cert = x509.load_pem_x509_certificate(certificate, default_backend()) message = wrapped_object['symmetric_key'] public_key = cert.public_key() #Encrypt symmetric key with RSA public key ciphertext = public_key.encrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) encrypted_object = { 'encrypted_symmetric_key': base64.b64encode(ciphertext), 'iv': wrapped_object['iv'], 'ciphertext': wrapped_object['ciphertext'], 'unencrypted_data': unencrypted_data } return encrypted_object
def Encrypt(message, publicKey): backend = default_backend() #Load the key #access public key with the path with open(publicKey, "rb") as key_file: RSAPubKey = serialization.load_pem_public_key(key_file.read(), backend=backend) #initialize AES key 256 bits AESKey = os.urandom(32) #initialize AES IV 128 bits iv = os.urandom(16) #Construct an AES cipher object with randomly generated AES key #and a randomly generated IV cipher = Cipher(algorithms.AES(AESKey), modes.CBC(iv), backend=backend) AESencryptor = cipher.encryptor() #Padding is a way to take data that may or may not be a multiple of the #block size for a cipher and extend it out so that it is. This is required #for many block cipher modes as they require the data to be encrypted to be an #exact multiple of the block size. from cryptography.hazmat.primitives import padding #padding is sometimes required to make a message the correct size #must be PKCS7 padder = padding.PKCS7(128).padder() #Set the default string type to UTF8. This #is the default for newer OpenSSLs message = message.encode('utf-8') padded_message = padder.update(message) padded_message += padder.finalize() #AESCipher value is the padded message cipherAES = AESencryptor.update(padded_message) + AESencryptor.finalize() #initialize HMAC key to random 256 bits HMACKey = os.urandom(32) #generate HMAC tag tagHMAC = hmac.HMAC(HMACKey, hashes.SHA256(), backend=default_backend()) tagHMAC.update(cipherAES) #finalize tag tag = tagHMAC.finalize() #concatenate AESKey and HMACKey concatenate = AESKey + HMACKey from cryptography.hazmat.primitives.asymmetric import padding #Encrypt keys with RSA Object aka the Public key cipherRSA = RSAPubKey.encrypt( concatenate, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #return RSA cipther, AES cipher, AES IV, and HMACTag jsonObject = { 'cipherRSA': cipherRSA, 'cipherAES': cipherAES, 'iv': iv, 'tag': tag } return jsonObject
def pk_decrypt(ciphertext: bytes, private_key: rsa.RSAPrivateKey) -> bytes: """ Decrypt an RSAES-OAEP-encrypted message. """ plaintext = private_key.decrypt( ciphertext, padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None)) return plaintext
def pk_encrypt(message: bytes, public_key: rsa.RSAPublicKey) -> bytes: """ Encrypt a message using RSAES-OAEP. """ ciphertext = public_key.encrypt( message, padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None)) return ciphertext
def decryptRSA(private_key, ciphertext): """ RSA DECRYPT """ pText = private_key.decrypt( ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return pText
def encryptRSA(public_key, message): """ RSA ENCRYPT """ cText = public_key.encrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return cText
def decryptAs(ct, prvkey): # decifro il cipher text inviato dal clietn plaintext = prvkey.decrypt( ct, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return plaintext
def Decryptor(jsonInfo, PrivKPath): #use two json loads because the request come with "" marks jsonData = json.loads(jsonInfo) jsonData = json.loads(jsonData) #grab all the information from the json and turn it into bytes RSAcipher = jsonData['RSAcipher'].to_bytes(256, byteorder='big') cipher = int(jsonData['cipher']).to_bytes(jsonData['cipherSize'], byteorder='big') iv = int(jsonData['iv']).to_bytes(16, byteorder='big') tag = int(jsonData['t']).to_bytes(32, byteorder='big') #do the opposite of encrypting from cryptography.hazmat.primitives.asymmetric import padding #load the private key of the user with open(PrivKPath, "rb") as key_file: #turn it into an RSA object RSAObj = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend()) #use the RSA object to decrypt the concatenated keys concat = RSAObj.decrypt( RSAcipher, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #the first half of the message is the AESKey AESKey = concat[:len(concat) // 2] #The second half is the HMAC key HMACKey = concat[len(concat) // 2:] #first create a tag again using the HMAC key and sha256 to recreate a tag tag2 = hmac.HMAC(HMACKey, hashes.SHA256(), backend=default_backend()) tag2.update(cipher) #check if the tasg are the same try: #Stops the program and "throws cryptography.exceptions.InvalidSignature" if tags aren't the same tag2.verify(tag) #use the AES key to create an AES decryptor AESdecryptor = Cipher(algorithms.AES(AESKey), modes.CBC(iv), backend=default_backend()).decryptor() #get the plain text by decyrpting the cipher message plaintext = AESdecryptor.update(cipher) + AESdecryptor.finalize() #Unpad the plane text to get back the original message from cryptography.hazmat.primitives import padding unpadder = padding.PKCS7(128).unpadder() Pplaintext = unpadder.update(plaintext) Pplaintext += unpadder.finalize() #return the plaintext return Pplaintext #this means the tag was bad and invalid except cryptography.exceptions.InvalidSignature: print("The tag was invalid")
def MyRSAencrypt(filepath, RSA_Publickey_filepath): backend = default_backend() C, IV, EncKey, tag, HMACKey, ext = MyFileEncryptMAC(filepath) cdubd = os.getcwd() with open(RSA_Publickey_filepath, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) RSACipher = public_key.encrypt( EncKey + HMACKey, # concatenated padding.OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return RSACipher, C, IV, ext, tag
def rsaDecryption(certFile, jsonFile): with open(jsonFile) as json_data: data = json.load(json_data) d = json.loads(data) #open JSON file and put it into dictionary json_data.close() asciiCT = d['Key'] #get RSA encrypted key decodedCT = asciiCT.encode('ascii') #ascii to b64 ct = base64.decodestring(decodedCT) # b64 to bytes with open(certFile, "rb") as key_file: # open private certificate from specified file path privateKey = serialization.load_pem_private_key(key_file.read(), password = None, backend = default_backend()) # create privateKey object from pprivate key data key = privateKey.decrypt(ct, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #decrypt key encodedKey = base64.encodestring(key) #bytes to b64 asciiKey = encodedKey.decode('ascii') #b64 to ascii print("Key after decryption:",asciiKey) d['Key'] = asciiKey jsonData = json.dumps(d) # dictionary to json with open(jsonFile, 'w') as outfile: # write to JSON file json.dump(jsonData, outfile)
def encrypter(message, public_key): #Loading RSA Public Key key_file = open(public_key, 'rb') #opens the public key file, read only and binary mode load_public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) public_key = load_public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) #Pads the message padded_message = sym_pad.update(message.encode('utf-8')) padded_message += sym_pad.finalize() #AES Message Encryption aes_key = os.urandom(32) #256-bit Key iv = os.urandom(16) #128-bit IV (16 bytes) #AES-CBC encryptor object aes_encrypt = Cipher( algorithms.AES(aes_key), modes.CBC(iv), backend=default_backend() ).encryptor() ciph_text = aes_encrypt.update(padded_message) + aes_encrypt.finalize() #HMAC Tag Creation hmac_key = os.urandom(32) #256-bit key used for HMAC hmac_tag = hmac.HMAC(hmac_key, hashes.SHA256(), backend=default_backend()) hmac_tag.update(ciph_text) tag = hmac_tag.finalize() #Encrypting AES and HMAC Key using RSA conc_key = aes_key + hmac_key #concatanates keys (512-bit total) ciph_key = load_public_key.encrypt( conc_key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) #Creates JSON output, currently dict object output = {"RSA_cipher": ciph_key, "AES_cipher": ciph_text, "IV": iv, "tag": tag} return output
def MyRSADecrypt(filepath, RSACipher, C, IV, tag, ext, RSA_Privatekey_filepath): #load private key file with open("RSA_Privatekey_filepath", "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) plaintext = private_key.decrypt( RSACipher, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) key_file.close() EncKey = plaintext[0:31] HMACKey = plaintext[32:] message = MyFileDecryptMAC(filepath, HMACKey) return message
def DecryptTest(jsonObject, privateKey): backend = default_backend() #access public key with the path with open(privateKey, "rb") as key_file: objectRSA = serialization.load_pem_private_key(key_file.read(), password=None, backend=backend) #Load private key into RSA object from cryptography.hazmat.primitives.asymmetric import padding concatenate = objectRSA.decrypt( jsonObject['cipherRSA'], padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #Recover AES key and HMAC key AESKey = concatenate[:len(concatenate) // 2] HMACKey = concatenate[len(concatenate) // 2:] #run an HMAC(SHA256 with the HMAC key recovered from above #regenerate a new tag tagUpdate = hmac.HMAC(HMACKey, hashes.SHA256(), backend=backend) tagUpdate.update(jsonObject['cipherAES']) #compare the udpated tag with the original tag(HMACKey) #try catch inserted or else invalid signature error try: #compare the two tags tagUpdate.verify(jsonObject['tag']) AESDecryptCipher = Cipher(algorithms.AES(AESKey), modes.CBC(jsonObject['iv']), backend=backend) AESdecryptor = AESDecryptCipher.decryptor() #plaintext text = AESdecryptor.update( jsonObject['cipherAES']) + AESdecryptor.finalize() from cryptography.hazmat.primitives import padding unpadder = padding.PKCS7(128).unpadder() #recover the plaintext data data = unpadder.update(text) data += unpadder.finalize() return data except cryptography.exceptions.InvalidSignature: print("invalid tag")
def MyRSAdecrypt(filepath, RSACipher, C, IV, ext, RSA_Privatekey_filepath, tag): with open(RSA_Privatekey_filepath, 'rb') as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) key = private_key.decrypt( RSACipher, padding.OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) EncKey = key[:32] HMACKey = key[-32:] m = MydecryptMAC(C, EncKey, IV, tag, HMACKey) #decrypt the message using decrypted key return m
def decrypter(json_object, private_key): key_file = open(private_key, 'rb') #opens file containing RSA private key load_private_key = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend()) private_key = load_private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) #parsed_json = json.loads(json_object) #parsed JSON object #decrypts the concatanated cipher keys that was encrypted using RSA concat_key = load_private_key.decrypt( json_object["RSA_cipher"], padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) aes_key = concat_key[:len(concat_key)//2] #first half of concatanated key hmac_key = concat_key[len(concat_key)//2:] #second half of concataneted key #Generates HMAC tag for integrity check with the HMAC tag created from the ciphertext hmac_tag = hmac.HMAC(hmac_key, hashes.SHA256(), backend=default_backend()) hmac_tag.update(json_object["AES_cipher"]) tag = hmac_tag.finalize() #Integrity check to ensure message wasn't modified if(tag != json_object["tag"]): print("New HMAC Tag:" + str(tag)) print("Old HMAC Tag:" + str(json_object["tag"])) return "failure" else: #decrypts the AES encrypted ciphertext and removes the padding aes_decrypt = Cipher( algorithms.AES(aes_key), modes.CBC(json_object["IV"]), backend=default_backend() ).decryptor() padded_message = aes_decrypt.update(json_object["AES_cipher"]) + aes_decrypt.finalize() #Unpads the message and returns it as plaintext message = sym_unpad.update(padded_message) return (message + sym_unpad.finalize()).decode('utf-8')
def MyRSADecrypt(filepath, RSACipher, C, IV, tag, ext, RSA_Privatekey_filepath): with open(RSA_Privatekey_filepath, 'rb') as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) key = private_key.decrypt( RSACipher, asymmetric, padding.OAEP( mgf=asymmetric.padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) EncKey_start = 0 EncKey_end = int((len(key) / 2)) HMACKey_start = EncKey_end HMACKey_end = int(len(key)) EncKey = key[EncKey_start:HMACKey_end] key_file.close() HMACKey = "" MyFileDecryptMAC(filepath, EncKey, HMACKey, IV, tag)
def rsaEncryption(certFile, jsonFile): with open(certFile, "rb") as key_file: #open public certificate from specified file path publicKey = serialization.load_pem_public_key(key_file.read(),backend = default_backend()) #create publicKey object from public key data key_file.close() with open(jsonFile) as json_data: data = json.load(json_data) d = json.loads(data) #open JSON file and put it into dictionary json_data.close() asciiKey = d['Key'] #get encryption key print("Key before encryption:",asciiKey) decodedKey = asciiKey.encode('ascii') #ascii to b64 key = base64.decodestring(decodedKey) #b64 to bytes ct = publicKey.encrypt(key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #encrypt key encodedCT = base64.encodestring(ct) # byte to base64 asciiCT = encodedCT.decode('ascii') # base64 to ascii so JSON will accept it d['Key'] = asciiCT #update dictionary with encrypted key jsonData = json.dumps(d) # dictionary to json with open(jsonFile, "w") as rewriteFile: json.dump(jsonData, rewriteFile) #write new json data to file rewriteFile.close() print("Key after encryption:",ct)
def encryption(message, public): backend = default_backend() f = open(public, 'rb') # open the public key pem file rsa_public = serialization.load_pem_public_key( f.read(), backend=backend) # import the key to RSA padded_message = padder.update(message.encode('utf-8')) padded_message += padder.finalize() aes_key = os.urandom(32) # generate AES 256-bit key iv = os.urandom(16) # generate the IV cipher = Cipher(algorithms.AES(aes_key), modes.CBC(iv), backend=backend) aes_object = cipher.encryptor() # create AES object ciphertext = aes_object.update(padded_message) + aes_object.finalize( ) # encrypt the message using AES hmac_key = os.urandom(32) #256-bit key used for HMAC hmac_object = hmac.HMAC( hmac_key, hashes.SHA256(), backend=backend) # create HMAC object using HMAC key and SHA256 hmac_object.update(ciphertext) tag = hmac_object.finalize() # create the integrity tag concatenated_key = aes_key + hmac_key # concatenate the keys (AES and HMAC keys) # encrypt the concatenated key rsa_cipher = rsa_public.encrypt( concatenated_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # create a JSON output json_object = { 'RSA_cipher': rsa_cipher, 'AES_cipher': ciphertext, 'IV': iv, 'tag': tag } return json_object
def rsaEncryption(publicKey, jsonFile): with open(jsonFile) as json_data: data = json.load(json_data) d = json.loads(data) #open JSON file and put it into dictionary json_data.close() asciiKey = d['Key'] #get encryption key decodedKey = asciiKey.encode('ascii') #ascii to b64 key = base64.decodestring(decodedKey) #b64 to bytes ct = publicKey.encrypt(key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #encrypt key encodedCT = base64.encodestring(ct) # byte to base64 asciiCT = encodedCT.decode( 'ascii') # base64 to ascii so JSON will accept it d['Key'] = asciiCT #update dictionary with encrypted key jsonData = json.dumps(d) # dictionary to json with open(jsonFile, "w") as rewriteFile: json.dump(jsonData, rewriteFile) #write new json data to file rewriteFile.close() return jsonFile
def decryption(json_object, private): backend = default_backend() f = open(private, 'rb') # open the private key pem file rsa_private = serialization.load_pem_private_key( f.read(), password=None, backend=backend) # import the private key to RSA object # decrypt the RSA cipher concatenate keys concatenated_key = rsa_private.decrypt( json_object['RSA_cipher'], padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # slit the concatenated key into half for AES key and HMAC key aes_key = concatenated_key[:len(concatenated_key) // 2] hmac_key = concatenated_key[len(concatenated_key) // 2:] # recreate the tag to compare with the original tag for integrity hmac_object = hmac.HMAC(hmac_key, hashes.SHA256(), backend=backend) hmac_object.update(json_object['AES_cipher']) tag = hmac_object.finalize() if (tag != json_object['tag']): return "failure" else: # descrypt the message after verify the tag cipher = Cipher(algorithms.AES(aes_key), modes.CBC(json_object['IV']), backend=backend) aes_object = cipher.decryptor() padded_message = aes_object.update( json_object['AES_cipher']) + aes_object.finalize() message = unpadder.update(padded_message) plaintext = (message + unpadder.finalize()).decode('utf-8') return plaintext
def MyRSADecrypt(RSACipher, c, iv, tag, ext, RSA_privatekey_filepath): fh = open(RSA_privatekey_filepath, "rb") # loads private key private_key = serialization.load_pem_private_key(fh.read(), password=None, backend=default_backend()) fh.close() # decrypts "RSACipher" (keys concatenated) key = private_key.decrypt( RSACipher, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # separates concatenation enckey = key[:32] hmackey = key[32:] # saves data into json file jsonFile = dict() jsonFile['c'] = base64.b64encode(c).decode('utf-8') jsonFile['iv'] = base64.b64encode(iv).decode('utf-8') jsonFile['tag'] = base64.b64encode(tag).decode('utf-8') jsonFile['enckey'] = base64.b64encode(enckey).decode('utf-8') jsonFile['hmackey'] = base64.b64encode(hmackey).decode('utf-8') jsonFile['ext'] = base64.b64encode(ext).decode('utf-8') fh = open("files/encryptedRSA.json", "wb") json.dump(jsonFile, fh) fh.close() # decrypts json file to return MyfileDecryptMAC("files/encryptedRSA.json") print('... Finished myrsadecrypt (mac)')
def get_oaep_padding(): from cryptography.hazmat.primitives.asymmetric import padding oaep = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) return oaep
def Encryptor(message, PKPath): #make the primary key into and RSA key object RSAObj = serialization.load_pem_public_key(PKPath.encode(), backend=default_backend()) #generate the key that will be used for AES encryption AESKey = os.urandom(32) #generate the IV that will be used for AES encryption iv = os.urandom(16) #create the AES encryptor using the AESkey, the IV and put it in CBC mode AESencryptor = Cipher(algorithms.AES(AESKey), modes.CBC(iv), backend=default_backend()).encryptor() from cryptography.hazmat.primitives import padding #pad the message to 128 bits using PKCS7 #this padder object will pad the message padder = padding.PKCS7(128).padder() #turn the message into bytes message = message.encode('utf-8') #pad the message Pmessage = padder.update(message) #finalize padding the message Pmessage += padder.finalize() #use the AES encryptor to encyprt the padded message cipher = AESencryptor.update(Pmessage) + AESencryptor.finalize() #generate an HMAC key that will be used to create a tag HMACKey = os.urandom(32) #create the tag using sha256 tag = hmac.HMAC(HMACKey, hashes.SHA256(), backend=default_backend()) tag.update(cipher) t = tag.finalize() #concatenate the 2 keys and then encrypt it using RSA concat = AESKey + HMACKey from cryptography.hazmat.primitives.asymmetric import padding #encyrpt the keys using the RSA object create with the receivers public key RSAcipher = RSAObj.encrypt( concat, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #cryptography turns everything into bytes which dont work in JSON #THe bytes cannot be decoded into string so turn them into ints #this is the integer value of the two encrypted keys with length 256 RSAint = int.from_bytes(RSAcipher, byteorder='big') #we need to save the size of the cipher message because it can change cipherSize = len(cipher) #turn the cipher message to an int cipherInt = int.from_bytes(cipher, byteorder='big') #turn the IV into ints ivInt = int.from_bytes(iv, byteorder='big') #turn the tag into an int tagInt = int.from_bytes(t, byteorder='big') #dump all the data into a json object jsonData = { 'RSAcipher': RSAint, 'cipherSize': cipherSize, 'cipher': cipherInt, 'iv': ivInt, 't': tagInt } return json.dumps(jsonData)
print private_pem from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding import base64 with open("path/to/public_key.pem", "rb") as key_file: public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) message = "your secret message" ciphertext = public_key.encrypt(message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) b64_ciphertext = base64.urlsafe_b64encode(ciphertext) print b64_ciphertext plaintext = private_key.decrypt(ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) print plaintext