Skip to main content
Go to Latest
File
import { DarkflareError } from './DarkflareError.ts'import { encode, hash } from './utilities.ts'
export async function encrypt(message: string, secret?: string) { if (!secret) { const c = window.__d.encryption
if (!c || !c.secretKey) throw new DarkflareError('crypto', 'CRYPTO NOT CONFIGURED')
secret = c.secretKey }
try { const iv = crypto.getRandomValues(new Uint8Array(12)) , ivStr = Array.from(iv).map(b => String.fromCharCode(b)).join('')
, alg = { name: 'AES-GCM', iv }
, key = await crypto.subtle.importKey('raw', await hash(secret), alg, false, ['encrypt'])
, cipherBuffer = await crypto.subtle.encrypt(alg, key, encode(message)) , cipherArray = Array.from(new Uint8Array(cipherBuffer)) , cipherStr = cipherArray.map(byte => String.fromCharCode(byte)).join('')
return btoa(ivStr + cipherStr) } catch (_err) { throw new DarkflareError('crypto', 'CANNOT ENCRYPT MESSAGE') }}