Python生成rsa密钥对操作示例

yipeiwu_com5年前Python基础

本文实例讲述了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加密/解密工具:
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的Django框架结合jQuery实现AJAX购物车页面

使用Python的Django框架结合jQuery实现AJAX购物车页面

Django中集成jquery 首先,静态的资源通常放入static文件夹中: static/ css/ djquery.css samples/...

对Python3中的input函数详解

对Python3中的input函数详解

下面介绍python3中的input函数及其在python2及pyhton3中的不同。 python3中的ininput函数,首先利用help(input)函数查看函数信息: 以上信息...

Python 连连看连接算法

功能:为连连看游戏提供连接算法 说明:模块中包含一个Point类,该类是游戏的基本单元“点”,该类包含属性:x,y,value。 其中x,y代表了该点的坐标,value代表该点的特征:0...

python 下 CMake 安装配置 OPENCV 4.1.1的方法

python 下 CMake 安装配置 OPENCV 4.1.1的方法

CMake 安装配置 OPENCV 4.1.1 解决各种问题 方法一 python 可以直接pip install opencv-contrib-python==3.4.x.x 安装,老...

利用Python在一个文件的头部插入数据的实例

在一个文件的末尾追加数据是很常用的。在使用过程中应该都比较熟悉不会出现什么错误。但是往一个文件头部插入数据可能或多或少会碰到一些问题。 看似正确的错误代码 很多代码看似正确,但是其实都是...