python利用公私钥加解密

小贴士
这里不再赘述公私钥的生成过程。可以利用OpenSSL进行生成。
加密代码
#!/usr/bin/python#加密 #conda install pycrypto#提前安装模块import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5publickey = RSA.importKey(open('public_key.pem').read()) enc = PKCS1_v1_5.new(publickey) ciphertext = enc.encrypt("3160610019")#加密字符串with open("crypt.txt", 'w') as f:#加密后保存在此文件中 f.write(base64.encodestring(ciphertext))


解密代码
#!/usr/bin/pythonfrom Crypto import Random import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5key = RSA.importKey(open('server.key').read()) dec = PKCS1_v1_5.new(key)with open('crypt.txt', 'r') as f:#读取密文 ciphertext = f.read() ciphertext = base64.decodestring(ciphertext)print dec.decrypt(ciphertext, Random.new().read)

注意:密钥最好不要设置密码哦。
【python利用公私钥加解密】






    推荐阅读