A library to faciliate using data encryption keys as well as do some light encryption/decryption.
import{randomBytes,randomUUID}from'crypto'import{tmpdir}from'os'import{FileKeyStore,IKeyStore}from'@bryopsida/key-store'import{IDataEncryptor,EncryptOpts,Crypto}from'../src/crypto'import{writeFile}from'fs/promises'import{describe,expect,it,beforeEach}from'@jest/globals'//setup a key store, in this case on the file systemconstkey=randomBytes(32)constsalt=randomBytes(16)constcontext=randomBytes(32)constmasterKey=randomBytes(32).toString('base64')constmasterSalt=randomBytes(16).toString('base64')constmasterKeyFile=randomUUID()constmasterSaltFile=randomUUID()conststoreDir=tmpdir()constkeyStoreDir=randomUUID()awaitwriteFile(`${storeDir}/${masterKeyFile}`,masterKey)awaitwriteFile(`${storeDir}/${masterSaltFile}`,masterSalt)keyStore=newFileKeyStore(`${storeDir}/${keyStoreDir}`,()=>Promise.resolve(key),()=>Promise.resolve(salt),()=>Promise.resolve(context))// now we can make the crypto instancecrypto=newCrypto(keyStore,`${storeDir}/${masterKeyFile}`,`${storeDir}/${masterSaltFile}`)// an example of encrypting to a encoded value and decryptingit('can encrypt and decrypted encoded text',async()=>{constrootKeyId=awaitcrypto.generateRootKey(32,'encoded-test')constdek=awaitcrypto.generateDataEncKey(32,rootKeyId,'encoded-test','dek')constencryptedData=awaitcrypto.encryptAndEncode({plaintext: Buffer.from('test-data'),keyId: dek,
rootKeyId,rootKeyContext: 'encoded-test',dekContext: 'dek',context: Buffer.from('data-context'),})constplainText=(awaitcrypto.decryptEncoded(encryptedData,'encoded-test','dek','data-context')).toString('utf8')expect(plainText).toEqual('test-data')})