首页 > 编程知识 正文

Python加密文件的实现方式

时间:2023-11-22 15:28:11 阅读:289261 作者:NJFH

Python加密文件是人们保护个人文件或隐私信息的常见方式,本文将从多个方面介绍Python加密文件的实现方式。

一、使用AES加密算法

AES算法是一种广泛使用的对称加密算法,它支持128、192和256位加密密钥长度,安全性很高。Python的crypto包中已经集成了AES加密算法,根据需求进行使用即可。

    from Crypto.Cipher import AES
    import hashlib

    block_size = 16
    padding_value = b''
    key = hashlib.sha256("my_secret_key".encode()).digest()
    iv = hashlib.md5("my_secret_iv".encode()).digest()[:16]

    def pad(s):
        return s + (block_size - len(s) % block_size) * padding_value

    def encrypt(plaintext):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        padded_plaintext = pad(plaintext)
        ciphertext = cipher.encrypt(padded_plaintext)
        return ciphertext

    def decrypt(ciphertext):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        padded_plaintext = cipher.decrypt(ciphertext)
        plaintext = padded_plaintext.rstrip(padding_value)
        return plaintext

以上代码中,我们指定了使用AES算法加密,对于密钥和初始向量我们使用了哈希算法进行了处理,此外,我们也加入了padding来保证数据长度为16的倍数。

二、使用RSA加密算法

RSA算法是一种非对称加密算法,它具有加密速度慢、安全性高的特点。将RSA算法应用到Python加密文件当中,我们需要用到RSA算法的秘钥和公钥,详细步骤如下:

    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    import binascii

    def generate_key_pairs():
        key = RSA.generate(2048)
        private_key = key.export_key() # 私钥
        public_key = key.publickey().export_key() # 公钥
        return private_key, public_key

    def encrypt_RSA(public_key, message):
        rsa_key = RSA.import_key(public_key)
        rsa_cipher = PKCS1_OAEP.new(rsa_key)
        encrypted_message = rsa_cipher.encrypt(message)
        return binascii.hexlify(encrypted_message)

    def decrypt_RSA(private_key, encrypted_message):
        rsa_key = RSA.import_key(private_key)
        rsa_cipher = PKCS1_OAEP.new(rsa_key)
        decrypted_message = rsa_cipher.decrypt(binascii.unhexlify(encrypted_message))
        return decrypted_message

以上代码中,我们首先生成了一对秘钥和公钥,通过export_key()进行输出。对于RSA算法,我们使用了PKCS1_OAEP算法进行加密和解密,使用了binascii将二进制流转换为16进制字符串。

三、使用Hash算法

Hash算法是一种将任意长度的消息压缩为固定长度输出的算法,最常见的Hash算法包括MD5、SHA-1、SHA-256等。通过对文件进行Hash加密,我们可以检查文件是否被篡改过。

    import hashlib

    def generate_md5(file_path):
        hash_md5 = hashlib.md5()
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()

    def generate_sha256(file_path):
        hash_sha256 = hashlib.sha256()
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_sha256.update(chunk)
        return hash_sha256.hexdigest()

以上代码中,我们使用了MD5和SHA-256两种Hash算法分别进行加密,使用了hashlib库对文件进行读取和hash处理,最后输出hash值。

四、使用PyCryptoDome库实现加密

PyCryptoDome是Python的一个加密库,它支持多种对称、非对称加密算法,能够用于多种场合下的加密、签名、验证等操作。下面是使用PyCryptoDome库进行文件加密和解密的示例:

    from Crypto.Cipher import AES

    def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
        if not out_filename:
            out_filename = in_filename + '.enc'
        iv = b'' * 16
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        filesize = os.path.getsize(in_filename)

        with open(in_filename, 'rb') as infile:
            with open(out_filename, 'wb') as outfile:
                outfile.write(struct.pack('

以上代码中,我们使用了AES算法对文件进行加密和解密,其中encrypt_file()函数为加密函数,decrypt_file()函数为解密函数,可以直接使用。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。