Python生成rsa密钥对操作示例
程序员文章站
2023-11-23 19:19:52
本文实例讲述了python生成rsa密钥对操作。分享给大家供大家参考,具体如下:
# -*- coding: utf-8 -*-
import rsa
# 先...
本文实例讲述了python生成rsa密钥对操作。分享给大家供大家参考,具体如下:
# -*- coding: utf-8 -*- import rsa # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用 (pubkey, privkey) = rsa.newkeys(1024) pub = pubkey.save_pkcs1() pubfile = open('public.pem','w+') pubfile.write(pub) pubfile.close() pri = privkey.save_pkcs1() prifile = open('private.pem','w+') prifile.write(pri) prifile.close() # load公钥和密钥 message = 'lovesoo.org' with open('public.pem') as publickfile: p = publickfile.read() pubkey = rsa.publickey.load_pkcs1(p) with open('private.pem') as privatefile: p = privatefile.read() privkey = rsa.privatekey.load_pkcs1(p) # 用公钥加密、再用私钥解密 crypto = rsa.encrypt(message, pubkey) message = rsa.decrypt(crypto, privkey) print message # sign 用私钥签名认证、再用公钥验证签名 signature = rsa.sign(message, privkey, 'sha-1') rsa.verify('lovesoo.org', signature, pubkey)
对文件进行rsa加密解密
from rsa.bigfile import * import rsa with open('public.pem') as publickfile: p = publickfile.read() pubkey = rsa.publickey.load_pkcs1(p) with open('private.pem') as privatefile: p = privatefile.read() privkey = rsa.privatekey.load_pkcs1(p) with open('mysec.txt', 'rb') as infile, open('outputfile', 'wb') as outfile: #加密输出 encrypt_bigfile(infile, outfile, pubkey) with open('outputfile', 'rb') as infile2, open('result', 'wb') as outfile2: #解密输出 decrypt_bigfile(infile2, outfile2, privkey)
ps:关于加密解密感兴趣的朋友还可以参考本站在线工具:
在线rsa加密/解密工具:
文字在线加密解密工具(包含aes、des、rc4等):
md5在线加密工具:
http://tools.jb51.net/password/createmd5password
在线散列/哈希算法加密工具:
在线md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160加密工具:
在线sha1/sha224/sha256/sha384/sha512加密工具:
更多关于python相关内容感兴趣的读者可查看本站专题:《python加密解密算法与技巧总结》、《python编码操作技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程》
希望本文所述对大家python程序设计有所帮助。
下一篇: 关键词如何定位及策略