python实现RSA加密解密方法
1 安装rsa 2 python -m pip install rsa
我们可以生成RSA公钥和密钥,也可以load一个.pem文件进来
1 # -*- coding: utf-8 -*- 2 import rsa 3 4 # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用 5 (pubkey, privkey) = rsa.newkeys(1024) 6 7 pub = pubkey.save_pkcs1() 8 pubfile = open('public.pem','w+') 9 pubfile.write(pub) 10 pubfile.close() 11 12 pri = privkey.save_pkcs1() 13 prifile = open('private.pem','w+') 14 prifile.write(pri) 15 prifile.close() 16 17 # load公钥和密钥 18 message = 'lovesoo.org' 19 with open('public.pem') as publickfile: 20 p = publickfile.read() 21 pubkey = rsa.PublicKey.load_pkcs1(p) 22 23 with open('private.pem') as privatefile: 24 p = privatefile.read() 25 privkey = rsa.PrivateKey.load_pkcs1(p) 26 27 # 用公钥加密、再用私钥解密 28 crypto = rsa.encrypt(message, pubkey) 29 message = rsa.decrypt(crypto, privkey) 30 print message 31 32 # sign 用私钥签名认证、再用公钥验证签名 33 signature = rsa.sign(message, privkey, 'SHA-1') 34 rsa.verify('lovesoo.org', signature, pubkey)
持续更新
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步