import { importAesKey } from './importAesKey' ; import { Buffer , crypto , random , TextEncoder } from './shims' ; const DEFAULT_OPTS = { encode : 'base64' , name : 'AES-GCM' } ; export async function encrypt ( msg , key , opt = DEFAULT_OPTS ) { const rand = { s : random ( 9 ) , iv : random ( 15 ) } ; const ct = await crypto . subtle . encrypt ( { iv : new Uint8Array ( rand . iv ) , name : opt . name || DEFAULT_OPTS . name || 'AES-GCM' } , await importAesKey ( key , rand . s , opt ) , new TextEncoder ( ) . encode ( msg ) ) ; const encoding = opt . encode || DEFAULT_OPTS . encode ; const r = { ct : Buffer . from ( ct , 'binary' ) . toString ( encoding ) , iv : rand . iv . toString ( encoding ) , s : rand . s . toString ( encoding ) } ; if ( opt . raw ) { return r ; } return 'SEA' + JSON . stringify ( r ) ; }