首页 > 编程语言 >python 使用 rsa库进行RSA签名和加解密

python 使用 rsa库进行RSA签名和加解密

时间:2023-12-27 18:46:17浏览次数:40  
标签:python self 加解密 RSA rsa result key message company

 

python 使用 rsa库进行RSA签名和加解密

 

# -*- coding: UTF-8 -*-
# ! /usr/bin/env python
import base64
import rsa
from rsa import common


# 使用 rsa库进行RSA签名和加解密
class RsaUtil(object):
    PUBLIC_KEY_PATH = '/tmp/gbzj/public_key.pem'  # 公钥
    PRIVATE_KEY_PATH = '/tmp/gbzj/private_key.pem'  # 私钥

    # 初始化key
    def __init__(self,
                 company_pub_file=PUBLIC_KEY_PATH,
                 company_pri_file=PRIVATE_KEY_PATH):

        if company_pub_file:
            self.company_public_key = rsa.PublicKey.load_pkcs1_openssl_pem(open(company_pub_file).read())
        if company_pri_file:
            self.company_private_key = rsa.PrivateKey.load_pkcs1(open(company_pri_file).read())

    def get_max_length(self, rsa_key, encrypt=True):
        """加密内容过长时 需要分段加密 换算每一段的长度.
            :param rsa_key: 钥匙.
            :param encrypt: 是否是加密.
        """
        blocksize = common.byte_size(rsa_key.n)
        reserve_size = 11  # 预留位为11
        if not encrypt:  # 解密时不需要考虑预留位
            reserve_size = 0
        maxlength = blocksize - reserve_size
        return maxlength

    # 加密 支付方公钥
    def encrypt_by_public_key(self, message):
        """使用公钥加密.
            :param message: 需要加密的内容.
            加密之后需要对接过进行base64转码
        """
        encrypt_result = b''
        max_length = self.get_max_length(self.company_public_key)
        while message:
            input = message[:max_length]
            message = message[max_length:]
            out = rsa.encrypt(input, self.company_public_key)
            encrypt_result += out
        encrypt_result = base64.b64encode(encrypt_result)
        return encrypt_result

    def decrypt_by_private_key(self, message):
        """使用私钥解密.
            :param message: 需要加密的内容.
            解密之后的内容直接是字符串,不需要在进行转义
        """
        decrypt_result = b""

        max_length = self.get_max_length(self.company_private_key, False)
        decrypt_message = base64.b64decode(message)
        while decrypt_message:
            input = decrypt_message[:max_length]
            decrypt_message = decrypt_message[max_length:]
            out = rsa.decrypt(input, self.company_private_key)
            decrypt_result += out
        return decrypt_result

    # 签名 商户私钥 base64转码
    def sign_by_private_key(self, data):
        """私钥签名.
            :param data: 需要签名的内容.
            使用SHA-1 方法进行签名(也可以使用MD5)
            签名之后,需要转义后输出
        """
        signature = rsa.sign(data, priv_key=self.company_private_key,
                             hash_method='SHA-256')  # 加密方式Use 'MD5', 'SHA-1', 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'
        return base64.b64encode(signature)

    def verify_by_public_key(self, message, signature):
        """公钥验签.
            :param message: 验签的内容.
            :param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码).
        """
        signature = base64.b64decode(signature)
        return rsa.verify(message, signature, self.company_public_key)


message = 'appId=f334fdgd&bizContent={"authCode":"4196a49571e747259028fa25df330604b4f6d301"}&timestamp=2022-08-01 10:20:08'
print("明文内容:>>> ")
print(message)
rsaUtil = RsaUtil()
encrypy_result = rsaUtil.encrypt_by_public_key(message)
print("加密结果:>>> ")
print(encrypy_result)
decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result)
print("解密结果:>>> ")
print(decrypt_result)

sign = rsaUtil.sign_by_private_key(message)
print("签名结果:>>> ")
print(sign)
print("验签结果:>>> ")
print(rsaUtil.verify_by_public_key(message, sign))

 

标签:python,self,加解密,RSA,rsa,result,key,message,company
From: https://www.cnblogs.com/zhaoyingjie/p/17931194.html

相关文章

  • 【Python数据分析课程设计】大数据分析—利用k-means 聚类分析对客户细分分析
    一、选题的背景在当今社会,大数据已经成为了企业决策的重要依据。通过对客户进行细分分析,企业可以更好地了解客户的需求和行为,从而制定更加精准的营销策略,提高市场竞争力。要达到的数据分析目标是通过对客户数据的分析,找出不同客户群体的特征和需求,为企业提供有针对性的营销......
  • python生成word文档
    python生成word文档,感觉比java生成方便很多下面看看步骤1、环境pipinstallpython-docx2、准备一张需要插入word中的图片monty-truth.png3、一段代码fromdocximportDocumentfromdocx.sharedimportInchesdocument=Document()document.add_heading('Document......
  • python实现汉诺塔游戏
    highlighter-pythonlt=list()#左边的空列表rt=list()#右边的空列表ct=list()#中间的空列表#初始化函数definit():size=int(input("请输入你要挑战的高度:"))#建立左边的汉诺塔foriinrange(1,size+1):lt.append(i*2-1);......
  • 一个完整Python实战项目:selenium识别验证码实现自动登录,自动操作浏览器获取某东数据
    最近都没啥时间,很久没更新了。今天分享一下,如何用selenium识别验证码,实现自动登录以及获取数据。目标:某东话不多说直接开始准备工作环境Python3.10Pycharm模块使用importrandomimporttimefromseleniumimportwebdriverimportpyautoguii......
  • 【Python&RS】基于Python对栅格数据进行归一化(统一量纲至0~1)
            有段时间没有更新Python处理栅格、矢量数据了,一部分是因为之前基本上已经把如何使用Python处理地理数据的方法覆盖完了,另一部分是因为最近有其他方面的知识需要学习和巩固。也是赶巧,最近有个项目需要构建模型对影像进行反演需要用到归一化,所以就编了一段代码,今......
  • Python采集html页面时如何去除掉script,link等指定html标签
    python爬虫去除html中特定标签、去除注释、替换实体前言:本文主要讲w3lib库的四个函数html.remove_tags()html.remove_tags_with_content()html.remove_comments()html.remove_entities()remove_tags作用:去除或保留标签,但是仅仅是去除标签,正文部分是不做处理的 看其函数......
  • python代码pycharm 中可以运行 vscode无法运行
    问题:pycharm中可以运行,切到vscode中时无法运行,都是路径无法读取到导致模块无法加载。分析:主要原因有可能是VSCode默认使用项目文件夹根目录作为工作目录(cwd),这会使得子文件夹中的程序无法使用相对路径。vscode中设置一下:文件=>首选项=>设置中搜索ExecuteinFileDir,......
  • centos 7.9 安装 python 3.10.5 和 openssl 3.0.12
    centos编译安装python和openssl安装环境:centos7.9:python3.10.5和openssl3.0.12centos6.10:python3.10.5和openssl1.1.1两个环境都能安装成功,可以正常使用。安装openssl下载地址下载后解压,进入到解压目录执行:./Configure--prefix=/usr/local/openssl3.......
  • 怎么用 python 项目函数实现字符串反转
    字符串反转是一个常见的操作,可以通过Python函数轻松实现。在本文中,我们将探讨如何使用Python函数来反转字符串,无论是针对单个字符串还是列表中的多个字符串。1.反转单个字符串要反转单个字符串,我们可以使用Python的切片功能或者内置的reversed()函数。使用切片功能defrevers......
  • Python 爬虫与网络安全有什么关系
    Python爬虫和网络安全之间存在密切的关系。爬虫是一种用于自动化从网络上获取信息的程序,而网络安全是保护计算机网络和系统免受未经授权的访问、攻击和数据泄露的实践。本文将探讨Python爬虫与网络安全之间的关系以及如何在爬虫开发中注意网络安全。爬虫的作用和风险爬虫通常用于从......