kbpgp.js

Small files & buffers

In most of the examples, we've been dealing with string plaintexts and ciphertexts. Of course, sometimes you want to read and write files and convert to interesting strings such as hex or base64.

Recall when we were encrypting, we expected a string for the message:

# using a string
params =
  msg:         "Chuck chucky, bo-bucky!"
  encrypt_for: chuck # a KeyManager instance
      

In Node.js we can pass a Node.js Buffer instead. This could come from a file. Keep in mind this file's buffer and output need to fit easily in memory. (For arbitrarily large files, streams will come soon in kbpgp's future.)

fs.readFile 'foo.png', (err, buff) ->
  params =
    msg:         buff
    encrypt_for: chuck

In the browser, we have a similar Buffer available, kbpgp.Buffer. It behaves exactly the same as a Node.js buffer, thanks to native-buffer-browserify.

# using a string as a Buffer, in the browser
params =
  msg:         new kbpgp.Buffer "Chuck chucky, bo-bucky!"
  encrypt_for: chuck
      

Outputting buffers

kbpgp's burn function calls back with both a result_string (armored, when encrypting or signing), and a result_buffer (just raw binary data). The latter is either a Node.js Buffer, as discussed above, or, in the browser, a kbpgp.Buffer.

kbpgp.burn params, (err, result_string, result_buffer) ->
  console.log result_buffer.toString('hex')
  console.log result_buffer.toString('base64')
  # etc...
  # ...these work in both the browser and Node.js
      

In the browser, with HTML5

If you want to support file processing in the browser, you can use an HTML5 FileReader and convert a file's contents to a Buffer, right in the client side. Depending on the browser, you'll have memory constraints.

f = some_html_5_file_object
r = new FileReader()   # modern browsers have this
r.readAsBinaryString f
r.onloadend = (file) ->
   buffer = new kbpgp.Buffer r.result
   # ... now process it using kbpgp

We're just getting started with this tutorial and examples. Hit us up on github if anything is missing.