首页 > 解决方案 > 解码 base64 字符串是否安全

问题描述

我正在提交用户提交的文件(应该是图像),但可以提交 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)

标签: pythonshellflaskbase64

解决方案


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

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

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


推荐阅读