曹耘豪的博客

Python使用OpenSSL解密

  1. 安装cryptography包
  2. 解密代码实现
  3. 参考

安装cryptography包

1
pip install cryptography -i https://pypi.douban.com/simple

解密代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding


def decrypt(data, private_key_data):
'''
:param data : 待解密的字节数组
:param private_key_data: 私钥字节数组
'''

private_key = serialization.load_pem_private_key(
private_key_data,
password = None
)

return private_key.decrypt(
data,
padding.OAEP( # 与加密时用的方式一致,否则会解密失败
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)

# 测试代码
if __name__ == '__main__':
data = bytes.fromhex('8e0f057eb288fc8')

with open('./private.key', 'rb') as f:
private_key_data = f.read()

res = decrypt(data, private_key_data)

print(res.decode('utf-8'))

参考

   /