To avoid including libc, I want to implement encryption in place by copying bytes into memory at a fixed offset or defining a global heapOffset. For simplicity, I might use a preallocated memory example with basePtr set to 0, but that isn't really practical. Instead, I could import memory from JavaScript to manage the buffer. Since this is for educational purposes, I'll keep it simple and not focus on robust memory management. The user asked for a "simple wrapper," which helps guide my approach!Creating a simple encryption wrapper
I’m looking to showcase a C function for encryption using XOR. I’d write it like this:
I might also include EMSCRIPTEN_KEEPALIVE. The JavaScript wrapper just needs to know the exported function name, so I'll provide a simple JS version for comparison.
I'll also discuss using WebAssembly.instantiateStreaming for loading, falling back to fetch/arrayBuffer if needed. Since they asked for a "wrapper," I’ll create createEncryptor that loads the wasm and returns an object with encryptWasm and encryptJs. Let's keep it straightforward! Below is a minimal, end-to-end example: a tiny “encryption” function (XOR) implemented in WebAssembly and a JavaScript wrapper that:
Loads the .wasm file
Copies data into Wasm memory
Calls the Wasm encryption function
Compares it to a pure JS version
(The XOR cipher is not secure; this is only for performance/FFI demonstration.)
1. Simple C code to compile to WebAssembly
encrypt.c:
c
// Very simple XOR "encryption" in-place: data[i] ^= key
// This function will be exported to Wasm.
#include <stdint.h>
// For Clang/LLD – explicitly export name:
__attribute__((export_name("xor_encrypt")))
void xor_encrypt(uint8_t *data, uint32_t len, uint8_t key) {
for (uint32_t i = 0; i < len; i++) {
data[i] ^= key;
}
}
// Wrapper around the encrypt.wasm module
async function initEncryptWasm(wasmUrl = 'encrypt.wasm') {
// Load and instantiate the WASM module
const response = await fetch(wasmUrl);
const { instance } = await WebAssembly.instantiateStreaming(response, {});
const { memory, xor_encrypt } = instance.exports;
if (!(memory instanceof WebAssembly.Memory) || typeof xor_encrypt !== 'function') {
throw new Error('WASM module missing expected exports');
}
// Simple allocator: reuse a fixed offset in memory
// For demo purposes only (not thread-safe or general-purpose).
let heapOffset = 0;
function ensureMemory(size) {
// Grow memory if needed (size in bytes)
const pageSize = 64 * 1024;
const neededPages = Math.ceil(size / pageSize);
const currentPages = memory.buffer.byteLength / pageSize;
if (neededPages > currentPages) {
memory.grow(neededPages - currentPages);
}
}
/**
* Encrypts a Uint8Array using the WASM xor_encrypt function.
* @param {Uint8Array} data - input data
* @param {number} key - single-byte key (0–255)
* @returns {Uint8Array} encrypted output (new buffer)
*/
function encryptWasm(data, key) {
if (!(data instanceof Uint8Array)) {
throw new TypeError('data must be a Uint8Array');
}
const len = data.length;
const size = len; // bytes needed
// Ensure there is enough memory
ensureMemory(heapOffset + size);
// Pointer where we place the data
const ptr = heapOffset;
// Get a view into the WASM memory
const memU8 = new Uint8Array(memory.buffer, ptr, len);
// Copy input into WASM memory
memU8.set(data);
// Call WASM function: xor_encrypt(ptr, len, key)
xor_encrypt(ptr, len, key & 0xff);
// Copy result out into a fresh Uint8Array
return new Uint8Array(memU8); // copies the contents
}
return { encryptWasm, memory, rawInstance: instance };
}
// Export for module environments
export { initEncryptWasm };
3. JavaScript-only version for comparison
encrypt-js.js:
js
/**
* Pure JS XOR encryption for comparison.
* @param {Uint8Array} data
* @param {number} key
* @returns {Uint8Array} encrypted copy
*/
function encryptJs(data, key) {
const out = new Uint8Array(data.length);
const k = key & 0xff;
for (let i = 0; i < data.length; i++) {
out[i] = data[i] ^ k;
}
return out;
}
export { encryptJs };
4. Using both and benchmarking
Example usage (ES modules):
js
import { initEncryptWasm } from './encrypt-wasm.js';
import { encryptJs } from './encrypt-js.js';
async function runDemo() {
const { encryptWasm } = await initEncryptWasm('encrypt.wasm');
const size = 10_000_000;
const key = 0x5a;
const data = new Uint8Array(size);
// Fill with some data
for (let i = 0; i < size; i++) data[i] = i & 0xff;
console.time('JS encrypt');
const jsResult = encryptJs(data, key);
console.timeEnd('JS encrypt');
console.time('WASM encrypt');
const wasmResult = encryptWasm(data, key);
console.timeEnd('WASM encrypt');
// Verify same result
let equal = jsResult.length === wasmResult.length;
for (let i = 0; equal && i < jsResult.length; i++) {
if (jsResult[i] !== wasmResult[i]) equal = false;
}
console.log('Results equal:', equal);
}
runDemo().catch(console.error);
This gives you a minimal WebAssembly wrapper for a performance-critical byte-wise encryption routine and a direct JS comparison. You can drop in a more complex encryption algorithm in C/Rust later while keeping the same JavaScript wrapper pattern.