UNPKG

@phala/dstack-sdk

Version:
42 lines (39 loc) 1.36 kB
import { x25519 } from '@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 = x25519.utils.randomPrivateKey(); const publicKey = x25519.getPublicKey(privateKey); const remotePubkey = hexToUint8Array(publicKeyHex); const shared = 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); } export { encryptEnvVars };