使用Python实现RSA加密

       RSA加密是一种非常常用的加密算法,该算法基于以下原理:求解两个大素数的积非常容易,但是对两个大素数的积进行因式分解比较困难。以下程序有三个功能:生成RSA私钥和公钥;根据给出的文件路径和文件名加密数据;根据给出的文件路径和文件名进行解密。

       读入文件后,若文件内容较长,则一次读入96个字符,循环读取,直到加密完毕,将文件中的原内容抹去,放入加密的内容;解密过程同理。

"""
使用RSA加密,密钥长度为3072位
"""

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64


# 初始化
def generate():
    # 伪随机数生成器
    random_generator = Random.new().read
    # rsa算法生成实例
    rsa = RSA.generate(3072, random_generator)
    private_pem = rsa.exportKey()
    with open('master-private.pem', 'wb') as f:
        f.write(private_pem)
    # 过的公钥并保存
    public_pem = rsa.publickey().exportKey()
    with open('master-public.pem', 'wb') as f:
        f.write(public_pem)
    print("公钥和私钥已放在程序同名文件夹下")


#加密
def rsa_encrypt(message, key):
        rsakey = RSA.importKey(key)  # 导入读取到的公钥
        cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
        # 通过生成的对象加密message明文,注意,在python3中加密的数据必须是bytes类型的数据,不能是str类型的数据
        cipher_text = base64.b64encode(cipher.encrypt(message.encode("utf-8")))
        return cipher_text


# 解密
def rsa_decrypt(cipher_text, key):
        rsakey = RSA.importKey(key)  # 导入读取到的私钥
        cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
        # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
        text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
        return text


def main():
    bytesLength = 96
    cryptostr = ""
    decryptostr = ""
    print("请选择需要的功能:")
    print("1. 生成私钥和公钥")
    print("2. 加密数据")
    print("3. 解密数据")
    SelectFlag = input("输入数字选择功能(1,2 or 3): ")
    match SelectFlag:
        case '1':
            generate()
        case '2':
            print("---------------加密开始---------------")
            filepath = input("请输入文件路径和文件名:")
            keypath = input("请输入公钥路径和文件名:")
            with open(keypath, 'r', encoding="utf-8") as publicfile:
                key = publicfile.read()
            with open(filepath, 'r+', encoding="utf-8") as fileSource:
                fileContent = fileSource.read()
                index = 0
                while index <= len(fileContent):
                    charFrame = fileContent[index:(index + bytesLength)]
                    cipher_text = rsa_encrypt(charFrame, key)
                    cryptostr = cryptostr + str(cipher_text) + "\n\n"
                    index = index + bytesLength
                fileSource.seek(0)
                fileSource.truncate()    # clear the file
                fileSource.write(cryptostr)
        case '3':
            print("---------------解密开始---------------")
            filepath = input("请输入文件路径和文件名:")
            keypath = input("请输入私钥路径和文件名:")
            with open(keypath, 'r', encoding="utf-8") as privatefile:
                privatekey = privatefile.read()
            with open(filepath, 'r+', encoding="utf-8") as fileSource:
                fileContent = fileSource.read()
                decrypptolist = fileContent.split('\n\n')
                index = 0
                while index < len(decrypptolist) and decrypptolist[index] != "":
                    decipher_text = rsa_decrypt(decrypptolist[index][1:-1], privatekey)
                    decryptostr = decryptostr + decipher_text.decode('utf-8')
                    index = index + 1
                fileSource.seek(0)
                fileSource.truncate()  # clear the file
                fileSource.write(decryptostr)
        case _:
            print("请选择三个功能中的一个")


main()

代码参考以下网站,若有侵权,请私信作者删除:

pycryptodemo实现DES,AES, RC4,Hash,RSA,DSA | 码农家园 (codenong.com)

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年11月7日
下一篇 2023年11月7日

相关推荐