Skip to content

Commit

Permalink
fix: use raw asn1js int value to improve performance (#2788)
Browse files Browse the repository at this point in the history
When converting an asn1js Integer to a base64url encoded string,
use the raw byte value instead of converting it to a string, then
a bigint, then bytes.
  • Loading branch information
achingbrain authored Oct 28, 2024
1 parent d34642d commit c4399dc
Showing 1 changed file with 16 additions and 27 deletions.
43 changes: 16 additions & 27 deletions packages/crypto/src/keys/rsa/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ export function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {
const values: asn1js.Integer[] = result.valueBlock.value

const key = {
n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),
e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),
d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),
p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),
q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),
dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),
dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),
qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),
n: asn1jsIntegerToBase64(values[1]),
e: asn1jsIntegerToBase64(values[2]),
d: asn1jsIntegerToBase64(values[3]),
p: asn1jsIntegerToBase64(values[4]),
q: asn1jsIntegerToBase64(values[5]),
dp: asn1jsIntegerToBase64(values[6]),
dq: asn1jsIntegerToBase64(values[7]),
qi: asn1jsIntegerToBase64(values[8]),
kty: 'RSA',
alg: 'RS256'
}
Expand Down Expand Up @@ -78,8 +78,8 @@ export function pkixToJwk (bytes: Uint8Array): JsonWebKey {

return {
kty: 'RSA',
n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),
e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')
n: asn1jsIntegerToBase64(values[0]),
e: asn1jsIntegerToBase64(values[1])
}
}

Expand Down Expand Up @@ -120,26 +120,15 @@ export function jwkToPkix (jwk: JsonWebKey): Uint8Array {
return new Uint8Array(der, 0, der.byteLength)
}

function bnToBuf (bn: bigint): Uint8Array {
let hex = bn.toString(16)
function asn1jsIntegerToBase64 (int: asn1js.Integer): string {
let buf = int.valueBlock.valueHexView

if (hex.length % 2 > 0) {
hex = `0${hex}`
// chrome rejects values with leading 0s
while (buf[0] === 0) {
buf = buf.subarray(1)
}

const len = hex.length / 2
const u8 = new Uint8Array(len)

let i = 0
let j = 0

while (i < len) {
u8[i] = parseInt(hex.slice(j, j + 2), 16)
i += 1
j += 2
}

return u8
return uint8ArrayToString(buf, 'base64url')
}

function bufToBn (u8: Uint8Array): bigint {
Expand Down

0 comments on commit c4399dc

Please sign in to comment.