filecrypt

1.2.4 • Public • Published

FileCrypt

npm

A webcrypto wrapper for files

Install:

npm i --save-dev filecrypt

Usage:

import FileCrypt from 'filecrypt';

Generating an encryption key:

FileCrypt.generateKey()
.then(key => {
    // key is a CryptoKey object
    console.log(key);
});

Generating an encryption key from a password:

FileCrypt.importPassword(password)
.then(key => {
    // key is a CryptoKey object
    console.log(key);
});

Wrapping and unwrapping a CryptoKey for storage:

FileCrypt.wrapKey(keyToWrap, wrappingKey)
.then(data => {
    const {key, iv} = data;
    // key is an ArrayBuffer representing the wrapped key, iv is the iv used
    console.log(key);
});
FileCrypt.unwrapKey(wrappedKey, unwrappingKey, iv)
.then(key => {
    // key is a CryptoKey
    console.log(key);
});

Importing and exporting a CryptoKey for insecure storage:

FileCrypt.exportKey(key)
.then(buf => {
    // buf is an ArrayBuffer
    console.log(buf);
});
FileCrypt.importKey(buf)
.then(key => {
    // key is a CryptoKey
    console.log(key);
});

Encrypting and decrypting:

input.addEventListener('change', function(e) {
    var file = e.target.files.item(0);
    FileCrypt.encrypt(key, file) // key is a CryptoKey
    .then(res => {
        let {result, iv} = res;
        console.log(iv.buffer); // the ArrayBuffer containing the iv used to encrypt
        console.log(result); // the ArrayBuffer containing the encrypted data
    });
});
 
FileCrypt.decrypt(key, iv, buffer)
.then(data => {
    // data is an ArrayBuffer containing the decrypted data
    console.log(data);
});

Saving the iv together with the encrypted file:

var merged = FileCrypt.mergeIvAndData(iv.buffer, result);
// merged is iv buffer prepended to result buffer
 
let {iv, data} = FileCrypt.splitIvAndData(merged);
console.log(iv);
console.log(data);
// iv and data are ArrayBuffers

Extra utilities:

// ArrayBuffer to base64 string
FileCrypt.ab2str(arrayBuffer);
 
// base64 string to ArrayBuffer
FileCrypt.str2ab(b64str);
 
// ArrayBuffer to File
FileCrypt.ab2file(arrayBuffer);
 
// File to ArrayBuffer
FileCrypt.file2ab(file)
.then(buffer => console.log(buffer));

Package Sidebar

Install

npm i filecrypt

Weekly Downloads

12

Version

1.2.4

License

none

Unpacked Size

9.3 kB

Total Files

3

Last publish

Collaborators

  • tklg