Python解决RSA加密
最近爬个网站需要用发现密码是通过RSA加密的,因此找网上python加密例子,发现都没有一个比较完整的demo
so,自己写一个吧~
首先,安装相应的库:
1. pyCrypto : pip install pyCrypto
2.pycryptodome: pip install pycryptodome
ps:安装的pyCrypto是会自动安装Crypto的,然后你的C是小写的,手动改成大写~
然后就没啥好讲的了,贴上代码:(注意事项在底下说)
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcsl_v1_5
import base64
msg = 'm123456'
public_key = '''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2GdFVfnjmqWNfN3m2Hml4pMcm
o66ltA2NHiG0DWuEs2XWVaNL8dAc6/Z/qA2nBXfKg/W/nEzJr6bbSm3oxlGm+AOA
Ennra+YPnS1ocoMbXwM1JUwjH5GbO93xfSDBGvOUE7c30zVkRkasN0vzG0WnoSTR
ErSrz0laLtVq1a980wIDAQAB
-----END PUBLIC KEY-----
'''
a = bytes(msg, encoding="utf8")
rsakey = RSA.importKey(public_key)
cipher = Cipher_pkcsl_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(a))
print(cipher_text)
注意事项:1. pulic_key格式一定不能错,必须!!!一定!!!一定要按照上边那个格式,换行也不行!!!
2. 要加密的明文必须得转为字节类型哇。