Python使用rsa库生成密钥对及加解密签名示例

陆遥
陆遥
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何在Python中利用rsa库生成1024位RSA密钥对,保存为PEM格式文件。示例涵盖使用公钥加密、私钥解密小文本及大文件的方法,并演示基于SHA-1算法的数字签名生成与验证流程,帮助开发者掌握Python中的非对称加密应用。

Python生成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)

此外,感兴趣的用户还可以参考本站提供的其他在线加密解密辅助工具:

在线RSA加密/解密工具: http://tools.jb51.net/password/rsa_encode

文字在线加密解密工具(包含AES、DES、RC4等): http://tools.jb51.net/password/txt_encode

MD5在线加密工具: http://tools.jb51.net/password/CreateMD5Password

在线散列/哈希算法加密工具: http://tools.jb51.net/password/hash_encrypt

在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具: http://tools.jb51.net/password/hash_md5_sha

在线sha1/sha224/sha256/sha384/sha512加密工具: http://tools.jb51.net/password/sha_encode

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表