欢迎访问宙启技术站
智能推送

使用Python实现MODE_ECB模式的文件加密与解密

发布时间:2024-01-04 08:31:10

ECB模式(Electronic Codebook)是一种常用的分组密码模式,它将明文分成固定长度的块,并使用相同的密钥对每个块进行加密。下面是使用Python实现ECB模式的文件加密与解密的示例代码:

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

def encrypt_file(input_filename, output_filename, key):
    cipher = AES.new(key, AES.MODE_ECB)
    with open(input_filename, 'rb') as f:
        plaintext = f.read()
    padded_plaintext = pad(plaintext, AES.block_size)
    ciphertext = cipher.encrypt(padded_plaintext)
    with open(output_filename, 'wb') as f:
        f.write(ciphertext)

def decrypt_file(input_filename, output_filename, key):
    cipher = AES.new(key, AES.MODE_ECB)
    with open(input_filename, 'rb') as f:
        ciphertext = f.read()
    padded_plaintext = cipher.decrypt(ciphertext)
    plaintext = unpad(padded_plaintext, AES.block_size)
    with open(output_filename, 'wb') as f:
        f.write(plaintext)

上述代码使用了pycryptodome库中的AESUtil.Padding模块来进行加密和解密操作。encrypt_file函数接受输入文件名、输出文件名和密钥作为输入参数,将输入文件内容加密后写入输出文件。decrypt_file函数接受输入文件名、输出文件名和密钥作为输入参数,将输入文件内容解密后写入输出文件。

下面是使用上述函数进行加密和解密的示例代码:

input_file = 'plaintext.txt'
encrypted_file = 'encrypted.txt'
decrypted_file = 'decrypted.txt'
key = b'This is a 16-byte key'

# 加密文件
encrypt_file(input_file, encrypted_file, key)
print('文件加密完成')

# 解密文件
decrypt_file(encrypted_file, decrypted_file, key)
print('文件解密完成')

运行上述代码后,会在当前目录下生成加密后的文件encrypted.txt和解密后的文件decrypted.txt。请将input_file替换为需要加密的文件路径,key替换为使用的密钥。

需要注意的是,ECB模式存在安全性问题,相同的明文块会被加密成相同的密文块。因此,使用ECB模式时需要注意密钥的生成和管理,以及对明文的切分方法。在实际应用中,更推荐使用更安全的分组密码模式,如CBC(Cipher Block Chaining)模式。