Files
komari/pkg/jsruntime/crypto_interop_test.go
T
2026-08-01 20:21:04 +08:00

58 lines
2.3 KiB
Go

package jsruntime
import (
"io"
"testing"
"time"
)
// TestCryptoNodeInterop decrypts ciphertext generated by real Node.js so the
// Go-backed implementation stays wire-compatible with OpenSSL/Node.
func TestCryptoNodeInterop(t *testing.T) {
runtime, err := New(`
function joinBuffers(parts) {
let total = 0;
for (const part of parts) total += part.length;
const out = Buffer.alloc(total);
let offset = 0;
for (const part of parts) {
for (let i = 0; i < part.length; i++) out[offset + i] = part[i];
offset += part.length;
}
return out;
}
function verify() {
const crypto = require("node:crypto");
const key = Buffer.alloc(32, 1);
const iv = Buffer.alloc(12, 2);
// Ciphertext and tag produced by Node.js aes-256-gcm.
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAAD(Buffer.from("aad"));
decipher.setAuthTag(Buffer.from("7e82cd250bea9365ccb4151131ef1cf4", "hex"));
const plain = joinBuffers([decipher.update(Buffer.from("6eb8bd2c3838b1dda7a9cfbc", "hex")), decipher.final()]);
if (plain.toString() !== "interop test") return "gcm decrypt";
// Re-encrypt with the same fixed key/IV: output must match Node's.
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(Buffer.from("aad"));
const encrypted = joinBuffers([cipher.update("interop test"), cipher.final()]);
if (encrypted.toString("hex") !== "6eb8bd2c3838b1dda7a9cfbc") return "gcm encrypt";
if (cipher.getAuthTag().toString("hex") !== "7e82cd250bea9365ccb4151131ef1cf4") return "gcm tag";
// Node aes-256-cbc ciphertext.
const decbc = crypto.createDecipheriv("aes-256-cbc", Buffer.alloc(32, 3), Buffer.alloc(16, 4));
const cbcPlain = joinBuffers([decbc.update(Buffer.from("b00d5d15de8d38270478ea1ce3b97990", "hex")), decbc.final()]);
if (cbcPlain.toString() !== "interop cbc") return "cbc decrypt";
// Node pbkdf2-sha512 vector.
if (crypto.pbkdf2Sync("pw", "salt", 1000, 32, "sha512").toString("hex") !==
"dba2956d5d8f05e6f06dc9732ca6037d32a4fcbcdde4b35e62594b632d059275") return "pbkdf2 sha512";
return true;
}
`, Options{NodeJS: true, BaseDir: t.TempDir(), Console: io.Discard, Timeout: 5 * time.Second})
if err != nil {
t.Fatal(err)
}
defer runtime.Close()
if err := runtime.Call("verify"); err != nil {
t.Fatalf("Node interop verification failed: %v", err)
}
}