如何使用HACL * wasm库?

时间:2019-01-15 03:57:22

标签: emscripten webassembly

珠穆朗玛峰项目上的好伙伴们将经过正式验证的密码库称为HACL *编译到Web组装中。不幸的是,没有使用here定义的代码的示例。

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

从本质上讲,这是我在客户端上尝试获得的可行示例的方法。

      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);
      });

所引用的代码尝试使用定义的here函数。不幸的是,此示例代码不起作用,哈希最终为零数组。

1 个答案:

答案 0 :(得分:4)

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

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);
};