Skip to content

Commit

Permalink
Merge 27bc16f into 2421b28
Browse files Browse the repository at this point in the history
  • Loading branch information
frankhinek authored Nov 9, 2023
2 parents 2421b28 + 27bc16f commit e7f1e8d
Show file tree
Hide file tree
Showing 4 changed files with 734 additions and 10 deletions.
46 changes: 36 additions & 10 deletions packages/crypto/src/jose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,41 @@ const joseToMulticodecMapping: { [key: string]: string } = {

export class Jose {

/**
* Canonicalizes a given object according to RFC 8785 (https://tools.ietf.org/html/rfc8785),
* which describes JSON Canonicalization Scheme (JCS). This function sorts the keys of the
* object and its nested objects alphabetically and then returns a stringified version of it.
* This method handles nested objects, array values, and null values appropriately.
*
* @param obj - The object to canonicalize.
* @returns The stringified version of the input object with its keys sorted alphabetically
* per RFC 8785.
*/
public static canonicalize(obj: { [key: string]: any }): string {
/**
* Recursively sorts the keys of an object.
*
* @param obj - The object whose keys are to be sorted.
* @returns A new object with sorted keys.
*/
const sortObjKeys = (obj: { [key: string]: any }): { [key: string]: any } => {
if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {
const sortedKeys = Object.keys(obj).sort();
const sortedObj: { [key: string]: any } = {};
for (const key of sortedKeys) {
// Recursively sort keys of nested objects.
sortedObj[key] = sortObjKeys(obj[key]);
}
return sortedObj;
}
return obj;
};

// Stringify and return the final sorted object.
const sortedObj = sortObjKeys(obj);
return JSON.stringify(sortedObj);
}

public static async cryptoKeyToJwk(options: {
key: Web5Crypto.CryptoKey,
}): Promise<JsonWebKey> {
Expand Down Expand Up @@ -897,7 +932,7 @@ export class Jose {
params.push(options.namedCurve);

/**
* All symmetric encryption (AES) WebCrypto algorithms
* AES symmetric encryption WebCrypto algorithms
* set a value for the "length" parameter.
*/
} else if ('length' in options && options.length !== undefined) {
Expand All @@ -923,15 +958,6 @@ export class Jose {

return { ...jose };
}

private static canonicalize(obj: { [key: string]: any }): string {
const sortedKeys = Object.keys(obj).sort();
const sortedObj = sortedKeys.reduce<{ [key: string]: any }>((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
return JSON.stringify(sortedObj);
}
}

type Constructable = new (...args: any[]) => object;
Expand Down
Loading

0 comments on commit e7f1e8d

Please sign in to comment.