Python使用Rsa加密
生成公私钥
当然也可以用Rsa模块来生成,不过还是使用openssl吧。
生成一个1024bit的私钥,便于试验,私钥要妥善保管:
openssl genrsa -out private.key 1024
由私钥生成公钥:
openssl rsa -in private.key -pubout -out public.key
你可以使用cat
来查看你的私钥或公钥,他应该由如下格式组成:
//私钥
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDhlMzeKVyiyZHVH5a40o......
-----END RSA PRIVATE KEY-----
//公钥
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ......
-----END PUBLIC KEY-----
Python下
Python2.7环境:
#coding=utf-8
import rsa
import base64
#简单的封装一下
def readfile(filename):
f = open(filename,'r')
buf = f.read()
f.close()
return buf
def loadkey(private_key,public_key): #加载私钥公钥
pri = rsa.PrivateKey.load_pkcs1(private_key.encode())
pub = rsa.PublicKey.load_pkcs1(public_key.encode())
return pri,pub
def rsa_encrypt(public_key,message): #使用公钥加密,加密后返回的是二进制流,所以用base64模块转成字符串
return base64.b64encode(rsa.encrypt(message.encode(),public_key))
def rsa_decrypt(private_key,message): #私钥解密,用base64模块转回二进制流解密
return rsa.decrypt(base64.b64decode(message),private_key).decode()
if __name__ == '__main__':
private_key,public_key = loadkey(readfile('private.key'),readfile('public.key'))
message = 'test'
encrypt_text = rsa_encrypt(public_key,message)
print encrypt_text
print rsa_decrypt(private_key,encrypt_text)
返回如下:
HXowzHMPD5vJ4CcAbCoQT1COUnnjqC4w6lu7UH255myj1CZFrCobBDCmDuNRRBxhmOS21SObDt5x5vAaJJcT4WexRNrA0pp3cem+73ea0TD0hH1CoETHo+NxOX0TS2/+sJG0/w8OY1MsXS43RhEt2iUWcUKpbzEI/aBu8T6kzdo=
test