Skip to content

Commit

Permalink
fix(jwk-webcrypto): prefer jwk algorithms that yield smaller signatures
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Apr 12, 2024
1 parent 718b387 commit 5241de0
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion packages/jwk-webcrypto/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ export async function generateKeypair(
extractable = false,
): Promise<CryptoKeyPair> {
const errors: unknown[] = []
for (const alg of algs) {
const algsSorted = Array.from(algs).sort(compareAlgos)
for (const alg of algsSorted) {
try {
return await crypto.subtle.generateKey(
toSubtleAlgorithm(alg),
Expand All @@ -140,3 +141,29 @@ export async function generateKeypair(

throw new AggregateError(errors, 'Failed to generate keypair')
}

/**
* 256K > ES (256 > 384 > 512) > PS (256 > 384 > 512) > RS (256 > 384 > 512) > other (in original order)
*/
function compareAlgos(a: string, b: string): number {
if (a === 'ES256K') return -1
if (b === 'ES256K') return 1

for (const prefix of ['ES', 'PS', 'RS']) {
if (a.startsWith(prefix)) {
if (b.startsWith(prefix)) {
const aLen = parseInt(a.slice(2, 5))
const bLen = parseInt(b.slice(2, 5))

// Prefer shorter key lengths
return aLen - bLen
}
return -1
} else if (b.startsWith(prefix)) {
return 1
}
}

// Don't know how to compare, keep original order
return 0
}

0 comments on commit 5241de0

Please sign in to comment.