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

来源:互联网 发布:全球秒杀 淘宝u站 编辑:程序博客网 时间:2024/06/05 17:17

项目合作需要,和其他网站通信,消息内容采用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 message32 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

用法差不多一致。load密钥的方式也有好几种。 二、跨平台密钥不统一 RSA加密验证搞定了,但是和java平台交互的时候出问题,java生成的密钥用Python根本load不了,更别说加密了,反之Java也load不了Python生成的密钥。 上网查找原因,RSA认真流程肯定没有问题,关键是不同平台执行RSA的标准有些偏差。



安装Cryptor库

wget https://github.com/dlitz/pycrypto/archive/master.zip 
Python setup.py install

生成rsa公钥和私钥

  1. 私钥
  2. openssl genrsa -out ./myPrivateKey.pem -passout pass:"f00bar" -des3 2048
  3. 用私钥生成公钥
  4. openssl rsa -pubout -in ./myPrivateKey.pem -passin pass:"f00bar" -out ./myPublicKey.pem

Rsa公钥加密,私钥解密的Python代码


encrypto.py

  1. #!/usr/bin/python
  2. from Crypto.PublicKey import RSA
  3. def encrypt(message):
  4. externKey="./myPublicKey.pem"
  5. privatekey = open(externKey, "r")
  6. encryptor = RSA.importKey(privatekey, passphrase="f00bar")
  7. encriptedData=encryptor.encrypt(message, 0)
  8. file = open("./cryptThingy.txt", "wb")
  9. file.write(encriptedData[0])
  10. file.close()
  11. if __name__ == "__main__":
  12. encryptedThingy=encrypt("Loren ipsum")

decrypto.py

  1. #!/usr/bin/python
  2. from Crypto.PublicKey import RSA
  3. def decrypt():
  4. externKey="./myPrivateKey.pem"
  5. publickey = open(externKey, "r")
  6. decryptor = RSA.importKey(publickey, passphrase="f00bar")
  7. retval=None
  8. file = open("./cryptThingy.txt", "rb")
  9. retval = decryptor.decrypt(file.read())
  10. file.close()
  11. return retval
  12. if __name__ == "__main__":
  13. decryptedThingy=decrypt()
  14. print "Decrypted: %s" % decryptedThingy

Rsa私钥签名,公钥验签的Python代码


sign.py

  1. from Crypto.PublicKey import RSA
  2. from Crypto.Hash import SHA
  3. from Crypto.Signature import PKCS1_v1_5
  4. from base64 import b64encode
  5. def rsa_sign(message):
  6. private_key_file = open('./myPrivateKey.pem', 'r')
  7. private_key = RSA.importKey(private_key_file)
  8. hash_obj = SHA.new(message)
  9. signer = PKCS1_v1_5.new(private_key)
  10. d = b64encode(signer.sign(hash_obj))
  11. file = open('./signThing.txt', 'wb')
  12. file.write(d)
  13. file.close()
  14. if '__main__' == __name__:
  15. rsa_sign('zhangshibo')

verify.py

  1. from Crypto.PublicKey import RSA
  2. from Crypto.Signature import PKCS1_v1_5
  3. from Crypto.Hash import SHA
  4. from base64 import b64decode
  5. def rsa_verify(message):
  6. public_key_file = open('./myPublicKey.pem', 'r')
  7. public_key = RSA.importKey(public_key_file)
  8. sign_file = open('./signThing.txt', 'r')
  9. sign = b64decode(sign_file.read())
  10. h = SHA.new(message)
  11. verifier = PKCS1_v1_5.new(public_key)
  12. return verifier.verify(h, sign)
  13. if '__main__' == __name__:
  14. print rsa_verify('zhangshibo')



阅读全文
1 0
原创粉丝点击