Skip to main content
Go to Latest
File
export async function encrypt(str: string, secret: string) { const iv = crypto.getRandomValues(new Uint8Array(12))
, ivString = Array.from(iv).map(byte => String.fromCharCode(byte)).join('')
, algorithm = { name: 'AES-GCM', iv }
, key = await crypto.subtle.importKey( 'raw', await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret)), algorithm, false, ['encrypt'] )
, cipherBuffer = await crypto.subtle.encrypt( algorithm, key, new TextEncoder().encode(str) )
, cipherArray = Array.from(new Uint8Array(cipherBuffer))
, cipherString = cipherArray.map(byte => String.fromCharCode(byte)).join('')
return btoa(ivString + cipherString)}