Skip to content

Commit a44c2ec

Browse files
committed
refactor: faster path for symmetric key checks
1 parent 94fdde7 commit a44c2ec

1 file changed

Lines changed: 10 additions & 15 deletions

File tree

src/lib/check_key_type.ts

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,6 @@ const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage) => {
122122
throw new TypeError(
123123
`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`,
124124
)
125-
default:
126-
break
127125
}
128126
}
129127

@@ -137,25 +135,22 @@ const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage) => {
137135
throw new TypeError(
138136
`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`,
139137
)
140-
default:
141-
break
142138
}
143139
}
144140
}
145141

146142
type Usage = 'sign' | 'verify' | 'encrypt' | 'decrypt'
147143

148144
export default (alg: string, key: unknown, usage: Usage): void => {
149-
const symmetric =
150-
alg.startsWith('HS') ||
151-
alg === 'dir' ||
152-
alg.startsWith('PBES2') ||
153-
/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) ||
154-
/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg)
155-
156-
if (symmetric) {
157-
symmetricTypeCheck(alg, key, usage)
158-
} else {
159-
asymmetricTypeCheck(alg, key, usage)
145+
switch (alg.substring(0, 2)) {
146+
case 'A1': // A128.+, A192.+
147+
case 'A2': // A256.+
148+
case 'di': // dir
149+
case 'HS': // HS\d{3}
150+
case 'PB': // PBES2.+
151+
symmetricTypeCheck(alg, key, usage)
152+
break
153+
default:
154+
asymmetricTypeCheck(alg, key, usage)
160155
}
161156
}

0 commit comments

Comments
 (0)