Update code

This commit is contained in:
User
2026-03-12 12:47:56 +08:00
parent 92e7fc5bda
commit 9dab61345c
9383 changed files with 1463454 additions and 1 deletions

View File

@@ -0,0 +1,180 @@
import { decode as b64u } from '../../util/base64url.js';
import { decrypt } from '../../lib/decrypt.js';
import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import { isDisjoint } from '../../lib/is_disjoint.js';
import { isObject } from '../../lib/is_object.js';
import { decryptKeyManagement } from '../../lib/decrypt_key_management.js';
import { decoder, concat, encode } from '../../lib/buffer_utils.js';
import { generateCek } from '../../lib/cek.js';
import { validateCrit } from '../../lib/validate_crit.js';
import { validateAlgorithms } from '../../lib/validate_algorithms.js';
import { normalizeKey } from '../../lib/normalize_key.js';
import { checkKeyType } from '../../lib/check_key_type.js';
import { decompress } from '../../lib/deflate.js';
export async function flattenedDecrypt(jwe, key, options) {
if (!isObject(jwe)) {
throw new JWEInvalid('Flattened JWE must be an object');
}
if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
throw new JWEInvalid('JOSE Header missing');
}
if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
throw new JWEInvalid('JWE Initialization Vector incorrect type');
}
if (typeof jwe.ciphertext !== 'string') {
throw new JWEInvalid('JWE Ciphertext missing or incorrect type');
}
if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
throw new JWEInvalid('JWE Authentication Tag incorrect type');
}
if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
throw new JWEInvalid('JWE Protected Header incorrect type');
}
if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
throw new JWEInvalid('JWE Encrypted Key incorrect type');
}
if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
throw new JWEInvalid('JWE AAD incorrect type');
}
if (jwe.header !== undefined && !isObject(jwe.header)) {
throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');
}
if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
}
let parsedProt;
if (jwe.protected) {
try {
const protectedHeader = b64u(jwe.protected);
parsedProt = JSON.parse(decoder.decode(protectedHeader));
}
catch {
throw new JWEInvalid('JWE Protected Header is invalid');
}
}
if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
}
const joseHeader = {
...parsedProt,
...jwe.header,
...jwe.unprotected,
};
validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
}
if (joseHeader.zip !== undefined && !parsedProt?.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
}
const { alg, enc } = joseHeader;
if (typeof alg !== 'string' || !alg) {
throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
}
if (typeof enc !== 'string' || !enc) {
throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
}
const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);
const contentEncryptionAlgorithms = options &&
validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
}
let encryptedKey;
if (jwe.encrypted_key !== undefined) {
try {
encryptedKey = b64u(jwe.encrypted_key);
}
catch {
throw new JWEInvalid('Failed to base64url decode the encrypted_key');
}
}
let resolvedKey = false;
if (typeof key === 'function') {
key = await key(parsedProt, jwe);
resolvedKey = true;
}
checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt');
const k = await normalizeKey(key, alg);
let cek;
try {
cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
}
catch (err) {
if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
throw err;
}
cek = generateCek(enc);
}
let iv;
let tag;
if (jwe.iv !== undefined) {
try {
iv = b64u(jwe.iv);
}
catch {
throw new JWEInvalid('Failed to base64url decode the iv');
}
}
if (jwe.tag !== undefined) {
try {
tag = b64u(jwe.tag);
}
catch {
throw new JWEInvalid('Failed to base64url decode the tag');
}
}
const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array();
let additionalData;
if (jwe.aad !== undefined) {
additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad));
}
else {
additionalData = protectedHeader;
}
let ciphertext;
try {
ciphertext = b64u(jwe.ciphertext);
}
catch {
throw new JWEInvalid('Failed to base64url decode the ciphertext');
}
const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
const result = { plaintext };
if (joseHeader.zip === 'DEF') {
const maxDecompressedLength = options?.maxDecompressedLength ?? 250_000;
if (maxDecompressedLength === 0) {
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}
if (maxDecompressedLength !== Infinity &&
(!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {
throw new TypeError('maxDecompressedLength must be 0, a positive safe integer, or Infinity');
}
result.plaintext = await decompress(plaintext, maxDecompressedLength);
}
if (jwe.protected !== undefined) {
result.protectedHeader = parsedProt;
}
if (jwe.aad !== undefined) {
try {
result.additionalAuthenticatedData = b64u(jwe.aad);
}
catch {
throw new JWEInvalid('Failed to base64url decode the aad');
}
}
if (jwe.unprotected !== undefined) {
result.sharedUnprotectedHeader = jwe.unprotected;
}
if (jwe.header !== undefined) {
result.unprotectedHeader = jwe.header;
}
if (resolvedKey) {
return { ...result, key: k };
}
return result;
}

View File

@@ -0,0 +1,177 @@
import { encode as b64u } from '../../util/base64url.js';
import { unprotected } from '../../lib/private_symbols.js';
import { encrypt } from '../../lib/encrypt.js';
import { encryptKeyManagement } from '../../lib/encrypt_key_management.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import { isDisjoint } from '../../lib/is_disjoint.js';
import { concat, encode } from '../../lib/buffer_utils.js';
import { validateCrit } from '../../lib/validate_crit.js';
import { normalizeKey } from '../../lib/normalize_key.js';
import { checkKeyType } from '../../lib/check_key_type.js';
import { compress } from '../../lib/deflate.js';
export class FlattenedEncrypt {
#plaintext;
#protectedHeader;
#sharedUnprotectedHeader;
#unprotectedHeader;
#aad;
#cek;
#iv;
#keyManagementParameters;
constructor(plaintext) {
if (!(plaintext instanceof Uint8Array)) {
throw new TypeError('plaintext must be an instance of Uint8Array');
}
this.#plaintext = plaintext;
}
setKeyManagementParameters(parameters) {
if (this.#keyManagementParameters) {
throw new TypeError('setKeyManagementParameters can only be called once');
}
this.#keyManagementParameters = parameters;
return this;
}
setProtectedHeader(protectedHeader) {
if (this.#protectedHeader) {
throw new TypeError('setProtectedHeader can only be called once');
}
this.#protectedHeader = protectedHeader;
return this;
}
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
if (this.#sharedUnprotectedHeader) {
throw new TypeError('setSharedUnprotectedHeader can only be called once');
}
this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
return this;
}
setUnprotectedHeader(unprotectedHeader) {
if (this.#unprotectedHeader) {
throw new TypeError('setUnprotectedHeader can only be called once');
}
this.#unprotectedHeader = unprotectedHeader;
return this;
}
setAdditionalAuthenticatedData(aad) {
this.#aad = aad;
return this;
}
setContentEncryptionKey(cek) {
if (this.#cek) {
throw new TypeError('setContentEncryptionKey can only be called once');
}
this.#cek = cek;
return this;
}
setInitializationVector(iv) {
if (this.#iv) {
throw new TypeError('setInitializationVector can only be called once');
}
this.#iv = iv;
return this;
}
async encrypt(key, options) {
if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
}
if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
}
const joseHeader = {
...this.#protectedHeader,
...this.#unprotectedHeader,
...this.#sharedUnprotectedHeader,
};
validateCrit(JWEInvalid, new Map(), options?.crit, this.#protectedHeader, joseHeader);
if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
}
if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
}
const { alg, enc } = joseHeader;
if (typeof alg !== 'string' || !alg) {
throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
}
if (typeof enc !== 'string' || !enc) {
throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
}
let encryptedKey;
if (this.#cek && (alg === 'dir' || alg === 'ECDH-ES')) {
throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
}
checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt');
let cek;
{
let parameters;
const k = await normalizeKey(key, alg);
({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
if (parameters) {
if (options && unprotected in options) {
if (!this.#unprotectedHeader) {
this.setUnprotectedHeader(parameters);
}
else {
this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };
}
}
else if (!this.#protectedHeader) {
this.setProtectedHeader(parameters);
}
else {
this.#protectedHeader = { ...this.#protectedHeader, ...parameters };
}
}
}
let additionalData;
let protectedHeaderS;
let protectedHeaderB;
let aadMember;
if (this.#protectedHeader) {
protectedHeaderS = b64u(JSON.stringify(this.#protectedHeader));
protectedHeaderB = encode(protectedHeaderS);
}
else {
protectedHeaderS = '';
protectedHeaderB = new Uint8Array();
}
if (this.#aad) {
aadMember = b64u(this.#aad);
const aadMemberBytes = encode(aadMember);
additionalData = concat(protectedHeaderB, encode('.'), aadMemberBytes);
}
else {
additionalData = protectedHeaderB;
}
let plaintext = this.#plaintext;
if (joseHeader.zip === 'DEF') {
plaintext = await compress(plaintext);
}
const { ciphertext, tag, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);
const jwe = {
ciphertext: b64u(ciphertext),
};
if (iv) {
jwe.iv = b64u(iv);
}
if (tag) {
jwe.tag = b64u(tag);
}
if (encryptedKey) {
jwe.encrypted_key = b64u(encryptedKey);
}
if (aadMember) {
jwe.aad = aadMember;
}
if (this.#protectedHeader) {
jwe.protected = protectedHeaderS;
}
if (this.#sharedUnprotectedHeader) {
jwe.unprotected = this.#sharedUnprotectedHeader;
}
if (this.#unprotectedHeader) {
jwe.header = this.#unprotectedHeader;
}
return jwe;
}
}