@phala/dstack-sdk
Version:
44 lines (40 loc) • 1.42 kB
JavaScript
;
var ed25519 = require('@noble/curves/ed25519');
// src/encrypt-env-vars.ts
function hexToUint8Array(hex) {
hex = hex.startsWith("0x") ? hex.slice(2) : hex;
return new Uint8Array(
hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) ?? []
);
}
function uint8ArrayToHex(buffer) {
return Array.from(buffer).map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function encryptEnvVars(envs, publicKeyHex) {
const envsJson = JSON.stringify({ env: envs });
const privateKey = ed25519.x25519.utils.randomPrivateKey();
const publicKey = ed25519.x25519.getPublicKey(privateKey);
const remotePubkey = hexToUint8Array(publicKeyHex);
const shared = ed25519.x25519.getSharedSecret(privateKey, remotePubkey);
const importedShared = await crypto.subtle.importKey(
"raw",
new Uint8Array(shared),
{ name: "AES-GCM", length: 256 },
true,
["encrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
importedShared,
new TextEncoder().encode(envsJson)
);
const result = new Uint8Array(
publicKey.length + iv.length + encrypted.byteLength
);
result.set(publicKey);
result.set(iv, publicKey.length);
result.set(new Uint8Array(encrypted), publicKey.length + iv.length);
return uint8ArrayToHex(result);
}
exports.encryptEnvVars = encryptEnvVars;