Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HmacSHA256 in WebAssembly compiled with Emscripten

Tags:

People also ask

What does WebAssembly compile to?

The WebAssembly. compile() function compiles WebAssembly binary code into a WebAssembly. Module object. This function is useful if it is necessary to a compile a module before it can be instantiated (otherwise, the WebAssembly.

Is WebAssembly compiled or interpreted?

WebAssembly, often abbreviated as Wasm, isn't really a “language” that you are going to be writing by hand. It's a binary-instruction format designed to be faster than JavaScript and very close to compiled languages. It's still an interpreted language, but it's designed to be interpreted by machines, not humans.

Can JavaScript be compiled to WebAssembly?

Yes, it is totally possible to call JavaScript-functions from inside your running WebAssembly functions!

Can C compile to WebAssembly?

When you've written a new code module in a language like C/C++, you can compile it into WebAssembly using a tool like Emscripten.


I'm trying to implement JWT token (encoding only) in WebAssembly, the goal is to have a very light weight wasm module. As a web developer my C knowledge is limited. For now I've implemented the following function (ported from JS) to encode url-safe Base64 encoder, which works perfectly.

char _keyStr[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
char ret_val[200];

char* encode (char *data){
    int len = strlen(data);
    int i = 0;
    int j = 0;

    while(i<len){
        char chr1 = data[i++];
        int chr2Out = (i > len - 1)? 1:0;
        char chr2 = data[i++];
        int chr3Out = (i > len - 1)? 1:0;;
        char chr3 = data[i++];


        char enc1 = chr1 >> 2;
        char enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        char enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        char enc4 = chr3 & 63;

        if (chr2Out) {
            enc3 = enc4 = 64;
        } else if (chr3Out) {
            enc4 = 64;
        }

        ret_val[j++] = _keyStr[enc1];
        ret_val[j++] = _keyStr[enc2];
        ret_val[j++] = _keyStr[enc3];
        ret_val[j++] = _keyStr[enc4];

    }
    ret_val[j] = '\0';
    return ret_val;
}

My next challenge is to be able to sign my JWT payload with HmacSHA256. The following JS fiddle, describes what I want to accomplish with C. https://jsfiddle.net/gm7boy2p/813/

I'm struggling with integrating a 3rd party code and complie it with emcc. I'm looking for a light weight library or a snippet.

Example code or any help would be appreciated.


Update: After extra research, reading this stackoverflow question and this article, it looks like using openssl or any other external library with WebAssembly is far from trivial. So what I'm looking for now is a standalone C function that I could integrate to my existing code.