简体   繁体   English

Javascript加密文件上传

[英]Javascript Encrypted File Upload

有没有办法使用javascript或ajax加密文件上传,如果是这样,你能给我一个例子或链接到工作示例吗?

The answer is Yes, there is a way to use javascript or ajax to encrypt file uploads. 答案是肯定的,有一种方法可以使用javascript或ajax来加密文件上传。 You can use standard Web APIs that have built-in native support in browsers: Use the standard File API and WebCrypto API to get the file from your filesystem and actually encrypt it—along with the Indexed Database API (indexedDB) (if you want) to store the encrypted file on the client side in the browser. 您可以使用在浏览器中具有内置本机支持的标准Web API:使用标准File APIWebCrypto API从文件系统获取文件并实际加密它 - 以及索引数据库API(indexedDB) (如果需要)将加密文件存储在浏览器的客户端。 A good simple example with working code is at Upload a file, encrypt it, calculate the hash and store the results using indexedDB . 工作代码的一个很好的简单示例是上传文件,加密文件,计算哈希并使用indexedDB存储结果

Short summary of how to do it 简要总结如何做到这一点

The first step is just the normal step of creating an input type=file element in your HTML, and binding a function to it for getting the file from your filesystem and doing something with it; 第一步是在HTML中创建input type=file元素,并将函数绑定到它以从文件系统获取文件并使用它执行某些操作的正常步骤; eg, use onsubmit="my_file_handler" . 例如,使用onsubmit="my_file_handler"

After that, inside your my_file_handler (or whatever name) function: 之后,在my_file_handler (或任何名称)函数内:

  1. Use .files[…] from that to get the input file(s). 使用.files[…]来获取输入文件。
  2. Define a function that takes a cryptographic key; 定义一个接受加密密钥的函数; within that function: 在该功能内:

    • create a new FileReader object and use, eg, .readAsArrayBuffer(…) to load the file 创建一个新的FileReader对象,并使用例如.readAsArrayBuffer(…)来加载该文件
    • use crypto.subtle to create a new SubtleCrypto object 使用crypto.subtle创建一个新的SubtleCrypto对象
    • use .digest(…) with that SubtleCrypto object and then crypto.subtle.encrypt(…) to actually encrypt the file with that key 使用.digest(…)SubtleCrypto对象,然后使用crypto.subtle.encrypt(…)实际使用该密钥加密文件
    • use indexedDB.open(…) and friends to open a connection to a DB and to put the encrypted file into it. 使用indexedDB.open(…)和朋友打开与DB的连接并将加密文件放入其中。
  3. Use .importKey(…) to get the key and call your function in step #2 on it to process the input file with it and store it using indexedDB . 使用.importKey(…)获取密钥并在其上的步骤#2中调用您的函数以使用它处理输入文件并使用indexedDB存储它。

Use an HTTPS URL to upload the files and the browser will encrypt the data for transit automatically. 使用HTTPS URL上传文件,浏览器将自动加密数据以进行传输。

(This assumes you want to protect the file in transit and not that you are trying to protect the file from people with admin rights on the server) (这假设您要保护传输中的文件,而不是您试图保护文件不受具有管理员权限的人员的影响)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM