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

南鱼

果然,我没有抓住重点

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

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   南鱼羁荒渡  阅读(2058)  评论(0编辑  收藏  举报

编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· DeepSeek+PageAssist实现本地大模型联网
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· 从 14 秒到 1 秒:MySQL DDL 性能优化实战
点击右上角即可分享
微信分享提示