forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
randomBytes,
|
||||
scryptSync,
|
||||
} from "node:crypto";
|
||||
import { requireThat } from "./runtime";
|
||||
export function encrypt(value: unknown, password: string) {
|
||||
requireThat(password.length >= 20, "OPERATOR_PASSWORD_TOO_SHORT");
|
||||
const salt = randomBytes(16),
|
||||
iv = randomBytes(12),
|
||||
cipher = createCipheriv("aes-256-gcm", scryptSync(password, salt, 32), iv);
|
||||
const body = Buffer.concat([
|
||||
cipher.update(JSON.stringify(value), "utf8"),
|
||||
cipher.final(),
|
||||
]);
|
||||
return JSON.stringify({
|
||||
v: 1,
|
||||
salt: salt.toString("base64"),
|
||||
iv: iv.toString("base64"),
|
||||
tag: cipher.getAuthTag().toString("base64"),
|
||||
data: body.toString("base64"),
|
||||
});
|
||||
}
|
||||
export function decrypt<T>(value: string, password: string): T {
|
||||
try {
|
||||
const e = JSON.parse(value);
|
||||
requireThat(e.v === 1, "INVALID_ENVELOPE");
|
||||
const decipher = createDecipheriv(
|
||||
"aes-256-gcm",
|
||||
scryptSync(password, Buffer.from(e.salt, "base64"), 32),
|
||||
Buffer.from(e.iv, "base64"),
|
||||
);
|
||||
decipher.setAuthTag(Buffer.from(e.tag, "base64"));
|
||||
return JSON.parse(
|
||||
Buffer.concat([
|
||||
decipher.update(Buffer.from(e.data, "base64")),
|
||||
decipher.final(),
|
||||
]).toString(),
|
||||
);
|
||||
} catch {
|
||||
throw new Error("OPERATOR_DECRYPTION_FAILED");
|
||||
}
|
||||
}
|
||||
export async function operatorPassword() {
|
||||
if (Bun.env.VP7_OPERATOR_PASSWORD) {
|
||||
requireThat(
|
||||
Bun.env.VP7_OPERATOR_PASSWORD.length >= 20,
|
||||
"OPERATOR_PASSWORD_TOO_SHORT",
|
||||
);
|
||||
return Bun.env.VP7_OPERATOR_PASSWORD;
|
||||
}
|
||||
const proc = Bun.spawn(
|
||||
[
|
||||
"bash",
|
||||
"-c",
|
||||
'IFS= read -r -s -p "Operator passphrase (20+ chars): " value; printf "\\n" >&2; printf "%s" "$value"',
|
||||
],
|
||||
{ stdin: "inherit", stdout: "pipe", stderr: "inherit" },
|
||||
);
|
||||
const password = await new Response(proc.stdout).text();
|
||||
requireThat(
|
||||
(await proc.exited) === 0 && password.length >= 20,
|
||||
"OPERATOR_PASSWORD_TOO_SHORT",
|
||||
);
|
||||
return password;
|
||||
}
|
||||
Reference in New Issue
Block a user