Crypto
If your script needs to use cryptography functions, the current recommendation is to use Webpack to polyfill Node's crypto module.
Crypto functions are necessary for a variety of use cases, including url signing and encrypting/decrypting data.
Below is an example script and webpack config:
import crypto from "crypto";
const ENCRYPT_KEY = "my_32_chars_encryption_key_12345";
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
return new Response(JSON.stringify({ secret: encryptString("secret") }));
}
function encryptString(str) {
let iv = crypto.randomBytes(16);
let cipher = crypto.createCipheriv("aes-256-cbc", ENCRYPT_KEY, iv);
let encrypted = cipher.update(str, "utf8", "hex");
encrypted += cipher.final("hex");
return `${iv.toString("hex")}:${encrypted}`;
}
module.exports = {
entry: "./index.js",
mode: "production",
target: "webworker",
optimization: {
minimize: true
}
};
import crypto from "crypto";
const ENCRYPT_KEY = "my_32_chars_encryption_key_12345";
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
return new Response(JSON.stringify({ secret: encryptString("secret") }));
}
function encryptString(str) {
let iv = crypto.randomBytes(16);
let cipher = crypto.createCipheriv("aes-256-cbc", ENCRYPT_KEY, iv);
let encrypted = cipher.update(str, "utf8", "hex");
encrypted += cipher.final("hex");
return `${iv.toString("hex")}:${encrypted}`;
}
module.exports = {
entry: "./index.js",
mode: "production",
target: "webworker",
optimization: {
minimize: true
}
};
Updated 5 months ago
What’s Next