noble-curves-extended
Version:
This project extends @noble/curves to allow randomBytes to be specified externally
1,641 lines • 108 kB
JavaScript
import { numberToBytesLE as zr, bytesToNumberLE as qe, ensureBytes as Xe } from "@noble/curves/abstract/utils";
import { randomBytes as Yr, concatBytes as Qr } from "@noble/hashes/utils";
import { mod as I, Field as q, getMinHashLength as jr, mapHashToField as en, pow2 as b, isNegativeLE as tn } from "@noble/curves/abstract/modular";
import { sha512 as st, sha384 as rn } from "@noble/hashes/sha512";
import { twistedEdwards as nn } from "@noble/curves/abstract/edwards";
import { hmac as sn } from "@noble/hashes/hmac";
import { weierstrass as on } from "@noble/curves/abstract/weierstrass";
import { sha256 as Ue } from "@noble/hashes/sha256";
import { compareUint8Arrays as ne, isUint8Array as ie, ensureUint8Array as se, encodeBase64Url as O, decodeBase64Url as $, decodeHex as fn } from "u8a-utils";
const cn = /* @__PURE__ */ BigInt(0), xe = (i) => typeof i == "bigint" && cn <= i;
function an(i, e, t) {
return xe(i) && xe(e) && xe(t) && e <= i && i < t;
}
function Ze(i, e, t, r) {
if (!an(e, t, r))
throw new Error(
"expected valid " + i + ": " + t + " <= n < " + r + ", got " + e
);
}
function ln(i, e, t = {}) {
if (!i || typeof i != "object")
throw new Error("expected valid options object");
function r(n, s, o) {
const f = i[n];
if (o && f === void 0) return;
const c = typeof f;
if (c !== s || f === null)
throw new Error(
`param "${n}" is invalid: expected ${s}, got ${c}`
);
}
Object.entries(e).forEach(([n, s]) => r(n, s, !1)), Object.entries(t).forEach(([n, s]) => r(n, s, !0));
}
const j = BigInt(0), K = BigInt(1), le = BigInt(2);
function un(i) {
return ln(i, {
adjustScalarBytes: "function",
powPminus2: "function"
}), Object.freeze({ ...i });
}
function hn(i) {
const e = un(i), { P: t, type: r, adjustScalarBytes: n, powPminus2: s, randomBytes: o } = e, f = r === "x25519";
if (!f && r !== "x448") throw new Error("invalid type");
const c = o || Yr, u = f ? 255 : 448, h = f ? 32 : 56, a = BigInt(f ? 9 : 5), d = BigInt(f ? 121665 : 39081), v = f ? le ** BigInt(254) : le ** BigInt(447), p = f ? BigInt(8) * le ** BigInt(251) - K : BigInt(4) * le ** BigInt(445) - K, L = v + p + K, y = (m) => I(m, t), z = fe(a);
function fe(m) {
return zr(y(m), h);
}
function be(m) {
const E = Xe("u coordinate", m, h);
return f && (E[31] &= 127), y(qe(E));
}
function Be(m) {
return qe(
n(Xe("scalar", m, h))
);
}
function Y(m, E) {
const U = Wr(be(E), Be(m));
if (U === j) throw new Error("invalid private or public key received");
return fe(U);
}
function Q(m) {
return Y(m, z);
}
function ce(m, E, U) {
const ae = y(m * (E - U));
return E = y(E - ae), U = y(U + ae), { x_2: E, x_3: U };
}
function Wr(m, E) {
Ze("u", m, j, t), Ze("scalar", E, v, L);
const U = E, ae = m;
let R = K, H = j, M = m, F = K, G = j;
for (let ye = BigInt(u - 1); ye >= j; ye--) {
const $e = U >> ye & K;
G ^= $e, { x_2: R, x_3: M } = ce(G, R, M), { x_2: H, x_3: F } = ce(G, H, F), G = $e;
const me = R + H, ke = y(me * me), Ee = R - H, De = y(Ee * Ee), Pe = ke - De, Xr = M + F, Zr = M - F, Je = y(Zr * me), Ge = y(Xr * Ee), Ke = Je + Ge, We = Je - Ge;
M = y(Ke * Ke), F = y(ae * y(We * We)), R = y(ke * De), H = y(Pe * (ke + y(d * Pe)));
}
({ x_2: R, x_3: M } = ce(G, R, M)), { x_2: H, x_3: F } = ce(G, H, F);
const qr = s(H);
return y(R * qr);
}
return {
CURVE: e,
scalarMult: Y,
scalarMultBase: Q,
getSharedSecret: (m, E) => Y(m, E),
getPublicKey: (m) => Q(m),
utils: { randomPrivateKey: () => c(h) },
GuBytes: z.slice()
};
}
const ze = q(
BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")
), Di = (i) => ({
utils: {
randomPrivateKey: () => {
const t = jr(ze.ORDER);
return en(i(t), ze.ORDER);
}
}
}), dn = BigInt(1), Ye = BigInt(2), gn = BigInt(5), wn = BigInt(8), oe = {
p: BigInt(
"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"
),
n: BigInt(
"0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"
),
h: wn,
a: BigInt(
"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"
),
d: BigInt(
"0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"
),
Gx: BigInt(
"0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"
),
Gy: BigInt(
"0x6666666666666666666666666666666666666666666666666666666666666658"
)
};
function ot(i) {
const e = BigInt(10), t = BigInt(20), r = BigInt(40), n = BigInt(80), s = oe.p, f = i * i % s * i % s, c = b(f, Ye, s) * f % s, u = b(c, dn, s) * i % s, h = b(u, gn, s) * u % s, a = b(h, e, s) * h % s, d = b(a, t, s) * a % s, v = b(d, r, s) * d % s, p = b(v, n, s) * v % s, L = b(p, n, s) * v % s, y = b(L, e, s) * h % s;
return { pow_p_5_8: b(y, Ye, s) * i % s, b2: f };
}
function ft(i) {
return i[0] &= 248, i[31] &= 127, i[31] |= 64, i;
}
const Qe = /* @__PURE__ */ BigInt(
"19681161376707505956807079304988542015446066515923890162744021073123829784752"
);
function vn(i, e) {
const t = oe.p, r = I(e * e * e, t), n = I(r * r * e, t), s = ot(i * n).pow_p_5_8;
let o = I(i * r * s, t);
const f = I(e * o * o, t), c = o, u = I(o * Qe, t), h = f === i, a = f === I(-i, t), d = f === I(-i * Qe, t);
return h && (o = c), (a || d) && (o = u), tn(o, t) && (o = I(-o, t)), { isValid: h || a, value: o };
}
const bn = q(oe.p, void 0, !0), Bn = {
...oe,
Fp: bn,
hash: st,
adjustScalarBytes: ft,
// dom2
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
// Constant-time, u/√v
uvRatio: vn
}, yn = (i) => nn({
...Bn,
randomBytes: i
}), Pi = ["Ed25519"], mn = BigInt(3), kn = (i) => /* @__PURE__ */ (() => {
const e = oe.p;
return hn({
P: e,
type: "x25519",
powPminus2: (t) => {
const { pow_p_5_8: r, b2: n } = ot(t);
return I(b(r, mn, e) * n, e);
},
adjustScalarBytes: ft,
randomBytes: i
});
})(), Ji = ["X25519"], En = (i) => (e, ...t) => sn(i, e, Qr(...t));
function ge(i, e, t) {
return on({
...i,
hash: e,
randomBytes: t,
hmac: En(e)
});
}
const ct = (i, e) => {
if (e.length == i.CURVE.nByteLength * 2)
return i.Signature.fromCompact(e);
if (e.length == i.CURVE.nByteLength * 2 + 1) {
const t = e[e.length - 1], r = e.slice(0, -1);
return i.Signature.fromCompact(r).addRecoveryBit(t);
}
throw new Error("Invalid raw signature");
}, at = {
p: BigInt(
"0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"
),
n: BigInt(
"0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"
),
h: BigInt(1),
a: BigInt(
"0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"
),
b: BigInt(
"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"
),
Gx: BigInt(
"0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"
),
Gy: BigInt(
"0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
)
}, xn = q(at.p), pn = (i) => ge(
{ ...at, Fp: xn, lowS: !1 },
Ue,
i
), lt = {
p: BigInt(
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"
),
n: BigInt(
"0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"
),
h: BigInt(1),
a: BigInt(
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"
),
b: BigInt(
"0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"
),
Gx: BigInt(
"0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"
),
Gy: BigInt(
"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"
)
}, Sn = q(lt.p), An = (i) => ge(
{ ...lt, Fp: Sn, lowS: !1 },
rn,
i
), ut = {
p: BigInt(
"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
),
n: BigInt(
"0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"
),
h: BigInt(1),
a: BigInt(
"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"
),
b: BigInt(
"0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"
),
Gx: BigInt(
"0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"
),
Gy: BigInt(
"0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"
)
}, In = q(ut.p), Nn = (i) => ge(
{
...ut,
Fp: In,
lowS: !1,
allowedPrivateKeyLengths: [130, 131, 132]
},
st,
i
), ue = {
p: BigInt(
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
),
n: BigInt(
"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
),
h: BigInt(1),
a: BigInt(0),
b: BigInt(7),
Gx: BigInt(
"0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
),
Gy: BigInt(
"0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
)
}, Vn = BigInt(1), Se = BigInt(2), je = (i, e) => (i + e / Se) / e;
function Un(i) {
const e = ue.p, t = BigInt(3), r = BigInt(6), n = BigInt(11), s = BigInt(22), o = BigInt(23), f = BigInt(44), c = BigInt(88), u = i * i * i % e, h = u * u * i % e, a = b(h, t, e) * h % e, d = b(a, t, e) * h % e, v = b(d, Se, e) * u % e, p = b(v, n, e) * v % e, L = b(p, s, e) * p % e, y = b(L, f, e) * L % e, z = b(y, c, e) * y % e, fe = b(z, f, e) * L % e, be = b(fe, t, e) * h % e, Be = b(be, o, e) * p % e, Y = b(Be, r, e) * u % e, Q = b(Y, Se, e);
if (!Ae.eql(Ae.sqr(Q), i)) throw new Error("Cannot find square root");
return Q;
}
const Ae = q(ue.p, void 0, void 0, { sqrt: Un }), Cn = (i) => ge(
{
...ue,
Fp: Ae,
lowS: !0,
// Allow only low-S signatures by default in sign() and verify()
endo: {
// Endomorphism, see above
beta: BigInt(
"0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"
),
splitScalar: (e) => {
const t = ue.n, r = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), n = -Vn * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), s = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), o = r, f = BigInt("0x100000000000000000000000000000000"), c = je(o * e, t), u = je(-n * e, t);
let h = I(e - c * r - u * s, t), a = I(-c * n - u * o, t);
const d = h > f, v = a > f;
if (d && (h = t - h), v && (a = t - a), h > f || a > f)
throw new Error("splitScalar: Endomorphism failed, k=" + e);
return { k1neg: d, k1: h, k2neg: v, k2: a };
}
}
},
Ue,
i
), Tn = (i) => {
if (!i || i.recovery === void 0 || i.recovery === null)
throw new Error("Invalid signature");
const e = i.toCompactRawBytes(), t = new Uint8Array(e.length + 1);
return t.set(e), t[t.length - 1] = i.recovery, t;
}, Gi = [
"P-256",
"P-384",
"P-521",
"secp256k1"
], Ki = [
"ES256",
"ES384",
"ES512",
"ES256K"
], w = (i) => i instanceof Error ? i.message : String(i), Rn = (i) => {
try {
return i.utils.randomPrivateKey();
} catch (e) {
throw console.log(w(e)), new Error("Failed to generate random private key");
}
}, Hn = (i, e, t, r = !0) => {
if (!r)
throw new Error("Uncompressed public key is not supported");
try {
if (t.length === e * 2) {
const n = t.slice(0, e), s = t.slice(e), o = i.getPublicKey(n);
if (ne(o, s))
return o;
throw new Error("Embedded public key is invalid");
}
return i.getPublicKey(t);
} catch (n) {
throw console.log(w(n)), new Error("Failed to get public key");
}
}, _n = (i, e, { message: t, privateKey: r, recovered: n = !1 }) => {
if (n)
throw new Error("Recovered signature is not supported");
try {
const s = ie(t) ? se(t) : t, o = r.length === e * 2 ? r.slice(0, e) : r;
return i.sign(s, o);
} catch (s) {
throw console.log(w(s)), new Error("Failed to sign message");
}
}, Ln = (i, { signature: e, message: t, publicKey: r }) => {
try {
const n = ie(t) ? se(t) : t;
return i.verify(e, n, r);
} catch (n) {
return console.log(w(n)), !1;
}
}, ht = (i, e, t) => {
try {
if (t.byteLength !== e)
throw new Error(
`Invalid public key byte length: ${t.byteLength}, expected ${e}`
);
return {
kty: "OKP",
crv: "Ed25519",
alg: "EdDSA",
x: O(t)
};
} catch (r) {
throw console.log(w(r)), new Error("Failed to convert public key to JWK");
}
}, Mn = (i, e, t) => {
try {
const r = i.getPublicKey(t);
return {
...ht(i, e, r),
d: O(t)
};
} catch (r) {
throw console.log(w(r)), new Error("Failed to convert private key to JWK");
}
}, Fn = (i, e, t, r) => {
try {
return dt(
i,
e,
t,
r
);
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert JWK to raw public key");
}
}, dt = (i, e, t, r) => {
if (r.kty == null)
throw new Error("Missing required parameter for kty");
if (r.kty !== "OKP")
throw new Error(`Invalid key type: ${r.kty}, expected OKP`);
if (r.crv == null)
throw new Error("Missing required parameter for crv");
if (r.crv !== t)
throw new Error(
`Invalid curve: ${r.crv}, expected ${t}`
);
if (r.x == null)
throw new Error("Missing required parameter for x");
if (typeof r.x != "string")
throw new Error("Invalid parameter type for x");
if (r.alg !== void 0 && r.alg !== null && r.alg !== "EdDSA")
throw new Error(`Invalid algorithm: ${r.alg}, expected EdDSA`);
let n;
try {
n = $(r.x);
} catch {
throw new Error("Malformed encoding for x");
}
if (n.length !== e)
throw new Error(
`Invalid the length of the key data for x: ${n.length}, expected ${e}`
);
return n;
}, On = (i, e, t, r) => {
try {
return $n(
i,
e,
t,
r
);
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert JWK to raw private key");
}
}, $n = (i, e, t, r) => {
const n = dt(
i,
e,
t,
r
);
if (r.d == null)
throw new Error("Missing required parameter for d");
if (typeof r.d != "string")
throw new Error("Invalid parameter type for d");
let s;
try {
s = $(r.d);
} catch {
throw new Error("Malformed encoding for d");
}
if (s.length !== e)
throw new Error(
`Invalid the length of the key data for d: ${s.length}, expected ${e}`
);
if (!ne(i.getPublicKey(s), n))
throw new Error(
"The public key derived from the private key does not match the public key in the JWK"
);
return s;
};
class Dn {
/**
* Creates a new Edwards instance.
*
* @param {Object} params - Edwards constructor parameters
* @param {CurveFn} params.curve - The curve implementation to use
* @param {RandomBytes} params.randomBytes - Function to generate random bytes
* @param {CurveName} params.curveName - Curve identifier (e.g. 'ed25519')
* @param {SignatureAlgorithmName} params.signatureAlgorithmName - Signature algorithm name
* @param {number} params.keyByteLength - Private/public key length in bytes
*/
constructor({
curve: e,
randomBytes: t,
curveName: r,
signatureAlgorithmName: n,
keyByteLength: s
}) {
this.randomPrivateKey = () => Rn(this.curve), this.getPublicKey = (o, f = !0) => Hn(
this.curve,
this.keyByteLength,
o,
f
), this.sign = ({
message: o,
privateKey: f,
recovered: c = !1
}) => _n(this.curve, this.keyByteLength, {
message: o,
privateKey: f,
recovered: c
}), this.verify = ({ signature: o, message: f, publicKey: c }) => Ln(this.curve, { signature: o, message: f, publicKey: c }), this.recoverPublicKey = (o) => {
throw new Error("Public key recovery is not supported");
}, this.toJwkPrivateKey = (o) => Mn(this.curve, this.keyByteLength, o), this.toJwkPublicKey = (o) => ht(this.curve, this.keyByteLength, o), this.toRawPrivateKey = (o) => On(
this.curve,
this.keyByteLength,
this.curveName,
o
), this.toRawPublicKey = (o) => Fn(
this.curve,
this.keyByteLength,
this.curveName,
o
), this.curve = e, this.randomBytes = t, this.curveName = r, this.keyByteLength = s, this.signatureAlgorithmName = n;
}
/**
* Gets the underlying curve implementation.
* This method allows access to the raw CurveFn implementation when needed.
*
* @returns {CurveFn} The underlying curve implementation
*/
getCurve() {
return this.curve;
}
}
const Pn = (i) => {
try {
return i.utils.randomPrivateKey();
} catch (e) {
throw console.log(w(e)), new Error("Failed to generate random private key");
}
}, Jn = (i, e, t = !0) => {
try {
return i.getPublicKey(e, t);
} catch (r) {
throw console.log(w(r)), new Error("Failed to get public key");
}
}, Gn = (i, { message: e, privateKey: t, recovered: r = !1 }) => {
try {
const n = ie(e) ? se(e) : e, s = i.sign(n, t, { prehash: !0 });
return r ? Tn(s) : s.toCompactRawBytes();
} catch (n) {
throw console.log(w(n)), new Error("Failed to sign message");
}
}, Kn = (i, { signature: e, message: t, publicKey: r }) => {
try {
const n = ie(t) ? se(t) : t, s = ct(i, e);
return i.verify(s, n, r, { prehash: !0 });
} catch (n) {
return console.log(w(n)), !1;
}
}, Wn = (i, { privateKey: e, publicKey: t }) => {
try {
const r = i.getSharedSecret(e, t).slice(1);
if (r.some((n) => n !== 0))
return r;
throw new Error("Shared secret is zero");
} catch (r) {
throw console.log(w(r)), new Error("Failed to compute shared secret");
}
}, gt = (i, e, t, r, n) => {
try {
const o = i.ProjectivePoint.fromHex(n).toRawBytes(!1);
if (o.length !== e * 2 + 1)
throw new Error(
`Invalid uncompressed public key length: ${o.length}, expected ${e * 2 + 1}`
);
const f = o.slice(1, 1 + e), c = o.slice(1 + e);
return {
kty: "EC",
crv: t,
alg: r,
x: O(f),
y: O(c)
};
} catch (s) {
throw console.log(w(s)), new Error("Failed to convert public key to JWK");
}
}, qn = (i, e, t, r, n) => {
try {
const s = i.getPublicKey(n);
return {
...gt(
i,
e,
t,
r,
s
),
d: O(n)
};
} catch (s) {
throw console.log(w(s)), new Error("Failed to convert private key to JWK");
}
}, Xn = (i, e, t, r, n) => {
try {
return wt(
i,
e,
t,
r,
n
);
} catch (s) {
throw console.log(w(s)), new Error("Failed to convert JWK to raw public key");
}
}, wt = (i, e, t, r, n) => {
if (n.kty === void 0 || n.kty === null)
throw new Error("Missing required parameter for kty");
if (n.kty !== "EC")
throw new Error(`Invalid key type: ${n.kty}, expected EC`);
if (n.crv == null)
throw new Error("Missing required parameter for crv");
if (n.crv !== t)
throw new Error(
`Invalid curve: ${n.crv}, expected ${t}`
);
if (n.x == null)
throw new Error("Missing required parameter for x");
if (typeof n.x != "string")
throw new Error("Invalid parameter type for x");
if (n.y == null)
throw new Error("Missing required parameter for y");
if (typeof n.y != "string")
throw new Error("Invalid parameter type for y");
if (n.alg != null && n.alg !== r)
throw new Error(
`Invalid algorithm: ${n.alg}, expected ${r}`
);
let s;
try {
s = $(n.x);
} catch {
throw new Error("Malformed encoding for x");
}
if (s.length !== e)
throw new Error(
`Invalid the length of the key data for x: ${s.length}, expected ${e}`
);
let o;
try {
o = $(n.y);
} catch {
throw new Error("Malformed encoding for y");
}
if (o.length !== e)
throw new Error(
`Invalid the length of the key data for y: ${o.length}, expected ${e}`
);
return new Uint8Array([4, ...s, ...o]);
}, Zn = (i, e, t, r, n) => {
try {
return zn(
i,
e,
t,
r,
n
);
} catch (s) {
throw console.log(w(s)), new Error("Failed to convert JWK to raw private key");
}
}, zn = (i, e, t, r, n) => {
const s = wt(
i,
e,
t,
r,
n
);
if (n.d === void 0 || n.d === null)
throw new Error("Missing required parameter for d");
if (typeof n.d != "string")
throw new Error("Invalid parameter type for d");
let o;
try {
o = $(n.d);
} catch {
throw new Error("Malformed encoding for d");
}
if (o.length !== e)
throw new Error(
`Invalid the length of the key data for d: ${o.length}, expected ${e}`
);
if (!ne(i.getPublicKey(o, !1), s))
throw new Error(
"The public key derived from the private key does not match the public key in the JWK"
);
return o;
}, Yn = (i, { signature: e, message: t, compressed: r = !0 }) => {
try {
const n = ie(t) ? se(t) : t, s = i.CURVE.hash(n);
return ct(i, e).recoverPublicKey(s).toRawBytes(r);
} catch (n) {
throw console.log(w(n)), new Error("Failed to recover public key");
}
};
class we {
/**
* Creates a new Weierstrass instance.
*
* @param {CurveFn} curve - The curve implementation to use
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor({
curve: e,
randomBytes: t,
curveName: r,
signatureAlgorithmName: n,
keyByteLength: s
}) {
this.randomPrivateKey = () => Pn(this.curve), this.getPublicKey = (o, f = !0) => Jn(this.curve, o, f), this.sign = ({
message: o,
privateKey: f,
recovered: c = !1
}) => Gn(this.curve, { message: o, privateKey: f, recovered: c }), this.verify = ({ signature: o, message: f, publicKey: c }) => Kn(this.curve, { signature: o, message: f, publicKey: c }), this.recoverPublicKey = ({
signature: o,
message: f,
compressed: c = !0
}) => Yn(this.curve, {
signature: o,
message: f,
compressed: c
}), this.getSharedSecret = ({
privateKey: o,
publicKey: f
}) => Wn(this.curve, { privateKey: o, publicKey: f }), this.toJwkPrivateKey = (o) => qn(
this.curve,
this.keyByteLength,
this.curveName,
this.signatureAlgorithmName,
o
), this.toJwkPublicKey = (o) => gt(
this.curve,
this.keyByteLength,
this.curveName,
this.signatureAlgorithmName,
o
), this.toRawPrivateKey = (o) => Zn(
this.curve,
this.keyByteLength,
this.curveName,
this.signatureAlgorithmName,
o
), this.toRawPublicKey = (o) => Xn(
this.curve,
this.keyByteLength,
this.curveName,
this.signatureAlgorithmName,
o
), this.curve = e, this.randomBytes = t, this.keyByteLength = s, this.curveName = r, this.signatureAlgorithmName = n;
}
/**
* Gets the underlying curve implementation.
* This method allows access to the raw CurveFn implementation when needed.
*
* @returns {CurveFn} The underlying curve implementation
*/
getCurve() {
return this.curve;
}
}
class vt extends we {
/**
* Creates a new P-256 curve instance.
*
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor(e) {
super({
curve: pn(e),
randomBytes: e,
curveName: "P-256",
signatureAlgorithmName: "ES256",
keyByteLength: 32
});
}
}
class bt extends we {
/**
* Creates a new P-521 curve instance.
*
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor(e) {
super({
curve: Nn(e),
randomBytes: e,
curveName: "P-521",
signatureAlgorithmName: "ES512",
keyByteLength: 66
});
}
}
class Bt extends we {
/**
* Creates a new P-384 curve instance.
*
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor(e) {
super({
curve: An(e),
randomBytes: e,
curveName: "P-384",
signatureAlgorithmName: "ES384",
keyByteLength: 48
});
}
}
class yt extends we {
/**
* Creates a new secp256k1 curve instance.
*
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor(e) {
super({
curve: Cn(e),
randomBytes: e,
curveName: "secp256k1",
signatureAlgorithmName: "ES256K",
keyByteLength: 32
});
}
}
const Qn = (i) => {
try {
return i.utils.randomPrivateKey();
} catch (e) {
throw console.log(w(e)), new Error("Failed to generate random private key");
}
}, jn = (i, e, t = !0) => {
if (!t)
throw new Error("Uncompressed public key is not supported");
try {
return i.getPublicKey(e);
} catch (r) {
throw console.log(w(r)), new Error("Failed to get public key");
}
}, mt = (i, e, t, r) => {
try {
if (r.length !== e)
throw new Error(
`Invalid public key length: ${r.length}, expected ${e}`
);
return {
kty: "OKP",
crv: t,
x: O(r)
};
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert public key to JWK");
}
}, ei = (i, e, t, r) => {
try {
const n = i.getPublicKey(r);
return {
...mt(
i,
e,
t,
n
),
d: O(r)
};
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert private key to JWK");
}
}, ti = (i, e, t, r) => {
try {
return kt(
i,
e,
t,
r
);
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert JWK to raw public key");
}
}, kt = (i, e, t, r) => {
if (r.kty === void 0 || r.kty === null)
throw new Error("Missing required parameter for kty");
if (r.kty !== "OKP")
throw new Error(`Invalid key type: ${r.kty}, expected OKP`);
if (r.crv === void 0 || r.crv === null)
throw new Error("Missing required parameter for crv");
if (r.crv !== t)
throw new Error(
`Invalid curve: ${r.crv}, expected ${t}`
);
if (r.x == null)
throw new Error("Missing required parameter for x");
if (typeof r.x != "string")
throw new Error("Invalid parameter type for x");
let n;
try {
n = $(r.x);
} catch {
throw new Error("Malformed encoding for x");
}
if (n.length !== e)
throw new Error(
`Invalid the length of the key data for x: ${n.length}, expected ${e}`
);
return n;
}, ri = (i, e, t, r) => {
try {
return ni(
i,
e,
t,
r
);
} catch (n) {
throw console.log(w(n)), new Error("Failed to convert JWK to raw private key");
}
}, ni = (i, e, t, r) => {
const n = kt(
i,
e,
t,
r
);
if (r.d === void 0 || r.d === null)
throw new Error("Missing required parameter for d");
if (typeof r.d != "string")
throw new Error("Invalid parameter type for d");
let s;
try {
s = $(r.d);
} catch {
throw new Error("Malformed encoding for d");
}
if (s.length !== e)
throw new Error(
`Invalid the length of the key data for d: ${s.length}, expected ${e}`
);
if (!ne(i.getPublicKey(s), n))
throw new Error(
"The public key derived from the private key does not match the public key in the JWK"
);
return s;
}, ii = [
// 0 (order 1)
"0000000000000000000000000000000000000000000000000000000000000000",
// 1 (order 1)
"0100000000000000000000000000000000000000000000000000000000000000",
// 325606250916557431795983626356110631294008115727848805560023387167927233504 (order 8)
"e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
// 39382357235489614581723060781553021112529911719440698176882885853963445705823 (order 8)
"5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
// p-1 (order 2)
"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec",
// p (order 4)
"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed",
// p+1 (order 1)
"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffee"
].map((i) => fn(i)), si = (i) => ii.some(
(e) => ne(i, e)
), oi = (i, e, { privateKey: t, publicKey: r }) => {
try {
if (e === "X25519" && si(r))
throw new Error("Public key is a small order point");
const n = i.getSharedSecret(t, r);
if (n.some((s) => s !== 0))
return n;
throw new Error("Shared secret is zero");
} catch (n) {
throw console.log(w(n)), new Error("Failed to compute shared secret");
}
};
class fi {
/**
* Creates a new Montgomery instance.
*
* @param {object} params - Constructor parameters
* @param {CurveFn} params.curve - The curve implementation to use
* @param {RandomBytes} params.randomBytes - Function to generate random bytes
* @param {CurveName} params.curveName - Curve name identifier (e.g. 'X25519')
* @param {number} params.keyByteLength - Expected byte length of keys (e.g. 32 for X25519)
*/
constructor({
curve: e,
randomBytes: t,
curveName: r,
keyByteLength: n
}) {
this.curve = e, this.randomBytes = t, this.curveName = r, this.keyByteLength = n;
}
/**
* Gets the underlying curve implementation.
* This method allows access to the raw CurveFn implementation when needed.
*
* @returns {CurveFn} The underlying curve implementation
*/
getCurve() {
return this.curve;
}
/**
* Generates a random private key for the Montgomery curve.
*
* @returns {Uint8Array} The random private key
*/
randomPrivateKey() {
return Qn(this.curve);
}
/**
* Derives a public key from a private key.
*
* @param {Uint8Array} privateKey - The private key to derive from
* @param {boolean} [compressed=true] - Whether to return a compressed public key
* @returns {Uint8Array} The derived public key
* @throws {Error} If the private key is invalid or uncompressed keys are requested
*/
getPublicKey(e, t = !0) {
return jn(this.curve, e, t);
}
/**
* Computes a shared secret using ECDH.
*
* @param {GetSharedSecretParams} params - The parameters for shared secret computation
* @param {Uint8Array} params.privateKey - The private key
* @param {Uint8Array} params.publicKey - The public key
* @returns {Uint8Array} The computed shared secret
* @throws {Error} If either the private key or public key is invalid
*/
getSharedSecret({
privateKey: e,
publicKey: t
}) {
return oi(this.curve, this.curveName, {
privateKey: e,
publicKey: t
});
}
/**
* Converts a private key to JWK format.
*
* @param {Uint8Array} privateKey - The private key to convert
* @returns {JwkPrivateKey} The private key in JWK format
* @throws {Error} If the private key is invalid
*/
toJwkPrivateKey(e) {
return ei(
this.curve,
this.keyByteLength,
this.curveName,
e
);
}
/**
* Converts a public key to JWK format.
*
* @param {Uint8Array} publicKey - The public key to convert
* @returns {JwkPublicKey} The public key in JWK format
* @throws {Error} If the public key is invalid
*/
toJwkPublicKey(e) {
return mt(
this.curve,
this.keyByteLength,
this.curveName,
e
);
}
/**
* Converts a JWK private key to raw format.
*
* @param {JwkPrivateKey} jwkPrivateKey - The JWK private key to convert
* @returns {Uint8Array} The private key in raw format
* @throws {Error} If the JWK is invalid
*/
toRawPrivateKey(e) {
return ri(
this.curve,
this.keyByteLength,
this.curveName,
e
);
}
/**
* Converts a JWK public key to raw format.
*
* @param {JwkPublicKey} jwkPublicKey - The JWK public key to convert
* @returns {Uint8Array} The public key in raw format
* @throws {Error} If the JWK is invalid
*/
toRawPublicKey(e) {
return ti(
this.curve,
this.keyByteLength,
this.curveName,
e
);
}
}
class ci extends fi {
/**
* Creates a new X25519 curve instance.
*
* @param {RandomBytes} randomBytes - A function to generate cryptographically secure random bytes.
*/
constructor(e) {
super({
curve: kn(e),
randomBytes: e,
curveName: "X25519",
keyByteLength: 32
});
}
}
const Wi = (i, e) => {
switch (i) {
case "P-256":
return new vt(e);
case "P-384":
return new Bt(e);
case "P-521":
return new bt(e);
case "secp256k1":
return new yt(e);
case "X25519":
return new ci(e);
default:
throw new Error(`Unsupported signature curve: ${i}`);
}
};
class ai extends Dn {
/**
* Creates a new Ed25519 instance.
*
* @param {RandomBytes} randomBytes - Function to generate random bytes
*/
constructor(e) {
super({
curve: yn(e),
randomBytes: e,
curveName: "Ed25519",
signatureAlgorithmName: "EdDSA",
keyByteLength: 32
});
}
}
const li = (i, e) => {
switch (i) {
case "P-256":
return new vt(e);
case "P-384":
return new Bt(e);
case "P-521":
return new bt(e);
case "secp256k1":
return new yt(e);
case "Ed25519":
return new ai(e);
default:
throw new Error(`Unsupported signature curve: ${i}`);
}
}, ui = (i) => {
throw new Error("RNG usage is disallowed for this curve");
}, qi = (i) => li(i, ui), hi = new TextEncoder(), di = (i) => {
const { crv: e, kty: t, x: r, y: n } = i;
if (t !== "EC")
throw new Error(`Invalid key type: ${t}, expected EC`);
if (e == null)
throw new Error("Missing required parameter for crv");
if (r == null)
throw new Error("Missing required parameter for x");
if (n == null)
throw new Error("Missing required parameter for y");
return JSON.stringify({ crv: e, kty: t, x: r, y: n }, ["crv", "kty", "x", "y"]);
}, gi = (i) => {
const { crv: e, kty: t, x: r } = i;
if (t !== "OKP")
throw new Error(`Invalid key type: ${t}, expected OKP`);
if (e == null)
throw new Error("Missing required parameter for crv");
if (r == null)
throw new Error("Missing required parameter for x");
return JSON.stringify({ crv: e, kty: t, x: r }, ["crv", "kty", "x"]);
}, wi = (i) => {
const { kty: e } = i;
if (e === "EC")
return di(i);
if (e === "OKP")
return gi(i);
throw new Error(`Invalid key type: ${e}, expected EC or OKP`);
}, Xi = (i) => {
const e = wi(i), t = hi.encode(e);
return Ue(t);
};
/*!
* MIT License
*
* Copyright (c) 2017-2024 Peculiar Ventures, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
const vi = "[object ArrayBuffer]";
class g {
static isArrayBuffer(e) {
return Object.prototype.toString.call(e) === vi;
}
static toArrayBuffer(e) {
return this.isArrayBuffer(e) ? e : e.byteLength === e.buffer.byteLength || e.byteOffset === 0 && e.byteLength === e.buffer.byteLength ? e.buffer : this.toUint8Array(e.buffer).slice(e.byteOffset, e.byteOffset + e.byteLength).buffer;
}
static toUint8Array(e) {
return this.toView(e, Uint8Array);
}
static toView(e, t) {
if (e.constructor === t)
return e;
if (this.isArrayBuffer(e))
return new t(e);
if (this.isArrayBufferView(e))
return new t(e.buffer, e.byteOffset, e.byteLength);
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
static isBufferSource(e) {
return this.isArrayBufferView(e) || this.isArrayBuffer(e);
}
static isArrayBufferView(e) {
return ArrayBuffer.isView(e) || e && this.isArrayBuffer(e.buffer);
}
static isEqual(e, t) {
const r = g.toUint8Array(e), n = g.toUint8Array(t);
if (r.length !== n.byteLength)
return !1;
for (let s = 0; s < r.length; s++)
if (r[s] !== n[s])
return !1;
return !0;
}
static concat(...e) {
let t;
Array.isArray(e[0]) && !(e[1] instanceof Function) || Array.isArray(e[0]) && e[1] instanceof Function ? t = e[0] : e[e.length - 1] instanceof Function ? t = e.slice(0, e.length - 1) : t = e;
let r = 0;
for (const o of t)
r += o.byteLength;
const n = new Uint8Array(r);
let s = 0;
for (const o of t) {
const f = this.toUint8Array(o);
n.set(f, s), s += f.length;
}
return e[e.length - 1] instanceof Function ? this.toView(n, e[e.length - 1]) : n.buffer;
}
}
const pe = "string", bi = /^[0-9a-f\s]+$/i, Bi = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, yi = /^[a-zA-Z0-9-_]+$/;
class et {
static fromString(e) {
const t = unescape(encodeURIComponent(e)), r = new Uint8Array(t.length);
for (let n = 0; n < t.length; n++)
r[n] = t.charCodeAt(n);
return r.buffer;
}
static toString(e) {
const t = g.toUint8Array(e);
let r = "";
for (let s = 0; s < t.length; s++)
r += String.fromCharCode(t[s]);
return decodeURIComponent(escape(r));
}
}
class V {
static toString(e, t = !1) {
const r = g.toArrayBuffer(e), n = new DataView(r);
let s = "";
for (let o = 0; o < r.byteLength; o += 2) {
const f = n.getUint16(o, t);
s += String.fromCharCode(f);
}
return s;
}
static fromString(e, t = !1) {
const r = new ArrayBuffer(e.length * 2), n = new DataView(r);
for (let s = 0; s < e.length; s++)
n.setUint16(s * 2, e.charCodeAt(s), t);
return r;
}
}
class B {
static isHex(e) {
return typeof e === pe && bi.test(e);
}
static isBase64(e) {
return typeof e === pe && Bi.test(e);
}
static isBase64Url(e) {
return typeof e === pe && yi.test(e);
}
static ToString(e, t = "utf8") {
const r = g.toUint8Array(e);
switch (t.toLowerCase()) {
case "utf8":
return this.ToUtf8String(r);
case "binary":
return this.ToBinary(r);
case "hex":
return this.ToHex(r);
case "base64":
return this.ToBase64(r);
case "base64url":
return this.ToBase64Url(r);
case "utf16le":
return V.toString(r, !0);
case "utf16":
case "utf16be":
return V.toString(r);
default:
throw new Error(`Unknown type of encoding '${t}'`);
}
}
static FromString(e, t = "utf8") {
if (!e)
return new ArrayBuffer(0);
switch (t.toLowerCase()) {
case "utf8":
return this.FromUtf8String(e);
case "binary":
return this.FromBinary(e);
case "hex":
return this.FromHex(e);
case "base64":
return this.FromBase64(e);
case "base64url":
return this.FromBase64Url(e);
case "utf16le":
return V.fromString(e, !0);
case "utf16":
case "utf16be":
return V.fromString(e);
default:
throw new Error(`Unknown type of encoding '${t}'`);
}
}
static ToBase64(e) {
const t = g.toUint8Array(e);
if (typeof btoa < "u") {
const r = this.ToString(t, "binary");
return btoa(r);
} else
return Buffer.from(t).toString("base64");
}
static FromBase64(e) {
const t = this.formatString(e);
if (!t)
return new ArrayBuffer(0);
if (!B.isBase64(t))
throw new TypeError("Argument 'base64Text' is not Base64 encoded");
return typeof atob < "u" ? this.FromBinary(atob(t)) : new Uint8Array(Buffer.from(t, "base64")).buffer;
}
static FromBase64Url(e) {
const t = this.formatString(e);
if (!t)
return new ArrayBuffer(0);
if (!B.isBase64Url(t))
throw new TypeError("Argument 'base64url' is not Base64Url encoded");
return this.FromBase64(this.Base64Padding(t.replace(/\-/g, "+").replace(/\_/g, "/")));
}
static ToBase64Url(e) {
return this.ToBase64(e).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
}
static FromUtf8String(e, t = B.DEFAULT_UTF8_ENCODING) {
switch (t) {
case "ascii":
return this.FromBinary(e);
case "utf8":
return et.fromString(e);
case "utf16":
case "utf16be":
return V.fromString(e);
case "utf16le":
case "usc2":
return V.fromString(e, !0);
default:
throw new Error(`Unknown type of encoding '${t}'`);
}
}
static ToUtf8String(e, t = B.DEFAULT_UTF8_ENCODING) {
switch (t) {
case "ascii":
return this.ToBinary(e);
case "utf8":
return et.toString(e);
case "utf16":
case "utf16be":
return V.toString(e);
case "utf16le":
case "usc2":
return V.toString(e, !0);
default:
throw new Error(`Unknown type of encoding '${t}'`);
}
}
static FromBinary(e) {
const t = e.length, r = new Uint8Array(t);
for (let n = 0; n < t; n++)
r[n] = e.charCodeAt(n);
return r.buffer;
}
static ToBinary(e) {
const t = g.toUint8Array(e);
let r = "";
for (let n = 0; n < t.length; n++)
r += String.fromCharCode(t[n]);
return r;
}
static ToHex(e) {
const t = g.toUint8Array(e);
let r = "";
const n = t.length;
for (let s = 0; s < n; s++) {
const o = t[s];
o < 16 && (r += "0"), r += o.toString(16);
}
return r;
}
static FromHex(e) {
let t = this.formatString(e);
if (!t)
return new ArrayBuffer(0);
if (!B.isHex(t))
throw new TypeError("Argument 'hexString' is not HEX encoded");
t.length % 2 && (t = `0${t}`);
const r = new Uint8Array(t.length / 2);
for (let n = 0; n < t.length; n = n + 2) {
const s = t.slice(n, n + 2);
r[n / 2] = parseInt(s, 16);
}
return r.buffer;
}
static ToUtf16String(e, t = !1) {
return V.toString(e, t);
}
static FromUtf16String(e, t = !1) {
return V.fromString(e, t);
}
static Base64Padding(e) {
const t = 4 - e.length % 4;
if (t < 4)
for (let r = 0; r < t; r++)
e += "=";
return e;
}
static formatString(e) {
return (e == null ? void 0 : e.replace(/[\n\r\t ]/g, "")) || "";
}
}
B.DEFAULT_UTF8_ENCODING = "utf8";
/*!
Copyright (c) Peculiar Ventures, LLC
*/
function W(i, e) {
let t = 0;
if (i.length === 1)
return i[0];
for (let r = i.length - 1; r >= 0; r--)
t += i[i.length - 1 - r] * Math.pow(2, e * r);
return t;
}
function D(i, e, t = -1) {
const r = t;
let n = i, s = 0, o = Math.pow(2, e);
for (let f = 1; f < 8; f++) {
if (i < o) {
let c;
if (r < 0)
c = new ArrayBuffer(f), s = f;
else {
if (r < f)
return new ArrayBuffer(0);
c = new ArrayBuffer(r), s = r;
}
const u = new Uint8Array(c);
for (let h = f - 1; h >= 0; h--) {
const a = Math.pow(2, h * e);
u[s - h - 1] = Math.floor(n / a), n -= u[s - h - 1] * a;
}
return c;
}
o *= Math.pow(2, e);
}
return new ArrayBuffer(0);
}
function Ie(...i) {
let e = 0, t = 0;
for (const s of i)
e += s.length;
const r = new ArrayBuffer(e), n = new Uint8Array(r);
for (const s of i)
n.set(s, t), t += s.length;
return n;
}
function Et() {
const i = new Uint8Array(this.valueHex);
if (this.valueHex.byteLength >= 2) {
const f = i[0] === 255 && i[1] & 128, c = i[0] === 0 && (i[1] & 128) === 0;
(f || c) && this.warnings.push("Needlessly long format");
}
const e = new ArrayBuffer(this.valueHex.byteLength), t = new Uint8Array(e);
for (let f = 0; f < this.valueHex.byteLength; f++)
t[f] = 0;
t[0] = i[0] & 128;
const r = W(t, 8), n = new ArrayBuffer(this.valueHex.byteLength), s = new Uint8Array(n);
for (let f = 0; f < this.valueHex.byteLength; f++)
s[f] = i[f];
return s[0] &= 127, W(s, 8) - r;
}
function mi(i) {
const e = i < 0 ? i * -1 : i;
let t = 128;
for (let r = 1; r < 8; r++) {
if (e <= t) {
if (i < 0) {
const o = t - e, f = D(o, 8, r), c = new Uint8Array(f);
return c[0] |= 128, f;
}
let n = D(e, 8, r), s = new Uint8Array(n);
if (s[0] & 128) {
const o = n.slice(0), f = new Uint8Array(o);
n = new ArrayBuffer(n.byteLength + 1), s = new Uint8Array(n);
for (let c = 0; c < o.byteLength; c++)
s[c + 1] = f[c];
s[0] = 0;
}
return n;
}
t *= Math.pow(2, 8);
}
return new ArrayBuffer(0);
}
function ki(i, e) {
if (i.byteLength !== e.byteLength)
return !1;
const t = new Uint8Array(i), r = new Uint8Array(e);
for (let n = 0; n < t.length; n++)
if (t[n] !== r[n])
return !1;
return !0;
}
function S(i, e) {
const t = i.toString(10);
if (e < t.length)
return "";
const r = e - t.length, n = new Array(r);
for (let o = 0; o < r; o++)
n[o] = "0";
return n.join("").concat(t);
}
/*!
* Copyright (c) 2014, GMO GlobalSign
* Copyright (c) 2015-2022, Peculiar Ventures
* All rights reserved.
*
* Author 2014-2019, Yury Strozhevsky
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
function he() {
if (typeof BigInt > "u")
throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.");
}
function Ce(i) {
let e = 0, t = 0;
for (let n = 0; n < i.length; n++) {
const s = i[n];
e += s.byteLength;
}
const r = new Uint8Array(e);
for (let n = 0; n < i.length; n++) {
const s = i[n];
r.set(new Uint8Array(s), t), t += s.byteLength;
}
return r.buffer;
}
function C(i, e, t, r) {
return e instanceof Uint8Array ? e.byteLength ? t < 0 ? (i.error = "Wrong parameter: inputOffset less than zero", !1) : r < 0 ? (i.error = "Wrong parameter: inputLength less than zero", !1) : e.byteLength - t - r < 0 ? (i.error = "End of input reached before message was fully decoded (inconsistent offset and length values)", !1) : !0 : (i.error = "Wrong parameter: inputBuffer has zero length", !1) : (i.error = "Wrong parameter: inputBuffer must be 'Uint8Array'", !1);
}
class Te {
constructor() {
this.items = [];
}
write(e) {
this.items.push(e);
}
final() {
return Ce(this.items);
}
}
const ee = [new Uint8Array([1])], tt = "0123456789", X = "", N = new ArrayBuffer(0), Re = new Uint8Array(0), re = "EndOfContent", xt = "OCTET STRING", pt = "BIT STRING";
function T(i) {
var e;
return e = class extends i {
get valueHex() {
return this.valueHexView.slice().buffer;
}
set valueHex(r) {
this.valueHexView = new Uint8Array(r);
}
constructor(...r) {
var n;
super(...r);
const s = r[0] || {};
this.isHexOnly = (n = s.isHexOnly) !== null && n !== void 0 ? n : !1, this.valueHexView = s.valueHex ? g.toUint8Array(s.valueHex) : Re;
}
fromBER(r, n, s) {
const o = r instanceof ArrayBuffer ? new Uint8Array(r) : r;
if (!C(this, o, n, s))
return -1;
const f = n + s;
return this.valueHexView = o.subarray(n, f), this.valueHexView.length ? (this.blockLength = s, f) : (this.warnings.push("Zero buffer length"), n);
}
toBER(r = !1) {
return this.isHexOnly ? r ? new ArrayBuffer(this.valueHexView.byteLength) : this.valueHexView.byteLength === this.valueHexView.buffer.byteLength ? this.valueHexView.buffer : this.valueHexVi