[1249]python实现rsa非对称加密

2023-12-25 09:25:43 浏览数 (2)

文章目录
  • 秘钥对象转换为字符串对象
  • Python实现RSA加密的方法:
    • 方法一:使用Python内置模块rsa
    • 方法二:使用第三方库cryptography
    • 方法三:使用第三方库Crypto

秘钥对象转换为字符串对象

代码语言:javascript复制
import rsa
import base64
 
pubkey, privkey = rsa.newkeys(1024)
#将公钥转换为字符串形式
pubkey_str = pubkey.save_pkcs1()
#将私钥转换为字符串形式
privkey_str = privkey.save_pkcs1()
# 将字符串形式的公钥转换成公钥原始对象
pubkey_1 = rsa.PublicKey.load_pkcs1(pubkey_str)
# 将字符串形式的私钥转换成私钥原始对象
privkey_1 = rsa.PrivateKey.load_pkcs1(privkey_str)
 
if __name__ == '__main__':
    print(pubkey_str)
    print(privkey_str)
    print('pubkey:', pubkey)
    print('pubkey_1:', pubkey_1)
    print('privkey:', privkey)
    print('privkey_1:', privkey_1)

输出结果如下:

代码语言:javascript复制
b'-----BEGIN RSA PUBLIC KEY-----nMIGJAoGBAKM3TIUT4GJhN0O51QshPTM1r7XWyVgKCRUVnRc 2lHP9ad2FHUO0KTtnpZd6NidVt65jtYr9Ta9APK o15CDPlELT98zu67PoHJqU WvL8kanLkU/iHY0Xmln/12049EfY82/W64EYcBg3VYsWeTyFTYS2Oea4ss1pQIQol6s jZNAgMBAAE=n-----END RSA PUBLIC KEY-----n'
b'-----BEGIN RSA PRIVATE KEY-----nMIICYQIBAAKBgQCjN0yFE BiYTdDudULIT0zNa 11slYCgkVFZ0XPtpRz/WndhR1nDtCk7aWXejYnVbeuY7WK/U2vQDyvqNeQgz5RC0/fM7uuz6ByalPlry/JGpy5FP4hn2NF5pf9dtOPRH2PNv1uuBGHAYN1WLFnk8hU2EtjnmuLLNaUCEKJerPo2TQIDAQABnAoGAdp/qbY5UtywRDpgxzzUJVf7fBjplfCdPEpPy6MI1yuBqmpunoqxx2G0gvUeFntHEIXyb4 1u 6nC1qrX79nVXqCiKdEab6nCbSwJSzL3fRc2ueWNC6pEud2V7ZI/vn3EDv cKl1T6UMwwFQtdDBv9S4ynh1KdGPLR8nUvj0HghscECRQCwJqO3HclPf8TYnJ/jP3diSrvJR sntSDJDMyaTPHsJStbH5XchICYx8HIjgBD1cCHkNgs09wzPzTmrnZ9YIZnk3IKJf8wI9AO0zobDGE5aAvtI2eWecfqYhcP3WOW6bCg800frOOx2fT6ZsnopS/LH5aq4 1n9rkPq6xPuy4F7WZmKDgvwJEeJarIxO4Gb1tQ1Dx61ODDL/JUcfun7oqrJgfhU5Bm5jCeoo/7IulAXJWvfZARjARsny9EMskhsyxaW3YlNvD38H5dynMCnPQCumt0g9Q2iMe9Falf/zxDjVaaJE9J  p1zCByxlHGrooPNLBaZjAhCkpfLV5TunWilSCqMZOYIqaYASnJ0CRQChaOKwfMSZP6mz1UgHtoSaqxqg/LQTMUckX/IQkLDwna0bod0PwygW7xqk1WhvR7uNAURTIebhBIkfYngIUxg5Gv9FYOw==n-----END RSA PRIVATE KEY-----n'
pubkey: PublicKey(114614180899816662258018971141129750228161444725660236552636414327069252062964265696176716368309427214265311260566775790634457057294585984882254254336080777607514136503682689896718325777997996063620666866381397285211628576815796029528491703485474562225177301504705035096703206922439404613610090555096098813517, 65537)
pubkey_1: PublicKey(114614180899816662258018971141129750228161444725660236552636414327069252062964265696176716368309427214265311260566775790634457057294585984882254254336080777607514136503682689896718325777997996063620666866381397285211628576815796029528491703485474562225177301504705035096703206922439404613610090555096098813517, 65537)
privkey: PrivateKey(114614180899816662258018971141129750228161444725660236552636414327069252062964265696176716368309427214265311260566775790634457057294585984882254254336080777607514136503682689896718325777997996063620666866381397285211628576815796029528491703485474562225177301504705035096703206922439404613610090555096098813517, 65537, 83301076714223526506766553754280669894377007418292695538019404111066460385173473055530301265778333415778648793251394852671017265865934046903451985216703216354223835337722934103722935286460487206454625071650506312832327725528870366950398054929753390889588502596672113288078616255672963706957699378989878063553, 39624393703997194023254088808380074207703219129987975954449603521017281676646309761008067414316225690073913525000841268968010583159115563085468357605813565046022131, 2892515700202492077222646666083004958400134459400611924928742817494612987083977721002026571647012988882660506840854658502919545255479672225980607)
privkey_1: PrivateKey(114614180899816662258018971141129750228161444725660236552636414327069252062964265696176716368309427214265311260566775790634457057294585984882254254336080777607514136503682689896718325777997996063620666866381397285211628576815796029528491703485474562225177301504705035096703206922439404613610090555096098813517, 65537, 83301076714223526506766553754280669894377007418292695538019404111066460385173473055530301265778333415778648793251394852671017265865934046903451985216703216354223835337722934103722935286460487206454625071650506312832327725528870366950398054929753390889588502596672113288078616255672963706957699378989878063553, 39624393703997194023254088808380074207703219129987975954449603521017281676646309761008067414316225690073913525000841268968010583159115563085468357605813565046022131, 2892515700202492077222646666083004958400134459400611924928742817494612987083977721002026571647012988882660506840854658502919545255479672225980607)

Python实现RSA加密的方法:

方法一:使用Python内置模块rsa
代码语言:javascript复制
import rsa
 
# 生成密钥对
(public_key, private_key) = rsa.newkeys(1024)
 
# 加密
message = 'Hello World!'
encrypted_message = rsa.encrypt(message.encode(), public_key)
 
# 解密
decrypted_message = rsa.decrypt(encrypted_message, private_key).decode()
 
print(decrypted_message)  # 输出 'Hello World!'
方法二:使用第三方库cryptography
代码语言:javascript复制
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend
 
# 生成RSA密钥对
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()
 
# 加密
message = b'Hello World!'
encrypted_message = public_key.encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
 
# 解密
decrypted_message = private_key.decrypt(
    encrypted_message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
 
print(decrypted_message.decode())  # 输出 'Hello World!'

这两种方法都可以实现RSA加密,第一种方法使用了Python的内置模块rsa,而第二种方法使用了第三方库cryptography。请注意,第二种方法需要先安装cryptography库。两种方法的核心思路是相同的,即生成密钥对、加密和解密过程,只是具体的实现细节有所不同。

方法三:使用第三方库Crypto

需要通过命令pip install pycryptodome安装第三方模块

代码语言:javascript复制
#! /usr/bin/env/python
# -*- coding:utf-8 -*-
import base64
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
 
 
def encrypt_str(origin_str_list, encrypt_lenth=1024):
    """
    加密函数
    :param origin_str_list: 需要加密的字符串列表
    :param encrypt_lenth:
    :return:
    """
    # 生成RsaKey对象
    random_generator = Random.new().read
    rsa = RSA.generate(encrypt_lenth, random_generator)
    # 通过RsaKey对象生成私钥,字节形式
    pubkey, privkey = rsa.publickey().exportKey(), rsa.exportKey()
    # 生成RSAKey类型的公钥和私钥
    pubkey, privkey = RSA.importKey(pubkey), RSA.importKey(privkey)
    # 生成cipher对象, 用于加解密操作
    cipher = PKCS1_v1_5.new(pubkey)
 
    # 存放加密字符串的列表
    encrypt_str_list = []
 
    for origin_str in origin_str_list:
        # 通过cipher.encrypt加密的数据,加密对象的数据类型需要为bytes类型
        encrypt_str_in_rsa = cipher.encrypt(bytes(origin_str.encode('utf-8')))
        # 在将加密后的字符串通过base64编码
        encrypt_str_in_base64 = base64.encodebytes(encrypt_str_in_rsa)
 
        # 加密后的字符串添加到encrypt_str_list中
        encrypt_str_list.append(encrypt_str_in_base64)
 
    return encrypt_str_list, privkey
 
 
def decrypt_str(encrypt_str_list, privkey):
    """
    解密函数
    :param encrypt_str_list:加密的字符串列表
    :param privkey: 私钥
    :return:
    """
    decrypt_str_list = []
    # 生成chiper对象, 用于加解密操作
    cipher = PKCS1_v1_5.new(privkey)
 
    for encrypt_str in encrypt_str_list:
        # 通过base64解码
        decrypt_str_in_base64 = base64.decodebytes(encrypt_str)
        # 通过rsa解密decrypt_str_in_base64
        decrypt_str_in_rsa = cipher.decrypt(decrypt_str_in_base64, 0).decode('utf-8')
 
        # 将解密后的数据添加到decrypt_str_list中
        decrypt_str_list.append(decrypt_str_in_rsa)
 
    return decrypt_str_list
 
 
if __name__ == '__main__':
    origin_str_list = ['hello', 'python']
    print('原始字符串:', origin_str_list)
    encrypt_str_list, privkey = encrypt_str(origin_str_list)
    print('加密后结果')
    for encrypt_str in encrypt_str_list:
        print('encrypt_str is:', encrypt_str)
    print('解密后结果:', decrypt_str(encrypt_str_list=encrypt_str_list, privkey=privkey))

输出结果:

代码语言:javascript复制
C:UsersAdministratorAppDataLocalProgramsPythonPython311python.exe D:/python_core_programming_learn/chapter_7_dict_set/notes.py
原始字符串: ['hello', 'python']
加密后结果
encrypt_str is: b'cwOr0KRFPf91C0ywgMfkYsfMKW/QSqJYnUjW1LWsrZEB4lhHVYpzxyQXZ/AqlZ/9jplndDG0BynDnJUkZi1aDWU RzCyBu7ueGYqQGfaSor2jdZClzP0KikS 1AcqWvm6Pz9bXYb6OHbTMhc/7IKJIHP6nz5RrlTiffl/19S38J2A=n'
encrypt_str is: b'iv3Pjo7F0BHBktJHfTz0Takmj Aq3annboGf2K3DlXJoCqjDTQjzbbS9ZvaKINrCzqdmarPxZnM1n UMGvacBENbC87FDBlcWuK9RFgNvQfR/fUuC/kwW ibrO4YmXx/2NamkrkOS2fHHW53GZ90hLLW8n54bZvRAbVs06ze8XKX4=n'
解密后结果: ['hello', 'python']

参考:https://blog.csdn.net/qq_25500415/article/details/118558579

0 人点赞