美文网首页
RSA 加解密

RSA 加解密

作者: aq_wzj | 来源:发表于2023-01-05 16:54 被阅读0次
import base64
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

pub_key = """-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----"""

pri_key = """-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----"""


#  加密
def encryption(text, public_key):
    # 字符串指定编码(转为bytes)
    text = text.encode('utf-8')
    # 构建公钥对象
    cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
    # 加密(bytes)
    text_encrypted = cipher_public.encrypt(text)
    # base64编码,并转为字符串
    text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
    return text_encrypted_base64


#  解密
def decryption(text_encrypted_base64, private_key):
    # 字符串指定编码(转为bytes)
    text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
    # base64解码
    text_encrypted = base64.b64decode(text_encrypted_base64)
    # 构建私钥对象
    cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
    # 解密(bytes)
    text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
    # 解码为字符串
    text_decrypted = text_decrypted.decode()
    return text_decrypted


text_str = '123456'
# 加密
miwen = encryption(text_str, pub_key)
print(miwen)
# 解密
mingwen = decryption(miwen, pri_key)
print(mingwen)

相关文章

网友评论

      本文标题:RSA 加解密

      本文链接:https://www.haomeiwen.com/subject/qparcdtx.html