Python使用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=https://www.it610.com/article/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代码 【Python使用Rsa公钥加密,私钥解密以及私钥签名,公钥验签的例子】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')
+

    推荐阅读