import { EncryptManifestList , KeyList , KeyInfoTuple , } from '@aws-crypto/integration-vectors' ; import { randomBytes } from 'crypto' ; import { AlgorithmSuiteIdentifier , EncryptionContext , } from '@aws-crypto/client-browser' ; import { URL } from 'url' ; import { readFileSync , writeFileSync } from 'fs' ; import got from 'got' ; export async function buildEncryptFixtures ( fixtures , manifestFile , keyFile , testName ? , slice ? ) { const [ start = 0 , end = 9999 ] = ( slice || '' ) . split ( ':' ) . map ( ( n ) => parseInt ( n , 10 ) ) ; const { tests , plaintexts } = await getParsedJSON ( manifestFile ) ; const { keys } = await getParsedJSON ( keyFile ) ; const plaintextBytes = { } ; Object . keys ( plaintexts ) . forEach ( ( name ) => { plaintextBytes [ name ] = randomBytes ( 10 ) . toString ( 'base64' ) ; } ) ; const testNames = [ ] ; let count = 0 ; for ( const [ name , testInfo ] of Object . entries ( tests ) ) { count += 1 ; if ( testName ) { if ( name !== testName ) continue ; } if ( slice ) { if ( start >= count ) continue ; if ( count > end ) continue ; } testNames . push ( name ) ; const { plaintext , 'master-keys' : masterKeys , algorithm , 'frame-size' : frameLength , 'encryption-context' : encryptionContext , } = testInfo ; const keysInfo = masterKeys . map ( ( keyInfo ) => { const key = keys [ keyInfo . key ] ; if ( ! key ) throw new Error ( `no key for ${ name }` ) ; return [ keyInfo , key ] as KeyInfoTuple ; } ) ; const suiteId = parseInt ( algorithm , 16 ) as AlgorithmSuiteIdentifier ; const test = { name , keysInfo , plainTextData : plaintextBytes [ plaintext ] , encryptOp : { suiteId , frameLength , encryptionContext } , } ; writeFileSync ( `${ fixtures }/${ name }.json` , JSON . stringify ( test ) ) ; } writeFileSync ( `${ fixtures }/encrypt_tests.json` , JSON . stringify ( testNames ) ) ; } export interface EncryptTestVectorInfo { name : string ; keysInfo : KeyInfoTuple [ ] ; plainTextData : string ; encryptOp : { suiteId : AlgorithmSuiteIdentifier ; frameLength : number ; encryptionContext : EncryptionContext ; } ; } async function getParsedJSON ( thing ) { try { const url = new URL ( thing ) ; if ( url . protocol === 'file:' ) { return jsonAtPath ( thing ) ; } else { return jsonAtUrl ( url ) ; } } catch ( ex ) { return jsonAtPath ( thing ) ; } } async function jsonAtUrl ( url ) { const { body } = await got ( url ) ; return JSON . parse ( body ) ; } function jsonAtPath ( path ) { const json = readFileSync ( path , { encoding : 'utf-8' } ) ; return JSON . parse ( json ) ; }