首页 > 编程语言 >python 对于实现rsa加密算法

python 对于实现rsa加密算法

时间:2024-05-17 15:43:32浏览次数:26  
标签:str python self rsa private pem key 加密算法

import base64

import rsa


class GenerateKey(object):
    d = "ascii"

    def generate_keys(self, bits=1024):
        (pubkey, privkey) = rsa.newkeys(bits)
        pem_pubkey = rsa.PublicKey.save_pkcs1(pubkey).decode(self.d)
        b64_pubkey = self.b64_encrypt(pem_pubkey).decode(self.d)

        pem_privkey = rsa.PrivateKey.save_pkcs1(privkey).decode(self.d)
        b64_privkey = self.b64_encrypt(pem_privkey).decode(self.d)

        return b64_pubkey, b64_privkey

    def decrypt(
        self, ciphertext: str | bytes, private_key_pem: bytes | str | rsa.PrivateKey
    ) -> str:
        """私钥入参必须是pem格式, 不接受(模数,指数) 的类型

        Args:
            ciphertext (str): 字符串
            private_key_pem (str): pem字节串

        Returns:
            _type_: _description_
        """
        if isinstance(private_key_pem, (str, bytes)):
            private_key_pem = private_key_pem.strip()
            if isinstance(private_key_pem, str):
                private_key_pem = private_key_pem.encode()
            private_key = rsa.PrivateKey.load_pkcs1(
                private_key_pem, "PEM"
            )  # 解析成为 (模数,指数) 类型
        else:
            private_key = private_key_pem
        if isinstance(ciphertext, str):
            ciphertext = ciphertext.encode()

        decrypted_text = rsa.decrypt(ciphertext, private_key)

        return decrypted_text.decode()

    def encrypt(self, plaintext: str | bytes, public_key: bytes | str | rsa.PublicKey):
        # rsa 加密函数
        """仅接受pem格式数据,不支持(模数,指数) 的类型

        Args:
            plaintext (str): 需要加密的文本
            public_key (rsa.PublicKey): 使用的公钥字节串

        Returns:
            _type_: _description_
        """
        if isinstance(plaintext, str):
            plaintext = plaintext.encode()

        if isinstance(public_key, (str, bytes)):
            public_key = public_key.strip()
            if isinstance(public_key, str):
                public_key = public_key.encode()
            public_key = rsa.PublicKey.load_pkcs1(public_key, "PEM")  # 解析成为 (模数,指数) 类型
        else:
            public_key = public_key

        ciphertext = rsa.encrypt(plaintext, public_key)
        return ciphertext.decode()

    def b64_encrypt(self, test: str):
        # b64编码
        return base64.b64encode(test.encode(self.d))

    def b64_decrypt(self, test: str):
        # b64解码
        return base64.b64decode(test.encode(self.d))

前端与后端传输时,前端可能传给后端的是b64对象,后端解密时需要注意。

标签:str,python,self,rsa,private,pem,key,加密算法
From: https://www.cnblogs.com/Pyxin/p/18197873

相关文章

  • Python模拟数据生成库Faker
    Python模拟数据生成库FakerPYPI官网https://pypi.org/project/Faker/Github官网https://github.com/joke2k/faker文档https://faker.readthedocs.io/en/master/中文参考:Python-faker的简单使用https://www.cnblogs.com/TSmagic/p/16072399.htmlpython中第三方库Fake......
  • 【吐槽】今天才发现PyCharm不支持对Python脚本进行块注释
    在PyCharm中对Python脚本Ctrl+Shift+/进行块注释不起作用,然后使用OpenArk64查看是否热键占用冲突,没有发现其他占用。然后发现PyCharm中Code菜单项下的选项CommentwithBlockComment是灰色的。又查了下,最后发现jetbrains官方帮助文档中已说明PyCharm不支持对Python脚本进行......
  • Python通过Geoip解析IP地址信息
    最近在研究ELK日志分析系统,在分析haproxy日志时,考虑需要将haproxy内获取到的IP地址进行解析,网站访问情况。于是有了这么一个需求,奈何maxmind数据库有些不准确,于是衍生出了一个想法,要测试maxmind数据库的准确性。于是乎想到了一个简单的方法,利用python脚本来配置geoip数据库来解......
  • python测试postgres远程登录
    #首先安装psycopg2模块importpsycopg2 #配置数据库连接参数conn_params={"dbname":"your_db","user":"your_user","password":"your_password","host":"your_host","port":&......
  • python爬虫基础
    前言Python非常适合用来开发网页爬虫,理由如下:1、抓取网页本身的接口相比与其他静态编程语言,如java,c#,c++,python抓取网页文档的接口更简洁;相比其他动态脚本语言,如perl,shell,python的urllib包提供了较为完整的访问网页文档的API。(当然ruby也是很好的选择)此外,抓取网页有时候需要模......
  • Python数据分析与挖掘实战(1-3章)
    非原创,仅个人关于《Python数据分析与挖掘实战》的学习笔记第一章基础略第二章数据分析简介基本概念元组、列表、字典、集合函数式编程:map()函数:定义一个函数,然后用map()逐一应用到map列表中的每个元素。map(lambdax+2:a)reduce()函数:用于递归计算。reduce(lambdax,......
  • 如何使用Python和Plotly绘制3D图形
    本文分享自华为云社区《Plotly绘制3D图形》,作者:柠檬味拥抱。在数据可视化领域,三维图形是一种强大的工具,可以展示数据之间的复杂关系和结构。Python语言拥有丰富的数据可视化库,其中Plotly是一款流行的工具,提供了绘制高质量三维图形的功能。本文将介绍如何使用Python和Plotly来绘......
  • python折线图包括设置横纵坐标字体大小刻度间隔等
    直径上代码#!usr/bin/envpython#-*-coding:utf-8-*-"""@author:Suyue@file:dryzhexian.py@time:2024/05/16@desc:"""importpandasaspdimportmatplotlibimportmatplotlib.pyplotaspltimportmatplotlib.tickerasticker......
  • Python03判断语句
    Python03判断语句比较运算符if语句......
  • Python进阶之实现单例模式的常见方法
    【一】单例模式介绍【1】什么是单例模式一个类只允许创建一个对象(或者实例),那这个类就是一个单例类,这种设计模式就叫作单例设计模式,简称单例模式【2】为什么要学单例模式当一个类的功能比较单一,只需要一个实例对象就可以完成需求时,就可以使用单例模式来节省内存资源【3】......