did-jwt
Version:
Library for Signing and Verifying JWTs that use DIDs as issuers and JWEs that use DIDs as recipients
41 lines • 1.48 kB
JavaScript
import { bytesToBase64url, encodeBase64url, stringToBytes } from '../util.js';
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { randomBytes } from '@noble/hashes/utils.js';
export function xc20pEncrypter(key) {
return (cleartext, aad) => {
const iv = randomBytes(24);
const cipher = xchacha20poly1305(key, iv, aad);
const sealed = cipher.encrypt(cleartext);
return {
ciphertext: sealed.subarray(0, sealed.length - 16),
tag: sealed.subarray(sealed.length - 16),
iv,
};
};
}
export function xc20pDirEncrypter(key) {
const xc20pEncrypt = xc20pEncrypter(key);
const enc = 'XC20P';
const alg = 'dir';
async function encrypt(cleartext, protectedHeader = {}, aad) {
const protHeader = encodeBase64url(JSON.stringify(Object.assign({ alg }, protectedHeader, { enc })));
const encodedAad = stringToBytes(aad ? `${protHeader}.${bytesToBase64url(aad)}` : protHeader);
return {
...xc20pEncrypt(cleartext, encodedAad),
protectedHeader: protHeader,
};
}
return { alg, enc, encrypt };
}
export function xc20pDirDecrypter(key) {
async function decrypt(sealed, iv, aad) {
try {
return xchacha20poly1305(key, iv, aad).decrypt(sealed);
}
catch {
return null;
}
}
return { alg: 'dir', enc: 'XC20P', decrypt };
}
//# sourceMappingURL=xc20pDir.js.map