-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
check_cek_length.ts
45 lines (40 loc) · 1.23 KB
/
check_cek_length.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { JWEInvalid, JOSENotSupported } from '../../util/errors.js'
import { isCryptoKey } from './webcrypto.js'
const checkCekLength = (enc: string, cek: Uint8Array | CryptoKey) => {
let expected: number
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
expected = parseInt(enc.substr(-3), 10)
if (!(cek instanceof Uint8Array)) {
throw new TypeError(`${enc} content encryption requires Uint8Array as key input`)
}
break
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
expected = parseInt(enc.substr(1, 3), 10)
break
default:
throw new JOSENotSupported(
`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`,
)
}
if (cek instanceof Uint8Array) {
if (cek.length << 3 !== expected) {
throw new JWEInvalid('Invalid Content Encryption Key length')
}
return
}
// CryptoKey
if (isCryptoKey(cek)) {
const { length } = <AesKeyAlgorithm>cek.algorithm
if (length !== expected) {
throw new JWEInvalid('Invalid Content Encryption Key length')
}
return
}
throw new TypeError('Invalid Content Encryption Key type')
}
export default checkCekLength