Skip to content

Commit

Permalink
refactor: move base64url around
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Feb 23, 2025
1 parent 03d72c8 commit e1350ef
Show file tree
Hide file tree
Showing 20 changed files with 124 additions and 125 deletions.
14 changes: 7 additions & 7 deletions src/jwe/flattened/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import type * as types from '../../types.d.ts'
import { decode as base64url } from '../../lib/base64url.js'
import { decode as b64u } from '../../util/base64url.js'
import decrypt from '../../lib/decrypt.js'
import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'
import isDisjoint from '../../lib/is_disjoint.js'
Expand Down Expand Up @@ -122,7 +122,7 @@ export async function flattenedDecrypt(
let parsedProt!: types.JWEHeaderParameters
if (jwe.protected) {
try {
const protectedHeader = base64url(jwe.protected)
const protectedHeader = b64u(jwe.protected)
parsedProt = JSON.parse(decoder.decode(protectedHeader))
} catch {
throw new JWEInvalid('JWE Protected Header is invalid')
Expand Down Expand Up @@ -178,7 +178,7 @@ export async function flattenedDecrypt(
let encryptedKey!: Uint8Array
if (jwe.encrypted_key !== undefined) {
try {
encryptedKey = base64url(jwe.encrypted_key!)
encryptedKey = b64u(jwe.encrypted_key!)
} catch {
throw new JWEInvalid('Failed to base64url decode the encrypted_key')
}
Expand Down Expand Up @@ -213,14 +213,14 @@ export async function flattenedDecrypt(
let tag: Uint8Array | undefined
if (jwe.iv !== undefined) {
try {
iv = base64url(jwe.iv)
iv = b64u(jwe.iv)
} catch {
throw new JWEInvalid('Failed to base64url decode the iv')
}
}
if (jwe.tag !== undefined) {
try {
tag = base64url(jwe.tag)
tag = b64u(jwe.tag)
} catch {
throw new JWEInvalid('Failed to base64url decode the tag')
}
Expand All @@ -237,7 +237,7 @@ export async function flattenedDecrypt(

let ciphertext: Uint8Array
try {
ciphertext = base64url(jwe.ciphertext)
ciphertext = b64u(jwe.ciphertext)
} catch {
throw new JWEInvalid('Failed to base64url decode the ciphertext')
}
Expand All @@ -251,7 +251,7 @@ export async function flattenedDecrypt(

if (jwe.aad !== undefined) {
try {
result.additionalAuthenticatedData = base64url(jwe.aad!)
result.additionalAuthenticatedData = b64u(jwe.aad!)
} catch {
throw new JWEInvalid('Failed to base64url decode the aad')
}
Expand Down
14 changes: 7 additions & 7 deletions src/jwe/flattened/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @module
*/

import { encode as base64url } from '../../lib/base64url.js'
import { encode as b64u } from '../../util/base64url.js'
import { unprotected } from '../../lib/private_symbols.js'
import encrypt from '../../lib/encrypt.js'
import type * as types from '../../types.d.ts'
Expand Down Expand Up @@ -249,13 +249,13 @@ export class FlattenedEncrypt {
let protectedHeader: Uint8Array
let aadMember: string | undefined
if (this._protectedHeader) {
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)))
protectedHeader = encoder.encode(b64u(JSON.stringify(this._protectedHeader)))
} else {
protectedHeader = encoder.encode('')
}

if (this._aad) {
aadMember = base64url(this._aad)
aadMember = b64u(this._aad)
additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember))
} else {
additionalData = protectedHeader
Expand All @@ -270,19 +270,19 @@ export class FlattenedEncrypt {
)

const jwe: types.FlattenedJWE = {
ciphertext: base64url(ciphertext),
ciphertext: b64u(ciphertext),
}

if (iv) {
jwe.iv = base64url(iv)
jwe.iv = b64u(iv)
}

if (tag) {
jwe.tag = base64url(tag)
jwe.tag = b64u(tag)
}

if (encryptedKey) {
jwe.encrypted_key = base64url(encryptedKey)
jwe.encrypted_key = b64u(encryptedKey)
}

if (aadMember) {
Expand Down
4 changes: 2 additions & 2 deletions src/jwe/general/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'
import generateCek from '../../lib/cek.js'
import isDisjoint from '../../lib/is_disjoint.js'
import encryptKeyManagement from '../../lib/encrypt_key_management.js'
import { encode as base64url } from '../../lib/base64url.js'
import { encode as b64u } from '../../util/base64url.js'
import validateCrit from '../../lib/validate_crit.js'
import normalizeKey from '../../lib/normalize_key.js'
import checkKeyType from '../../lib/check_key_type.js'
Expand Down Expand Up @@ -301,7 +301,7 @@ export class GeneralEncrypt {

const k = await normalizeKey(recipient.key, alg)
const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, { p2c })
target.encrypted_key = base64url(encryptedKey!)
target.encrypted_key = b64u(encryptedKey!)
if (recipient.unprotectedHeader || parameters)
target.header = { ...recipient.unprotectedHeader, ...parameters }
}
Expand Down
4 changes: 2 additions & 2 deletions src/jwk/thumbprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import digest from '../lib/digest.js'
import { encode as base64url } from '../lib/base64url.js'
import { encode as b64u } from '../util/base64url.js'

import { JOSENotSupported, JWKInvalid } from '../util/errors.js'
import { encoder } from '../lib/buffer_utils.js'
Expand Down Expand Up @@ -97,7 +97,7 @@ export async function calculateJwkThumbprint(
}

const data = encoder.encode(JSON.stringify(components))
return base64url(await digest(digestAlgorithm, data))
return b64u(await digest(digestAlgorithm, data))
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/jws/flattened/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import type * as types from '../../types.d.ts'
import { encode as base64url } from '../../lib/base64url.js'
import { encode as b64u } from '../../util/base64url.js'
import sign from '../../lib/sign.js'

import isDisjoint from '../../lib/is_disjoint.js'
Expand Down Expand Up @@ -130,12 +130,12 @@ export class FlattenedSign {

let payload = this._payload
if (b64) {
payload = encoder.encode(base64url(payload))
payload = encoder.encode(b64u(payload))
}

let protectedHeader: Uint8Array
if (this._protectedHeader) {
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)))
protectedHeader = encoder.encode(b64u(JSON.stringify(this._protectedHeader)))
} else {
protectedHeader = encoder.encode('')
}
Expand All @@ -146,7 +146,7 @@ export class FlattenedSign {
const signature = await sign(alg, k, data)

const jws: types.FlattenedJWS = {
signature: base64url(signature),
signature: b64u(signature),
payload: '',
}

Expand Down
8 changes: 4 additions & 4 deletions src/jws/flattened/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import type * as types from '../../types.d.ts'
import { decode as base64url } from '../../lib/base64url.js'
import { decode as b64u } from '../../util/base64url.js'
import verify from '../../lib/verify.js'

import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'
Expand Down Expand Up @@ -106,7 +106,7 @@ export async function flattenedVerify(
let parsedProt: types.JWSHeaderParameters = {}
if (jws.protected) {
try {
const protectedHeader = base64url(jws.protected)
const protectedHeader = b64u(jws.protected)
parsedProt = JSON.parse(decoder.decode(protectedHeader))
} catch {
throw new JWSInvalid('JWS Protected Header is invalid')
Expand Down Expand Up @@ -176,7 +176,7 @@ export async function flattenedVerify(
)
let signature: Uint8Array
try {
signature = base64url(jws.signature)
signature = b64u(jws.signature)
} catch {
throw new JWSInvalid('Failed to base64url decode the signature')
}
Expand All @@ -191,7 +191,7 @@ export async function flattenedVerify(
let payload: Uint8Array
if (b64) {
try {
payload = base64url(jws.payload)
payload = b64u(jws.payload)
} catch {
throw new JWSInvalid('Failed to base64url decode the payload')
}
Expand Down
10 changes: 5 additions & 5 deletions src/jwt/unsecured.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @module
*/

import * as base64url from '../lib/base64url.js'
import * as b64u from '../util/base64url.js'

import type * as types from '../types.d.ts'
import { decoder } from '../lib/buffer_utils.js'
Expand Down Expand Up @@ -55,8 +55,8 @@ export interface UnsecuredResult<PayloadType = types.JWTPayload> {
export class UnsecuredJWT extends ProduceJWT {
/** Encodes the Unsecured JWT. */
encode(): string {
const header = base64url.encode(JSON.stringify({ alg: 'none' }))
const payload = base64url.encode(JSON.stringify(this._payload))
const header = b64u.encode(JSON.stringify({ alg: 'none' }))
const payload = b64u.encode(JSON.stringify(this._payload))

return `${header}.${payload}.`
}
Expand All @@ -82,15 +82,15 @@ export class UnsecuredJWT extends ProduceJWT {

let header: types.JWSHeaderParameters
try {
header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)))
header = JSON.parse(decoder.decode(b64u.decode(encodedHeader)))
if (header.alg !== 'none') throw new Error()
} catch {
throw new JWTInvalid('Invalid Unsecured JWT')
}

const payload = jwtPayload(
header,
base64url.decode(encodedPayload),
b64u.decode(encodedPayload),
options,
) as UnsecuredResult<PayloadType>['payload']

Expand Down
2 changes: 1 addition & 1 deletion src/key/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @module
*/

import { decode as decodeBase64URL } from '../lib/base64url.js'
import { decode as decodeBase64URL } from '../util/base64url.js'
import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js'
import toCryptoKey from '../lib/jwk_to_key.js'

Expand Down
6 changes: 3 additions & 3 deletions src/lib/aesgcmkw.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import encrypt from './encrypt.js'
import decrypt from './decrypt.js'
import { encode as base64url } from '../lib/base64url.js'
import { encode as b64u } from '../util/base64url.js'

export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint8Array) {
const jweAlgorithm = alg.slice(0, 7)
Expand All @@ -9,8 +9,8 @@ export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint

return {
encryptedKey: wrapped.ciphertext,
iv: base64url(wrapped.iv!),
tag: base64url(wrapped.tag!),
iv: b64u(wrapped.iv!),
tag: b64u(wrapped.tag!),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib/asn1.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type * as types from '../types.d.ts'
import invalidKeyInput from './invalid_key_input.js'
import { encodeBase64, decodeBase64 } from './base64url.js'
import { encodeBase64, decodeBase64 } from '../lib/base64.js'
import { JOSENotSupported } from '../util/errors.js'
import { isCryptoKey, isKeyObject } from './is_key_like.js'

Expand Down
30 changes: 30 additions & 0 deletions src/lib/base64.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export function encodeBase64(input: Uint8Array): string {
// @ts-ignore
if (Uint8Array.prototype.toBase64) {
// @ts-ignore
return input.toBase64()
}

const CHUNK_SIZE = 0x8000
const arr = []
for (let i = 0; i < input.length; i += CHUNK_SIZE) {
// @ts-expect-error
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)))
}
return btoa(arr.join(''))
}

export function decodeBase64(encoded: string): Uint8Array {
// @ts-ignore
if (Uint8Array.fromBase64) {
// @ts-ignore
return Uint8Array.fromBase64(encoded)
}

const binary = atob(encoded)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
}
70 changes: 0 additions & 70 deletions src/lib/base64url.ts

This file was deleted.

Loading

0 comments on commit e1350ef

Please sign in to comment.