python crypto加密运用

首先安装必须包,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

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

转载于:https://www.cnblogs.com/nanyu/p/10613333.html

你可能感兴趣的:(python,json)