import { XWing } from "@noble/post-quantum/hybrid.js"; import { xchacha20poly1305 } from "@noble/ciphers/chacha.js"; import { randomBytes } from "@noble/hashes/utils.js"; import { sha3_512 } from "@noble/hashes/sha3.js"; import type { EncryptedPayload } from "./types.ts"; export function encryptText( publicKey: Uint8Array, text: string, ): EncryptedPayload { // Create a copy of the public key to prevent mutation by XWing.encapsulate const publicKeyCopy = new Uint8Array(publicKey); const { cipherText, sharedSecret } = XWing.encapsulate(publicKeyCopy); const nonce = randomBytes(24); const contentBytes = new TextEncoder().encode(text); const cipher = xchacha20poly1305(sharedSecret, nonce); const content = cipher.encrypt(contentBytes); const hash = sha3_512(contentBytes); return { cipherText: cipherText.toBase64(), content: content.toBase64(), nonce: nonce.toBase64(), hash: hash.toBase64(), length: contentBytes.byteLength, }; }