Skip to content

Instantly share code, notes, and snippets.

@bshambaugh
Created December 1, 2023 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bshambaugh/e4d2e4926e3d6d1f800864bee58d7127 to your computer and use it in GitHub Desktop.
Save bshambaugh/e4d2e4926e3d6d1f800864bee58d7127 to your computer and use it in GitHub Desktop.
why does auth encrypter with dir have a key wrapper?
https://github.com/decentralized-identity/veramo/blob/next/packages/did-comm/src/encryption/a256kw-encrypters.ts#L144-L157
export function a256gcmAuthEncrypterEcdh1PuV3x25519WithA256KW(
recipientPublicKey: Uint8Array,
senderSecret: Uint8Array | ECDH,
options: Partial<AuthEncryptParams> = {},
): Encrypter {
return createFullEncrypter(
recipientPublicKey,
senderSecret,
options,
{ createKek: createX25519Ecdh1PUv3Kek, alg: 'ECDH-1PU' },
a256KeyWrapper,
{ from: (cek: Uint8Array) => a256gcmDirEncrypter(cek), enc: 'A256GCM' },
)
}
https://github.com/decentralized-identity/veramo/blob/next/packages/did-comm/src/encryption/a256gcm-dir.ts#L8-L42
function createA256GCMEncrypter(
key: Uint8Array,
): (cleartext: Uint8Array, aad?: Uint8Array) => EncryptionResult {
const blockcipher = new AES(key)
const cipher = new GCM(blockcipher)
return (cleartext: Uint8Array, aad?: Uint8Array) => {
const iv = randomBytes(cipher.nonceLength)
const sealed = cipher.seal(iv, cleartext, aad)
return {
ciphertext: sealed.subarray(0, sealed.length - cipher.tagLength),
tag: sealed.subarray(sealed.length - cipher.tagLength),
iv,
}
}
}
export function a256gcmDirEncrypter(key: Uint8Array): Encrypter {
const enc = 'A256GCM'
const alg = 'dir'
async function encrypt(
cleartext: Uint8Array,
protectedHeader: ProtectedHeader = {},
aad?: Uint8Array,
): Promise<EncryptionResult> {
const protHeader = encodeBase64url(JSON.stringify(Object.assign({ alg }, protectedHeader, { enc })))
const encodedAad = fromString(aad ? `${protHeader}.${bytesToBase64url(aad)}` : protHeader, 'utf-8')
return {
...createA256GCMEncrypter(key)(cleartext, encodedAad),
protectedHeader: protHeader,
}
}
return { alg, enc, encrypt }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment