中等
技术面试0 次浏览

编写一个Python程序,实现对一个文件的加密和解密功能。要求使用AES算法,密钥长度为128位。

华为安全工程师
Python编程加密算法

答题要点

答题可按照功能实现步骤进行阐述。关键要点:1. 导入必要的库:使用`pycryptodome`库实现AES加密。2. 生成密钥:生成128位的密钥。3. 加密函数:对文件内容进行加密处理。4. 解密函数:对加密后的文件内容进行解密。示例思路:首先导入`pycryptodome`库,然后生成128位的密钥。编写加密函数,将文件内容读取后进行加密,再将加密结果写入新文件。编写解密函数,读取加密文件内容进行解密,将解密结果写入文件。代码示例如下:python from Crypto.Cipher import AES def encrypt_file(key, in_filename, out_filename): cipher = AES.new(key, AES.MODE_EAX) with open(in_filename, 'rb') as infile: data = infile.read() ciphertext, tag = cipher.encrypt_and_digest(data) with open(out_filename, 'wb') as outfile: [outfile.write(x) for x in (cipher.nonce, tag, ciphertext)] def decrypt_file(key, in_filename, out_filename): with open(in_filename, 'rb') as infile: nonce, tag, ciphertext = [infile.read(x) for x in (16, 16, -1)] cipher = AES.new(key, AES.MODE_EAX, nonce) data = cipher.decrypt(ciphertext) try: cipher.verify(tag) with open(out_filename, 'wb') as outfile: outfile.write(data) except ValueError: print('Key incorrect or message corrupted')