How does one use the HACL* wasm library?

Viewed 102

The nice folks over at project everest compiled a formally verified cryptographic library known as HACL* to web assembly. Unfortunately there are no examples of using the code defined here.

I tested the code with Version 71.0.3578.98 (Official Build) (64-bit) of Chrome.

Here is in essence what I attempted on the client in order to get a working example.

      var module = HaclLoader().then(function(m) {
        var state_buffer = new ArrayBuffer(32);
        var state = new Uint32Array(state_buffer);
        var message_buffer = new ArrayBuffer(32);
        var message = new Uint8Array(message_buffer);
        for (var i = 0; i < message.length; i++) {
          message[i] = i;
        }             
        var hash_buffer = new ArrayBuffer(32);
        var hash = new Uint8Array(hash_buffer);
        m._Hacl_SHA2_256_init(state);
        m._Hacl_SHA2_256_update(state, message);
        m._Hacl_SHA2_256_finish(state, hash);
        console.log(hash);
      });

The code referenced attempts to use the functions defined here. Unfortunately this sample code does not work, the hash ends up being a zero array.

1 Answers

The solution was to use the primitives provided once the module was loaded, as follows.

let HACL = HaclLoader();

let sha256_init = HACL._Hacl_SHA2_256_init;
let sha256_update = HACL._Hacl_SHA2_256_update;
let sha256_finish = HACL._Hacl_SHA2_256_finish;

let state
let state_buffer
let message
let message_buffer
let hash
let hash_buffer

HACL.onRuntimeInitialized = function() {
    console.log(HACL);

    const state = new Uint32Array(8);
    for (let i = 0; i < 8; i++) {
        state[i] = i;
    }
    state_buffer = HACL._malloc(8 * state.BYTES_PER_ELEMENT);
    HACL.HEAPU32.set(state, state_buffer >> 2);

    const message = new Uint8Array(32);
    for (let i = 0; i < 32; i++) {
        state[i] = i;
    }
    message_buffer = HACL._malloc(32 * message.BYTES_PER_ELEMENT);
    HACL.HEAPU8.set(message, message_buffer >> 2);

    const hash = new Uint8Array(32);
    for (let i = 0; i < 32; i++) {
        state[i] = i;
    }
    hash_buffer = HACL._malloc(32 * hash.BYTES_PER_ELEMENT);
    HACL.HEAPU8.set(hash, hash_buffer >> 2);

    sha256_init(state_buffer);
    sha256_update(state_buffer, message_buffer);
    sha256_finish(state_buffer, hash_buffer);

    let result = [];
    for (let i = 0; i < 32; i++) {
        result[i] = HACL.HEAPU8[hash_buffer/Uint8Array.BYTES_PER_ELEMENT+i];
    }
    console.log(result);
};
Related