大江东去,浪淘尽,千古风流人物。故垒西边,人道是,三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。遥想公瑾当年,小乔初嫁了,雄姿英发。羽扇纶巾,谈笑间,樯橹灰飞烟灭。故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。

南鱼

果然,我没有抓住重点

导航

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的简单运用,,,,,,

posted on 2019-03-28 10:30  南鱼羁荒渡  阅读(2055)  评论(0编辑  收藏  举报