Skip to main content
 首页 » 编程设计

python之解码 base64 字符串是否安全

2024年11月01日34arxive

我正在提交用户提交的文件(应该是图像),但可以提交 python 文件。它作为 base64 编码字符串发送到后端 Flask 服务器,并解码为子目录中的文件。我担心安全问题,因为用户提交的文件将作为 img src="/images/fileThatIDecoded.jpg" 标签包含在动态生成的 HTML 中。我自己设置了名称和文件扩展名。如何验证解码后的 base64 字符串是否为有效图像?为了使用 imghdr 模块,我必须已经将解码后的字符串保存到一个文件中,这可能是不安全的。


我的代码:

mainPond.onaddfile = (err, item) => { 
  if (err) { 
    console.warn(err); 
    return; 
  } 
  const base64String = item.getFileEncodeBase64String(); 
  console.log(base64String) 
  document.getElementById("hiddenFile").value = base64String 
} 
document.getElementById("submitbtn").onclick = function() { 
  if (validateForm()) { 
    document.getElementById("form").submit() 
  } 
} 
@app.route("/create", methods=["GET","POST"]) 
@login_required 
def create(): 
    if request.method == "GET": 
        return render_template("create.html") 
    else: 
        imgdata = request.form.get("mainFile") 
        if helpers.verifyImage(imgdata[:44]): 
            imgdata = base64.b64decode(imgdata) 
            filename = 'some_image.jpg' 
            filename = os.path.join(os.path.abspath(os.curdir), "images", filename) 
            with open(filename, 'wb') as f: 
                f.write(imgdata) 

请您参考如下方法:

假设用户提供的文件是安全的是不安全的。 base64 编码对安全性没有任何影响。

要验证提供的文件是否为图像,您可以使用 imghdr module在标准库中,它“确定文件或字节流中包含的图像类型。”

您可以将图像作为字节流直接传递给 imghdr,而不是将其保存为文件。