转载自:http://blog.csdn.net/nyist327/article/details/48352253
安装Cryptor库
wget https://github.com/dlitz/pycrypto/archive/master.zip
python setup.py install
生成rsa公钥和私钥
私钥
openssl genrsa -out ./myPrivateKey.pem -passout pass:"f00bar" -des3 2048
用私钥生成公钥
openssl rsa -pubout -in ./myPrivateKey.pem -passin pass:"f00bar" -out ./myPublicKey.pem
Rsa公钥加密,私钥解密的Python代码
encrypto.py
#!/usr/bin/python
from Crypto.PublicKey import RSA
def encrypt(message):
externKey="./myPublicKey.pem"
privatekey = open(externKey, "r")
encryptor = RSA.importKey(privatekey, passphrase="f00bar")
encriptedData=encryptor.encrypt(message, 0)
file = open("./cryptThingy.txt", "wb")
file.write(encriptedData[0])
file.close()
if __name__ == "__main__":
encryptedThingy=encrypt("Loren ipsum")
decrypto.py
#!/usr/bin/python
from Crypto.PublicKey import RSA
def decrypt():
externKey="./myPrivateKey.pem"
publickey = open(externKey, "r")
decryptor = RSA.importKey(publickey, passphrase="f00bar")
retval=None
file = open("./cryptThingy.txt", "rb")
retval = decryptor.decrypt(file.read())
file.close()
return retval
if __name__ == "__main__":
decryptedThingy=decrypt()
print "Decrypted: %s" % decryptedThingy
Rsa私钥签名,公钥验签的Python代码
sign.py
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64encode
def rsa_sign(message):
private_key_file = open('./myPrivateKey.pem', 'r')
private_key = RSA.importKey(private_key_file)
hash_obj = SHA.new(message)
signer = PKCS1_v1_5.new(private_key)
d = b64encode(signer.sign(hash_obj))
file = open('./signThing.txt', 'wb')
file.write(d)
file.close()
if '__main__' == __name__:
rsa_sign('zhangshibo')
verify.py
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from base64 import b64decode
def rsa_verify(message):
public_key_file = open('./myPublicKey.pem', 'r')
public_key = RSA.importKey(public_key_file)
sign_file = open('./signThing.txt', 'r')
sign = b64decode(sign_file.read())
h = SHA.new(message)
verifier = PKCS1_v1_5.new(public_key)
return verifier.verify(h, sign)
if '__main__' == __name__:
print rsa_verify('zhangshibo')