我使用以下命令使用openssl加密了一个文件
cat input.txt
hello world
openssl aes-256-cbc -pass pass:'00112233445566778899aabbccddeeff' -iv a2a8a78be66075c94ca5be53c8865251 -nosalt -base64 -in input.txt -out output.txt
cat output.txt
pt7DqtAwtTjPbTlzVApucQ==如何使用python包解密文件。我试过下面的方法,但没有用。
>>> from Crypto.Cipher import AES
>>> from base64 import b64decode
>>> with open('output.txt') as f:
... aes = AES.new('00112233445566778899aabbccddeeff', AES.MODE_CBC, IV='a2a8a78be66075c94ca5be53c8865251'.decode('hex'))
... print(aes.decrypt(b64decode(f.read())))
...
L�|�L ��O�*$&9�我需要一种在python中使用openssl 256-cbc加密和解密的方法来加密文件。
发布于 2018-11-18 17:54:22
密码不是钥匙。Openssl使用EVP_BytesToKey从密码和salt创建一个适当的密钥(如果需要的话& IV )。
正如James在评论中提到的,您可以使用-P (或-p)选项告诉Openssl打印密钥(以十六进制表示),然后可以将密钥传递给Crypto.Cipher。或者,您可以用Python实现EVP_BytesToKey,如下所示。这是EVP_BytesToKey的简化版本,不使用salt,count arg的默认值为1。
由于EVP_BytesToKey docs状态,这是一个相当弱的密码派生函数。正如hashlib文档提到的,现代密码派生通常执行数十万次散列以使密码哈希攻击速度非常慢。
我们还需要一个函数来从解密的数据字节中删除PKCS7填充。下面的unpad函数只是假定填充数据是有效的。在实际软件中,unpad函数必须验证填充数据是否有效,以防止基于填充的攻击。我的unpad函数还假定数据已被编码为UTF-8字节,并将未添加的数据解码为文本。
from __future__ import print_function
from Crypto.Cipher import AES
from base64 import b64decode
from hashlib import md5
def evp_simple(data):
out = ''
while len(out) < 32:
out += md5(out + data).digest()
return out[:32]
def unpad(s):
offset = ord(s[-1])
return s[:-offset].decode('utf-8')
iv = 'a2a8a78be66075c94ca5be53c8865251'.decode('hex')
passwd = '00112233445566778899aabbccddeeff'
key = evp_simple(passwd)
print('key', key.encode('hex'))
aes = AES.new(key, AES.MODE_CBC, IV=iv)
data = b64decode('pt7DqtAwtTjPbTlzVApucQ==')
raw = aes.decrypt(data)
print(repr(raw), len(raw))
plain = unpad(raw)
print(repr(plain), len(plain))输出
key b4377f7babf2991b7d6983c4d3e19cd4dd37e31af1c9c689ca22e90e365be18b
'hello world\n\x04\x04\x04\x04' 16
u'hello world\n' 12这段代码不会在Python 3上运行,所以这里有一个Python3版本。
from Crypto.Cipher import AES
from base64 import b64decode
from hashlib import md5
def evp_simple(data):
out = b''
while len(out) < 32:
out += md5(out + data).digest()
return out[:32]
def unpad(s):
offset = s[-1]
return s[:-offset].decode('utf-8')
iv = bytes.fromhex('a2a8a78be66075c94ca5be53c8865251')
passwd = b'00112233445566778899aabbccddeeff'
key = evp_simple(passwd)
aes = AES.new(key, AES.MODE_CBC, IV=iv)
data = b64decode('pt7DqtAwtTjPbTlzVApucQ==')
raw = aes.decrypt(data)
print(repr(raw), len(raw))
plain = unpad(raw)
print(repr(plain), len(plain))输出
b'hello world\n\x04\x04\x04\x04' 16
'hello world\n' 12https://stackoverflow.com/questions/53359064
复制相似问题