简体   繁体   中英

Javascript Encrypted File Upload

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

The answer is Yes, there is a way to use javascript or ajax to encrypt file uploads. 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. A good simple example with working code is at Upload a file, encrypt it, calculate the hash and store the results using 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; eg, use onsubmit="my_file_handler" .

After that, inside your my_file_handler (or whatever name) function:

  1. Use .files[…] from that to get the input file(s).
  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
    • use crypto.subtle to create a new SubtleCrypto object
    • use .digest(…) with that SubtleCrypto object and then crypto.subtle.encrypt(…) to actually encrypt the file with that key
    • use indexedDB.open(…) and friends to open a connection to a DB and to put the encrypted file into it.
  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 .

Use an HTTPS URL to upload the files and the browser will encrypt the data for transit automatically.

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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