大爱

Python实现RSA加密解密方法

2015-12-08

本文主要介绍在Windows+python2.7环境下实现RSA加密解密。

1. 使用M2Crypto

1) 安装M2Crypto

M2Crypto库本身在windows下安装比较麻烦,但这里我们使用大神打包好的安装包^^。

百度网盘地址:http://pan.baidu.com/s/1qXnvi1I

a. 根据你的系统不同下载对应的win32或win64安装包

b. 解压压缩包,进入目录中,使用 python setup.py install 命令安装即可

2) 示例

使用M2Crypto进行RSA加密示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
from M2Crypto import RSA,BIO

rsa = RSA.gen_key(1024, 3, lambda *agr:None)
pub_bio = BIO.MemoryBuffer()
priv_bio = BIO.MemoryBuffer()

rsa.save_pub_key_bio(pub_bio)
rsa.save_key_bio(priv_bio, None)

pub_key = RSA.load_pub_key_bio(pub_bio)
priv_key = RSA.load_key_bio(priv_bio)

message = 'lovesoo.org'

encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)

print encrypted
print decrypted

2. 使用rsa库

1) rsa库安装

pip install rsa

2) 示例

我们可以生成RSA公钥和密钥,也可以load一个.pem文件进来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- 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)
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章