Rock's blog

兴趣是最好的老师

0%

利用Python的rsa模块加解密文件

1.模块安装

Python默认没有安装rsa模块,所以如果编译器告诉你找不到rsa模块时,你需要安装它.

Windows下:

在你安装Python的目录下找到Scripts目录,运行里面的pip.exe,其使用方式和linux下的pip一致.

在cmd中输入:

pip install rsa

这会在Script目录下下载一些exe程序,这时rsa模块就已经安装好了

Linux下:

在命令行中输入:

pip install rsa

2.代码示例

(1)加密程序 encrypt.py

import rsa
import base64
from sys import argv

try:
    plainfileName = argv[1]
    cipherFileName = argv[2]
    
    plainfileObject = open(plainfileName)
    cipherFileObject = open(cipherFileName,"wb")
    try:
        message = plainfileObject.read()	# 明文
        
        #生成密钥
        (pubkey, privkey) = rsa.newkeys(2048)
        # 保存密钥
        with open('public.pem','w+') as f:
            f.write(pubkey.save_pkcs1().decode())

        with open('private.pem','w+') as f:
            f.write(privkey.save_pkcs1().decode())

        # 公钥加密
        crypto = base64.encodestring(rsa.encrypt(message.encode(), pubkey))
        # print(str(crypto,encoding = 'utf-8'))
        cipherFileObject.write(crypto)
        
    finally:
        plainfileObject.close()
        cipherFileObject.close()
except:
    print("Example:\nencrypt.py plainfileName cipherFileName")

该程序会要求你以这样的方式运行它:

encrypt.py plainfileName cipherFileName

其中plainfileName是你要加密的文件名,cipherFileName是密文保存的文件名

(3)解密代码示例 decrypt.py

import rsa
import base64
from sys import argv

try:

    fileName = argv[1]
    publicKey = argv[2]
    privateKey = argv[3]

    fileObject = open(fileName,"rb")
    try:
        crypto = fileObject.read()	# 明文
        
        # 导入密钥
        with open(publicKey,'r') as f:
            pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())

        with open(privateKey,'r') as f:
            privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())

        # 私钥解密
        message = rsa.decrypt(base64.decodestring(crypto), privkey).decode()
        print(message)
    finally:
        fileObject.close()
except:
    print("Example:\ndecrypt.py fileName publicKey privateKey")

该程序会要求你以这样的方式运行它:

decrypt.py fileName publicKey privateKey

fileName指你要解密的文件,publicKey是当时加密时生成的公钥文件,privateKey是私钥文件