# Python实现RSA无填充加密，兼容BouncyCastle

2018/12/25 14:04

rsa算法其实就是通过这两个参数计算实现公钥加密，所以正常情况下使用常规加密库即可达到目的。

if __name__ == '__main__':
# 实为16进制串，前补0
e = '010001'
# m也需要补00
m = int.from_bytes(bytearray.fromhex(m), byteorder='big')
e = int.from_bytes(bytearray.fromhex(e), byteorder='big')
# js加密为反向，为保持一致原文应反向处理，所以这里原文实际为204dowls
plaintext = 'slwod402'.encode('utf-8')
# 无填充加密逻辑
input_nr = int.from_bytes(plaintext, byteorder='big')
crypted_nr = pow(input_nr, e, m)
keylength = math.ceil(m.bit_length() / 8)
crypted_data = crypted_nr.to_bytes(keylength, byteorder='big')
print(crypted_data.hex())
# 72ff82c8f227ba9cf429635b89291b2d7ef54bcf8635af432b9917bd3593d8d8aa0c186764cef86c8530d349db6132521a9c70af939a0242bb3d01ce7094cf91f3a058742fc680d70b17c4441ebf60fd4f92bce660e4785fe56d85ac7f7023f4ccf702c247f37b36a255dc04d9ce14745f422c6113290ff9b479494fd805557e

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes

if __name__ == "__main__":
m = int.from_bytes(bytearray.fromhex(m), byteorder='big')
e = int.from_bytes(bytearray.fromhex(e), byteorder='big')
key = rsa.RSAPublicNumbers(e, m).public_key(default_backend())
pem = key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('key.pem', 'w+') as f:
f.writelines(pem.decode())

Java-web中利用RSA进行加密解密操作的方法示例

Java 进行 RSA 加解密时不得不考虑到的那些事儿

https://github.com/pyca/cryptography/issues/2735

0
0 收藏

0 评论
0 收藏
0