接口自动化之RSA加密处理

一、RSA加密

数据论,需求两个大的素数比较简单,但将他们的乘积进行因式分解却极其困难。将乘积作为加密秘钥

RSA算法会生成一对秘钥,公钥和私钥。

公钥公开,用来加密数据,私钥不能泄露用来解密数据。也称为非对称加密。应为加密速度比较慢,一般用来做身份验证和短数据加密。

二、RSA使用

2.1 安装

pip install rsa

2.2 生成秘钥对

import rsa
pub,pri=rsa.newkeys(1024)

公钥是PublicKey(123646278002766893186075774844059180757005221703367385921812618519119762713419622214727814977007972861211250577065949539856442533452705330223286445588049894005751111617839446982738779185909151652171547781293472187625368999390462690820657297238644444889423850681462317352194249994042451287625140715187857046001, 65537)
私钥是PrivateKey(123646278002766893186075774844059180757005221703367385921812618519119762713419622214727814977007972861211250577065949539856442533452705330223286445588049894005751111617839446982738779185909151652171547781293472187625368999390462690820657297238644444889423850681462317352194249994042451287625140715187857046001, 65537, 119918230558827326514795647113283268811450156349661022271027539339514644213614669691781965115180795017035389137874617677080356804076894021611033555857601241168074325477786144183664899849831622114666424267132164966062313145023544712636842297827040882952755597147844542689205757182519335672277332007727560903169, 56918274205416331700234848962842427078058542054921384748886592446400219532727804086394995968180128941465644766627914058928612323188317932846350778861990103258302417, 21723476287515537120859987258975888717507756518099538481564621955901705815091002195169631521556621299066640308812435995798907

2.3 加密

# 将消息加密前转换成字节数据
message = '你好呀'.encode('utf-8')
print(message)
# 加密
res = rsa.encrypt(message, pub)
# 一般rsa加密会以base64编码输出
# base64编码就是把二进制以文本的形式输出
import base64
final_res=base64.b64encode(res).decode()

2.4 解密

# 解密
# 先把base64编码输出转换为字节final_res.encode()
# 还要解码base64编码
final_res=base64.b64decode(final_res.encode())
# 解密
res=rsa.decrypt(final_res, pri).decode('utf-8')

2.5 读取现有公钥

pub_key= """
    -----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE
    O3F7gs+7bzrgPsMl29LX8UoPYvIG8C604CprBQ4FkfnJpnhWu2lvUB0WZyLq6sBr
    tuPorOc42+gLnFfyhJAwdZB6SqWfDg7bW+jNe5Ki1DtU7z8uF6Gx+blEMGo8Dg+S
    kKlZFc8Br7SHtbL2tQIDAQAB
    -----END PUBLIC KEY-----
    """
# 一般提供的公钥的格式都是上面的pem格式的
# 1. 先要转换成字节数据
pub_key=pub_key.encode()
res=rsa.PublicKey.load_pkcs1_openssl_pem(pub_key)

2.6 封装为加密函数

import base64
import time

import rsa


def rsa_encrypt(msg: str, server_pub_key: str):
    # 公钥转换为字节数据
    pub_key_byte = server_pub_key.encode()
    # 调用方法进行加载
    pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key_byte)

    # 将加密数据转换成字节
    message = msg.encode('utf-8')

    # 加密
    crypt_msg = rsa.encrypt(message, pub_key)
    # 4. 将加密的结果字节转化成base64编码的字符串
    res = base64.b64encode(crypt_msg).decode()
    return res
posted @ 2021-08-18 18:13  大头~~  阅读(339)  评论(0编辑  收藏  举报