Пример #1
0
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
Пример #2
0
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
Пример #3
0
 def SignKeys(self, client_public_key, server_public_key):
     signature = self.private_key.sign(
         (client_public_key + server_public_key),
         padding.PSS(
             mgf=padding.MGF1(hashes.SHA256()),
             salt_length=padding.PSS.MAX_LENGTH),    hashes.SHA256())
     return signature
Пример #4
0
def encryptAs(pt, pubkey):
    ciphertext = pubkey.encrypt(
        bytes(pt),
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
    return ciphertext
Пример #5
0
def verify_rsa():
    # Read the public key.
    filename = raw_input('Type the PEM file containing the RSA public key: ')
    with open(filename, 'rb') as f:
        pubkey_text = f.read()
        pubkey = serialization.load_pem_public_key(pubkey_text,
                                                   backend=default_backend())

    # Read the file to verify.
    filename = raw_input('Type the file to verify: ')
    with open(filename, 'rb') as f:
        plaintext = f.read()

    # Read the signature.
    filename = raw_input('Type the signature file: ')
    with open(filename, 'rb') as f:
        signature = f.read()

    # Verify the file.
    pubkey.verify(
        signature, plaintext,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

    # If passing here, the verification is ok.
    print 'Signature ok'
Пример #6
0
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)
Пример #7
0
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
Пример #8
0
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
Пример #9
0
def generate_sign(private_key):
    from cryptography.hazmat.primitives.asymmetric import padding

    sign = private_key.sign(
        b'key', padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=128), hashes.SHA256())
    return sign
Пример #10
0
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
Пример #11
0
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
Пример #12
0
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
Пример #13
0
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
Пример #14
0
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
Пример #15
0
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
Пример #16
0
 def sign_private(self, message, hash_using=hashes.SHA256()):
     # if self.priv_key.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) == self.certificate.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo):
     #     logger.info("SAO IGUAIS")
     signature = self.priv_key.sign(
         message.encode(),
         padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                     salt_length=padding.PSS.MAX_LENGTH), hash_using)
     logger.info("Signing with private: %s" % (signature))
     return signature
Пример #17
0
def pk_sign(message: bytes, private_key: rsa.RSAPrivateKey) -> bytes:
    """
    Sign a message using RSASSA-PSS.
    """
    signer = private_key.signer(
        padding.PSS(padding.MGF1(hashes.SHA256()), padding.PSS.MAX_LENGTH),
        hashes.SHA256())
    signer.update(message)
    return signer.finalize()
Пример #18
0
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")
Пример #19
0
def gen_pubKey(privateKey):
    """ RSA PUBLIC KEY """
    chosen_hash = hashes.SHA256()
    hasher = hashes.Hash(chosen_hash, default_backend())
    hasher.update(b"data & ")
    hasher.update(b"more data")
    digest = hasher.finalize()
    sig = privateKey.sign(
        digest,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH),
        utils.Prehashed(chosen_hash))
    publicKey = privateKey.public_key()
    publicKey.verify(
        sig, digest,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH),
        utils.Prehashed(chosen_hash))
    return publicKey
Пример #20
0
def pk_verify(message: bytes, public_key: rsa.RSAPublicKey,
              signature: bytes) -> bool:
    """
    Verify a message signature created with RSASSA-PSS.
    """
    verifier = public_key.verifier(
        signature,
        padding.PSS(padding.MGF1(hashes.SHA256()), padding.PSS.MAX_LENGTH),
        hashes.SHA256())
    verifier.update(message)

    try:
        verifier.verify()
        return True
    except exceptions.InvalidSignature:
        return False
Пример #21
0
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)
Пример #22
0
    def verifySignature(self, signatureClient, client_public_key,
                        server_public_key):
        key_file = open("key_client.pem", "rb")
        pp = key_file.read()
        key_file.close()

        rsa_client_public_key = serialization.load_pem_public_key(
            pp[1874:], backend=default_backend())
        try:
            rsa_client_public_key.verify(
                signatureClient, (client_public_key + server_public_key),
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())

        except InvalidSignature as InvalidSignature:
            print("Assinatura inválida")
            exit
Пример #23
0
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
Пример #24
0
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")
Пример #25
0
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
Пример #26
0
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')
Пример #27
0
    def verifySignature(self, signatureClient, client_public_key,
                        server_public_key, unknown_cert):
        try:
            uc = crypto.load_certificate(crypto.FILETYPE_PEM, unknown_cert)
            store = crypto.X509Store()
            store.add_cert(self.trusted_cert)
            store_ctx = crypto.X509StoreContext(store, uc)
            store_ctx.verify_certificate()

            public_key_cert = x509.load_pem_x509_certificate(
                unknown_cert, default_backend()).public_key()
            public_key_cert.verify(
                signatureClient, (client_public_key + server_public_key),
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())

        except Exception as e:
            print(e)
            exit
Пример #28
0
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)
Пример #29
0
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
Пример #30
0
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