python crypto rsa 加密运用

首先安装必须包,pycrypto..

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5 #生成对象

然后定义一个生成公私钥的函数:

 def getRSAKeys(self,keyLength):
        '''keylength 指定长度 如:1024,2048'''
        private = RSA.generate(keyLength)
        public  = private.publickey()
        privateKey = private.exportKey()
        publicKey = public.exportKey()
        return privateKey, publicKey #生成一对公私钥匙

定义加密函数:

def rsaPubEncrypt(pubKey, data, length=200): 
    '''按照生成公私钥匙长度定义length,1024 length = 100,2048 length = 200'''
    publicKey = RSA.importKey(pubKey)
    cipher = PKCS1_v1_5.new(publicKey)  #
    data = json.dumps(data) # 看情况
    #encryptedData = cipher.encrypt(data)  一般加密
    encryptedData = []  # 长字符串加密
    for i in range(0, len(data), length):
        encryptedData.append(cipher.encrypt(data[i:i + length]))
    print encryptedData
    return "".join(encryptedData)
    # return encryptedData    一般加密返回

定义解密函数:

def rsaPrivateDecrypt(privKey, data,length=256):  # 解密
    '''解密length 根据加密length 100 对应128 200 对应 256'''
    privateKey = RSA.importKey(privKey)
    cipher = PKCS1_v1_5.new(privateKey)
    decryptedData = []
    for i in range(0, len(data), length):
        json_data = data[i:i + length]
        len_da = len(json_data)
        json_data = cipher.decrypt(json_data,'xyz')
        decryptedData.append(json_data)
    data = ''.join(decryptedData)
    return data
#对于长字符串加解密
def
rsa_long_encrypt(pub_key_str, msg, length=100): """ 单次加密串的长度最大为 (key_size/8)-11 1024bit的证书用100, 2048bit的证书用 200 """ pubobj = rsa.importKey(pub_key_str) pubobj = PKCS1_v1_5.new(pubobj) res = [] for i in range(0, len(msg), length): res.append(pubobj.encrypt(msg[i:i+length])) return "".join(res) def rsa_long_decrypt(priv_key_str, msg, length=128): """ 1024bit的证书用128,2048bit证书用256位 """ privobj = rsa.importKey(priv_key_str) privobj = PKCS1_v1_5.new(privobj) res = [] for i in range(0, len(msg), length): res.append(privobj.decrypt(msg[i:i+length], 'xyz')) return "".join(res)

以上就是对crypto的简单运用,,,,,,

原文地址:https://www.cnblogs.com/nanyu/p/10613333.html