分享

python下RSA加密解密以及跨平台问题

 xenophobe 2014-12-05

项目合作需要,和其他网站通信,消息内容采用RSA加密方式传递。之前没有接触过RSA,于是两个问题出现了:

声明: 环境WIN 7 + python 2.6.6 RSA格式:PEM

一、Python下RSA加密解密怎么做? 现在网上搜索关于RSA的信息,然后看一下Python下是怎么做的。

找到两种方法:

1、使用rsa库 安装

pip install rsa

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

复制代码
 1 # -*- coding: utf-8 -*-
 2 __author__ = 'luchanghong'
 3 import rsa
 4 
 5 # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
 6 (pubkey, privkey) = rsa.newkeys(1024)
 7 
 8 pub = pubkey.save_pkcs1()
 9 pubfile = open('public.pem','w+')
10 pubfile.write(pub)
11 pubfile.close()
12 
13 pri = privkey.save_pkcs1()
14 prifile = open('private.pem','w+')
15 prifile.write(pri)
16 prifile.close()
17 
18 # load公钥和密钥
19 message = 'hello'
20 with open('public.pem') as publickfile:
21     p = publickfile.read()
22     pubkey = rsa.PublicKey.load_pkcs1(p)
23 
24 with open('private.pem') as privatefile:
25     p = privatefile.read()
26     privkey = rsa.PrivateKey.load_pkcs1(p)
27 
28 # 用公钥加密、再用私钥解密
29 crypto = rsa.encrypt(message, pubkey)
30 message = rsa.decrypt(crypto, privkey)
31 print message
32 
33 # sign 用私钥签名认真、再用公钥验证签名
34 signature = rsa.sign(message, privkey, 'SHA-1')
35 rsa.verify('hello', signature, pubkey)
复制代码

 

2、使用M2Crypto python关于RSA的库还是蛮多的,当然也可以直接用openSSL。M2Crypto安装的时候比较麻烦,虽然官网有exe的安装文件,但是2.6的有bug,建议使用0.19.1版本,最新的0.21.1有问题。

复制代码
 1 # -*- coding: utf-8 -*-
 2 __author__ = 'luchanghong'
 3 from M2Crypto import RSA,BIO
 4 
 5 rsa = RSA.gen_key(1024, 3, lambda *agr:None)
 6 pub_bio = BIO.MemoryBuffer()
 7 priv_bio = BIO.MemoryBuffer()
 8 
 9 rsa.save_pub_key_bio(pub_bio)
10 rsa.save_key_bio(priv_bio, None)
11 
12 pub_key = RSA.load_pub_key_bio(pub_bio)
13 priv_key = RSA.load_key_bio(priv_bio)
14 
15 message = 'i am luchanghong'
16 
17 encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
18 decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)
19 
20 print decrypted
复制代码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多