Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RSA加解密(二) #234

Open
soapgu opened this issue Jan 9, 2024 · 0 comments
Open

RSA加解密(二) #234

soapgu opened this issue Jan 9, 2024 · 0 comments
Labels

Comments

@soapgu
Copy link
Owner

soapgu commented Jan 9, 2024

  • 前言

这一篇日志的目标,把加密解密改成http服务,并进行一些测试。

  • fastapi

python以前我用的是Flask框架,听说fastapi更加流行,顺便这次试试水。

可以看下面的官方文档参考

  1. 安装相关库
pip install fastapi
pip install "uvicorn[standard]"
  1. 编写app
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import StreamingResponse
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import os

app = FastAPI()
recipient_key = RSA.import_key(open("publicKey").read())
max_plain_text_len = recipient_key.size_in_bytes() - 42 
cipher_rsa = PKCS1_OAEP.new(recipient_key)
private_key = RSA.import_key(open("privateKey").read())
decipher_rsa = PKCS1_OAEP.new(private_key)
data_length = private_key.size_in_bytes()


@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.post("/upload/")
async def create_upload_file(file: UploadFile):
    print(file.filename)
    save_path = os.path.join(os.getcwd(), "downloads" , file.filename)
    print(save_path)
    with open(save_path, 'wb') as out_file:
        while content := await file.read(max_plain_text_len):  # 每次读取RSA加密最大值
            encrypted_chunk = cipher_rsa.encrypt(content)
            out_file.write(encrypted_chunk)
    return {"filename": file.filename}

@app.get("/download")
async def get_file( file: str ):
    download_path = os.path.join(os.getcwd(), "downloads" , file)
    def iterfile():
        with open(download_path, 'rb') as in_file:
            while content := in_file.read(data_length):  # 每次读取数据
            #print("---read data---")
                decrypted_chunk = decipher_rsa.decrypt(content)
                yield decrypted_chunk
    headers = {
       "Content-Disposition": f"attachment; filename={file}",  # 设置下载文件名
    }
    return StreamingResponse(iterfile(), headers=headers , media_type="application/octet-stream")
  1. 运行server
uvicorn main:app --reload
图片

这里main是应该main.py的关系
而且支持自动更新,和开发node后端体验差不多

  • 运行测试结果

  • 第一个问题:加密解密速度慢

16710673437381651.jpg
大小:69K
加密: 0.1567249298095703 秒
解密: 0.31秒

123.png
大小:3.6M
加密:8.2986秒
解密:14.77秒

eBook.pdf
大小:8.3M
加密:19.2719秒
解密:34.08秒

  • 第二个问题:密文长度比明文大
    由于RSA的每个数据块加密是87byte->128byte,存储空间反而还变大了

所以RSA其实并不适合文件加密,其实在HTTS协议中,RSA是用来协商密钥的,真正的传输加密还是用的ASE对称加密

@soapgu soapgu added the Research label Jan 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant