Git Product home page Git Product logo

recrypt-wasm-binding's Introduction

Recrypt WebAssembly Binding

Build Status NPM Version

This repository contains bindings to allow Recrypt to be used as a WebAssembly module within the browser. It depends on recrypt-rs as a dependency and contains shims both in Rust and JS to marshal data between WebAssembly and JavaScript. The bindings are generated using wasm-bindgen.

Install

npm install @ironcorelabs/recrypt-wasm-binding

Examples

The following examples show how to use this library from a browser-based web application. This library will need to be loaded with a module bundler such as webpack in order to correctly handle importing of ES6 modules and to properly load and instantiate the WebAssembly module. This module will also need to be loaded asynchronously if used via webpack. Refer to the webpack.config.js file which shows how this module is loaded for benchmarks and unit tests which are both run within the browser.

Basic Encrypt/Decrypt Example

import * as Recrypt from "@ironcorelabs/recrypt-wasm-binding";

//Create a new Recrypt API instance
const Api256 = new Recrypt.Api256();

//Generate both a user key pair and a signing key pair
const keys = Api256.generateKeyPair();
const signingKeys = Api256.generateEd25519KeyPair();

//Generate a plaintext to encrypt
const plaintext = Api256.generatePlaintext();

//Encrypt the data to the public key and then attempt to decrypt with the private key
const encryptedValue = Api256.encrypt(plaintext, keys.publicKey, signingKeys.privateKey);
const decryptedValue = Api256.decrypt(encryptedValue, keys.privateKey);

decryptedValue === plaintext; //true

Single-hop Transform Encryption Example

import * as Recrypt from "@ironcorelabs/recrypt-wasm-binding";

//Create a new Recrypt API instance
const Api256 = new Recrypt.Api256();

//Generate both a user key pair and a signing key pair
const userKeys = Api256.generateKeyPair();
const signingKeys = Api256.generateEd25519KeyPair();

//Generate a plaintext to encrypt
const plaintext = Api256.generatePlaintext();

//Encrypt the data to the user public key
const encryptedValue = Api256.encrypt(plaintext, userKeys.publicKey, signingKeys.privateKey);

//Generate a second public/private key pair as the target of the transform. This will allow the encrypted data to be
//transformed to this second key pair and allow it to be decrypted.
const deviceKeys = Api256.generateKeyPair();

//Generate a transform key from the user private key to the device public key
const userToDeviceTransformKey = Api256.generateTransformKey(userKeys.privateKey, deviceKeys.publicKey, signingKeys.privateKey);

//Transform the encrypted data (without decrypting it!) so that it can be decrypted with the second key pair
const transformedEncryptedValue = Api256.transform(encryptedValue, userToDeviceTransformKey, signingKeys.privateKey);

//Decrypt the data using the second private key
const decryptedValue = Api256.decrypt(transformedEncryptedValue, deviceKeys.privateKey);

decryptedValue === plaintext; //true

Types

This library contains a TypeScript definitions file which shows the available classes and methods.

Local Environment Setup

A few things are required as dependencies locally before you're able to run the benchmarks and unit tests for this library.

  • Install Rust. You must have Rust installed in order to compile the Rust bindings to WASM
  • Proper Rust target: Run rustup target add wasm32-unknown-unknown to add the wasm32-unknown-unknown target to Rust which is required to compile to WASM.
  • Install wasm-bindgen via cargo install wasm-bindgen-cli.
  • Run yarn from the root of this repo to install all JS dependencies.

Compiling WebAssembly Module

Run the yarn compile to compile the Rust code and generate a WASM module. The resulting .wasm file and wasm-bindgen shim will be generated in the target directory. By default we compile in release mode. Compiling is required before running either the unit tests or benchmarks below.

Benchmarks

Make sure you run yarn compile first.

In order to run the benchmarks in the browser you can run yarn benchmark. This will startup a webpack server at http://localhost:8080 which when opened will automatically start running the unit tests and display the results to the screen and developer console.

Unit Tests

Make sure you run yarn compile first.

Unit tests can be run in two ways

  • yarn test will run the tests via the command line via Chrome Headless and report the results at the end.
  • yarn testInBrowser will startup a webpack server at http://localhost:8080 which you can visit to see the results of the test within the browser directly.

License

Recrypt-wasm-binding is licensed under the GNU Affero General Public License. We also offer commercial licenses - email for more information.

Copyright (c) 2021 IronCore Labs, Inc. All rights reserved.

recrypt-wasm-binding's People

Contributors

bobwall23 avatar cjyar avatar clintfred avatar coltfred avatar dependabot[bot] avatar ernieturner avatar giarc3 avatar leeroy-travis avatar skeet70 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recrypt-wasm-binding's Issues

Help: Using recrypt-wasm-binding with Create-React-App

I found the webpack-usage documentation somewhat confusing, even after trying to eject a create-react-app project. I'm new to wasm+react, but was hoping using the npm module would make it more seamless.

Would love any additional documentation for using this in client-side browser applications.

Use 32-bit backend for ed25519

Our ed25519 dependency in recrypt supports using a 32-bit backend instead of the default 64 bit. This both improves performance and reduces the file size in the WASM code. We should figure out how to enable that feature at the WASM level to gain these improvements.

Question: why does transform need the signingKeys.privateKey

//Transform the encrypted data (without decrypting it!) so that it can be decrypted with the second key pair
const transformedEncryptedValue = Api256.transform(encryptedValue, userToDeviceTransformKey, signingKeys.privateKey);

I was wondering why this step needs the sigingKeys.privateKey. Doesn't that add the risk that comes with transferring the signignKey privateKey to the device?

Add PBKDF2 w/SHA-256 method to WASM binary

Edge doesn't yet support the PBKDF2 flavor that we've implemented for master private key escrow and the pure-JS polyfill is very slow. To better support Edge we should implement PBKDF2 in wasm so that we get better performance numbers and can call it from IronWeb.

Update dependencies

There are several downstream vulnerabilities that could tangentially impact this library, update dependencies.

Fix random number generation to support MS Edge in a WebWorker

The wasm-bindgen shim that gets generated as part of this package includes code that attempts to call the WebCrypto API. When this WASM module is used in a WebWorker, that API is not available in MS Edge which causes errors. We should expose a method in the shim to let users pass in a random value to be used in lieu of calling crypto.getRandomValues.

asm.js / Internet Explorer compatibility

Hi,

we still need to support Internet Explorer which does not support WebAssembly.

recrypt with ScalaJS is not an option because decrypting a transformed cipher takes up to 25 seconds with IE.

For a fallback solution I wanted to try asm.js compilation: I changed the target to asmjs-unknown-emscripten. Then I had to change the crate type to lib because cdylib was not supported by asmjs-unknown-emscripten. However, compilation failed:

   Compiling ed25519-dalek v1.0.0-pre.0 (https://github.com/IronCoreLabs/ed25519-dalek?branch=rand-0.6#1132665a)
error[E0277]: the trait bound `rand::distributions::Standard: rand::distributions::Distribution<u128>` is not satisfied
   --> /home/dph/.cargo/git/checkouts/ed25519-dalek-ab972af0b2b0a306/1132665/src/ed25519.rs:984:44
    |
984 |         .map(|_| Scalar::from(thread_rng().gen::<u128>()))
    |                                            ^^^ the trait `rand::distributions::Distribution<u128>` is not implemented for `rand::distributions::Standard`
    |
    = help: the following implementations were found:
              <rand::distributions::Standard as rand::distributions::Distribution<()>>
              <rand::distributions::Standard as rand::distributions::Distribution<(A, B)>>
              <rand::distributions::Standard as rand::distributions::Distribution<(A, B, C)>>
              <rand::distributions::Standard as rand::distributions::Distribution<(A, B, C, D)>>
            and 58 others

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `ed25519-dalek`.
warning: build failed, waiting for other jobs to finish...
error: build failed

Do you have any experience with asm.js compilation of recrypt-rs via emscripten?

version mismatch

This build failed in the Get version step:

Version 'null' in './examples/create-react-app-example/package.json' doesn't match '0.6.24-pre' from others in './Cargo.toml
./examples/create-react-app-example/package.json
./package.json'

The example app has a version that doesn't match the other versions in the repo. The bump-version workflow doesn't know what to do with that.

The current logic for package.json files is: If package.json is in the root of the repo, read the version from it. Otherwise, ignore the deeply nested package.json and read the version from package.json in the root of the repo, which must exist.

Options:

  • Change the example app so it has the same version as the repo.
  • Nest the example app more deeply so it gets ignored by find . -maxdepth 3.
  • Modify the bump-version scripts so they ignore that file. Maybe ignore deeply-nested package.json completely if there's no root package.json?

Expose the substring search functions to WASM

Pull in the ironcore-search-helpers and expose functions. Requires these steps:

  • Upgrade to recrypt 0.11
  • Expose the generate_hashes_for_string_with_padding and generate_hashes_for_string functions, behind a feature flag.

Compile on newer wasm bindgen

I'm not sure which version of wasm-bindgen is running in CI, but my local attempts with wasm-bindgen 0.2.74 (d1d64200a) failed to compile.

It looks like there need to be significant reworks in the fixBindgenShim.js code, as the output of wasm-bindgen has changed pretty significantly itself.

function removeNodeJSFunctions() {
    const shimJS = fs.readFileSync(SOURCE_JS_FILE, "utf8");

    //Replace the entire __wbg_require and randomFillSync method that is auto generated in the output.
    const codeWithoutNode = shimJS
        .replace(/\nexport function __wbg_require_[a-f0-9]*[(]arg0, arg1[)] {[^}]*};\n/, "")
        .replace(/\nexport function __wbg_randomFillSync_[a-f0-9]*[(]arg0, arg1, arg2[)] {[^}]*};\n/, "");

    if (codeWithoutNode.includes("require(") || codeWithoutNode.includes("randomFillSync")) {
        throw new Error("Replacement of NodeJS import and/or randomFillSync functions failed!");
    }
    fs.writeFileSync(SOURCE_JS_FILE, codeWithoutNode, "utf8");
}

That worked to fix the removeNodeJSFunctions breakage, but it looks like each of the other replacement functions may have changed as well.

According to https://caniuse.com/cryptography, WebCrypto support in WebWorkers was added to Edge at the end of 2018, we may now be safe to drop all the stuff we're doing in the shim to use Recrypt.setRandomSeed instead in Edge, which would simplify the shim drastically.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.