openssl enc -e -aes-256-cbc -k passwd加密的文件,如何用python解密
- User
openssl enc -e -aes-256-cbc -k passwd加密的文件,如何用python解密
- Assistant
可以使用pycryptodome或cryptography库在Python中解密openssl enc工具加密的文件。
使用pycryptodome解密文件:
from Crypto.Cipher import AES KEY = b'passwd' # 加密时使用的密码 IV = b'0000000000000000' # 初始向量,与加密时使用的一致 BLOCK_SIZE = 16 # 分块大小 with open('encrypted_file.txt', 'rb') as f: cipher_text = f.read() cipher = AES.new(KEY, AES.MODE_CBC, IV) plain_text = cipher.decrypt(cipher_text) # 去掉填充部分 padding_size = plain_text[-1] plain_text = plain_text[:-padding_size] with open('decrypted_file.txt', 'wb') as f: f.write(plain_text)使用cryptography解密文件:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend KEY = b'passwd' # 加密时使用的密码 IV = b'0000000000000000' # 初始向量,与加密时使用的一致 BLOCK_SIZE = 16 # 分块大小 with open('encrypted_file.txt', 'rb') as f: cipher_text = f.read() backend = default_backend() cipher = Cipher(algorithms.AES(KEY), modes.CBC(IV), backend=backend) decryptor = cipher.decryptor() plain_text = decryptor.update(cipher_text) + decryptor.finalize() # 去掉填充部分 padding_size = plain_text[-1] plain_text = plain_text[:-padding_size] with open('decrypted_file.txt', 'wb') as f: f.write(plain_text) - User
上文中的初始向量对应的是openssl enc的那个参数
- Assistant
是的,上文中的初始向量(IV)对应的是openssl enc的
-iv参数。在使用 openssl enc 进行加密时,如果不指定-iv参数,会使用默认的全 0 的初始向量。因此,如果在 Python 中使用相同的密码和初始向量解密 openssl enc 加密的文件,也要确保使用了正确的初始向量。 - User
openssl enc -e -aes-256-cbc -k passwd加密的文件,如何用python2标准库解密
- Assistant
Python 2标准库中没有提供AES CBC模式的加解密支持,因此无法直接使用标准库进行解密。
不过,可以通过使用pycrypto库在Python 2中解密openssl enc工具加密的文件。以下是使用pycrypto库进行解密的示例代码:
from Crypto.Cipher import AES KEY = b'passwd' # 加密时使用的密码 IV = b'0000000000000000' # 初始向量,与加密时使用的一致 BLOCK_SIZE = 16 # 分块大小 with open('encrypted_file.txt', 'rb') as f: cipher_text = f.read() cipher = AES.new(KEY, AES.MODE_CBC, IV) plain_text = cipher.decrypt(cipher_text) # 去掉填充部分 padding_size = ord(plain_text[-1]) plain_text = plain_text[:-padding_size] with open('decrypted_file.txt', 'wb') as f: f.write(plain_text)在Python 2中,需要使用
ord()函数将字符转换为对应的ASCII码值。此外,Python 2中的字符串是以字节为单位而非Unicode字符,因此可以直接使用字节串进行加解密。 - User
使用python的Crypto,报错Incorrect AES length是什么意思
- Assistant
Incorrect AES length意味着密钥长度不正确,无法进行加密或解密。在AES-CBC模式中,密钥长度应该是16、24或32字节。如果使用了不合法的密钥长度,则会导致
Incorrect AES length错误。另外,如果使用的是其他的AES加密模式,可能需要遵循不同的密钥长度规则,需要参考具体的加密算法规范。如果您遇到了
Incorrect AES length错误,请确保使用了正确长度的密钥并检查代码中其他可能导致此错误的因素,例如编码、填充等。