今天碰到一个对接 Java rsa pkcs1 用公钥解密,

2021-06-11 21:20:37 +08:00
 chenqh

python 我搜了好久,都是用私钥解密的, 论坛里的大佬有给个资料的吗?

我实在搜不到了

2963 次点击
所在节点    Python
21 条回复
chenqh
2021-06-15 20:33:11 +08:00
@among


```
import M2Crypto
from tornado import escape
import base64
"""
sudo yum install -y python3-devel openssl-devel swig
pip install M2Crypto
"""

def handle_key_inner(key, start, end):
result = ''
# 分割 key,每 64 位长度换一行
divide = int(len(key) / 64)
divide = divide if (divide > 0) else divide + 1
line = divide if (len(key) % 64 == 0) else divide + 1
for i in range(line):
result += key[i * 64:(i + 1) * 64] + '\n'
result = start + result + end
return result


def handle_pub_key(key):
"""
处理公钥
公钥格式 pem,处理成以-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾的格式
:param key:pem 格式的公钥,无-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾
:return:
"""
start = '-----BEGIN PUBLIC KEY-----\n'
end = '-----END PUBLIC KEY-----'
return handle_key_inner(key, start, end)


def handle_pri_key(key):
start = '-----BEGIN PRIVATE KEY-----\n'
end = '-----END PRIVATE KEY-----'
return handle_key_inner(key, start, end)


def util_rsa_encrypt_with_private_key_str(msg: bytes, private_key_str: str, blocksize=117):
private_key_str = "".join([e.strip() for e in private_key_str.splitlines()])
private_key_str = handle_pri_key(private_key_str)
bio = M2Crypto.BIO.MemoryBuffer(private_key_str.encode("utf-8"))
rsa_pri = M2Crypto.RSA.load_key_bio(bio)
out_li = []
len_msg = len(msg)
for i in range(0, len_msg, blocksize):
piece = msg[i:i + blocksize]
ctxt_pri = rsa_pri.private_encrypt(piece, M2Crypto.RSA.pkcs1_padding) # 这里的方法选择加密填充方式,所以在解密的时候 要对应。
out_li.append(ctxt_pri)
raw_msg = b''.join(out_li)
return base64.b64encode(raw_msg)


def pub_decrypt_with_pubkeyfile(msg, file_name):
rsa_pub = M2Crypto.RSA.load_pub_key(file_name)
pub_decrypt(msg, rsa_pub)


def util_rsa_decrypt_with_public_key_str(msg, pub_key: str):
"""
Args:
msg: base64 string
"""
pub_key = "".join([e.strip() for e in pub_key.splitlines()])
pub_key = handle_pub_key(pub_key)
msg = escape.utf8(msg)
bio = M2Crypto.BIO.MemoryBuffer(pub_key.encode("utf-8"))
rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)
return pub_decrypt(msg, rsa_pub)


def pub_decrypt(msg, rsa_pub, block_size=128):

ctxt_pri = base64.b64decode(msg) # 先将 str 转成 base64
# maxlength = 128
li = []
len_ctxt = len(ctxt_pri)
for i in range(0, len_ctxt, block_size):
input = ctxt_pri[i:i + block_size]
out = rsa_pub.public_decrypt(input, M2Crypto.RSA.pkcs1_padding) # 解密
li.append(out)
return b''.join(li)

```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/783006

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX