如何使用HACL*wasm库?

et4*_*4te 7 emscripten webassembly

项目珠穆朗玛峰上的好人们编写了一个正式验证的加密库,称为HACL*,用于Web组装.遗憾的是,没有使用此处定义的代码的示例.

我用Version 71.0.3578.98 (Official Build) (64-bit)Chrome 测试了代码.

这实际上是我在客户端上尝试的,以获得一个有效的例子.

      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);
      });
Run Code Online (Sandbox Code Playgroud)

引用的代码尝试使用此处定义的函数.不幸的是,这个示例代码不起作用,哈希最终成为零数组.

et4*_*4te 3

解决方案是使用加载模块后提供的原语,如下所示。

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);
};
Run Code Online (Sandbox Code Playgroud)