jose/lib/help/base64url.js
Filip Skokan 5b53cb0155 fix: limit calculation of missing RSA private components
- this deprecates the use of `JWK.importKey` in favor of
`JWK.asKey`
- this deprecates the use of `JWKS.KeyStore.fromJWKS` in favor of
`JWKS.asKeyStore`

Both `JWK.importKey` and `JWKS.KeyStore.fromJWKS` could have resulted
in the process getting blocked when large bitsize RSA private keys
were missing their components and could also result in an endless
calculation loop when the private key's private exponent was outright
invalid or tampered with.

The new methods still allow to import private RSA keys with these
optimization key parameters missing but its disabled by default and one
should choose to enable it when working with keys from trusted sources

It is recommended not to use @panva/jose versions with this feature in
its original on-by-default form - v1.1.0 and v1.2.0 These will
2019-06-20 23:32:13 +02:00

57 lines
1.4 KiB
JavaScript

const b64uRegExp = /^[a-zA-Z0-9_-]*$/
const fromBase64 = (base64) => {
return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}
const toBase64 = (base64url) => {
return base64url.replace(/-/g, '+').replace(/_/g, '/')
}
const encode = (input, encoding = 'utf8') => {
return fromBase64(Buffer.from(input, encoding).toString('base64'))
}
const encodeBuffer = (buf) => {
return fromBase64(buf.toString('base64'))
}
const decode = (input) => {
if (!b64uRegExp.test(input)) {
throw new TypeError('input is not a valid base64url encoded string')
}
return Buffer.from(toBase64(input), 'base64').toString('utf8')
}
const decodeToBuffer = (input) => {
if (!b64uRegExp.test(input)) {
throw new TypeError('input is not a valid base64url encoded string')
}
return Buffer.from(toBase64(input), 'base64')
}
const b64uJSON = {
encode: (input) => {
return encode(JSON.stringify(input))
},
decode: (input) => {
return JSON.parse(decode(input))
}
}
b64uJSON.decode.try = (input) => {
try {
return b64uJSON.decode(input)
} catch (err) {
return decode(input)
}
}
const encodeBN = (bn) => encodeBuffer(bn.toBuffer())
module.exports.decode = decode
module.exports.decodeToBuffer = decodeToBuffer
module.exports.encode = encode
module.exports.encodeBuffer = encodeBuffer
module.exports.JSON = b64uJSON
module.exports.encodeBN = encodeBN