Socket
Socket
Sign inDemoInstall

@noble/curves

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@noble/curves - npm Package Compare versions

Comparing version 0.7.0 to 0.7.1

1

_shortw_utils.d.ts

@@ -56,3 +56,2 @@ import { randomBytes } from '@noble/hashes/utils';

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -59,0 +58,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

2

abstract/bls.js

@@ -135,3 +135,3 @@ "use strict";

msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normalizePrivateKey(privateKey));
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G2.ProjectivePoint)

@@ -138,0 +138,0 @@ return sigPoint;

@@ -7,7 +7,7 @@ declare type Hex = string | Uint8Array;

domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
a24: bigint;
a: bigint;
montgomeryBits: number;
powPminus2?: (x: bigint) => bigint;
xyToU?: (x: bigint, y: bigint) => bigint;
Gu: string;
Gu: bigint;
};

@@ -19,3 +19,3 @@ export declare type CurveFn = {

getPublicKey: (privateKey: Hex) => Uint8Array;
Gu: string;
GuBytes: Uint8Array;
};

@@ -22,0 +22,0 @@ export declare function montgomery(curveDef: CurveType): CurveFn;

@@ -11,3 +11,3 @@ "use strict";

(0, utils_js_1.validateObject)(curve, {
a24: 'bigint',
a: 'bigint',
}, {

@@ -19,3 +19,3 @@ montgomeryBits: 'isSafeInteger',

powPminus2: 'function',
Gu: 'string',
Gu: 'bigint',
});

@@ -30,3 +30,3 @@ // Set defaults

const { P } = CURVE;
const modP = (a) => (0, modular_js_1.mod)(a, P);
const modP = (n) => (0, modular_js_1.mod)(n, P);
const montgomeryBits = CURVE.montgomeryBits;

@@ -53,2 +53,3 @@ const montgomeryBytes = Math.ceil(montgomeryBits / 8);

}
// Accepts 0 as well
function assertFieldElement(n) {

@@ -60,2 +61,4 @@ if (typeof n === 'bigint' && _0n <= n && n < P)

// x25519 from 4
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = (CURVE.a - BigInt(2)) / BigInt(4);
/**

@@ -72,4 +75,2 @@ *

const k = assertFieldElement(scalar);
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = CURVE.a24;
const x_1 = u;

@@ -152,4 +153,5 @@ let x_2 = _1n;

// Computes public key from private. By doing scalar multiplication of base point.
const GuBytes = encodeUCoordinate(CURVE.Gu);
function scalarMultBase(scalar) {
return scalarMult(scalar, CURVE.Gu);
return scalarMult(scalar, GuBytes);
}

@@ -161,3 +163,3 @@ return {

getPublicKey: (privateKey) => scalarMultBase(privateKey),
Gu: CURVE.Gu,
GuBytes: GuBytes,
};

@@ -164,0 +166,0 @@ }

@@ -86,3 +86,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

ProjectivePoint: ProjConstructor<T>;
normalizePrivateKey: (key: PrivKey) => bigint;
normPrivateKeyToScalar: (key: PrivKey) => bigint;
weierstrassEquation: (x: T) => T;

@@ -93,3 +93,3 @@ isWithinCurveOrder: (num: bigint) => boolean;

ProjectivePoint: ProjConstructor<T>;
normalizePrivateKey: (key: PrivKey) => bigint;
normPrivateKeyToScalar: (key: PrivKey) => bigint;
weierstrassEquation: (x: T) => T;

@@ -165,3 +165,2 @@ isWithinCurveOrder: (num: bigint) => boolean;

isValidPrivateKey(privateKey: PrivKey): boolean;
hashToPrivateKey: (hash: Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -168,0 +167,0 @@ precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;

@@ -116,4 +116,4 @@ "use strict";

// Validates if priv key is valid and converts it to bigint.
// Supports options CURVE.normalizePrivateKey and CURVE.wrapPrivateKey.
function normalizePrivateKey(key) {
// Supports options allowedPrivateKeyLengths and wrapPrivateKey.
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;

@@ -206,3 +206,3 @@ if (lengths && typeof key !== 'bigint') {

static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}

@@ -404,4 +404,5 @@ // "Private method", don't use it directly

* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @param affinePoint optional point ot save cached precompute windows on it
* @returns New point

@@ -434,2 +435,4 @@ */

* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point

@@ -493,3 +496,3 @@ */

ProjectivePoint: Point,
normalizePrivateKey,
normPrivateKeyToScalar,
weierstrassEquation,

@@ -528,3 +531,3 @@ isWithinCurveOrder,

}
const { ProjectivePoint: Point, normalizePrivateKey, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
...CURVE,

@@ -536,3 +539,2 @@ toBytes(c, point, isCompressed) {

if (isCompressed) {
// TODO: hasEvenY
return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);

@@ -658,3 +660,3 @@ }

try {
normalizePrivateKey(privateKey);
normPrivateKeyToScalar(privateKey);
return true;

@@ -666,23 +668,23 @@ }

},
normPrivateKeyToScalar: normalizePrivateKey,
normPrivateKeyToScalar: normPrivateKeyToScalar,
/**
* Converts some bytes to a valid private key. Needs at least (nBitLength+64) bytes.
*/
hashToPrivateKey: (hash) => ut.numberToBytesBE(mod.hashToPrivateScalar(hash, CURVE_ORDER), CURVE.nByteLength),
/**
* Produces cryptographically secure private key from random of size (nBitLength+64)
* as per FIPS 186 B.4.1 with modulo bias being neglible.
*/
randomPrivateKey: () => utils.hashToPrivateKey(CURVE.randomBytes(Fp.BYTES + 8)),
randomPrivateKey: () => {
const rand = CURVE.randomBytes(Fp.BYTES + 8);
const num = mod.hashToPrivateScalar(rand, CURVE_ORDER);
return ut.numberToBytesBE(num, CURVE.nByteLength);
},
/**
* 1. Returns cached point which you can use to pass to `getSharedSecret` or `#multiply` by it.
* 2. Precomputes point multiplication table. Is done by default on first `getPublicKey()` call.
* If you want your first getPublicKey to take 0.16ms instead of 20ms, make sure to call
* utils.precompute() somewhere without arguments first.
* @param windowSize 2, 4, 8, 16
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
return point;

@@ -718,3 +720,4 @@ },

* Computes shared public key from private key and public key.
* Checks: 1) private key validity 2) shared key is on-curve
* Checks: 1) private key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param privateA private key

@@ -731,3 +734,3 @@ * @param publicB different public key

const b = Point.fromHex(publicB); // check for being on-curve
return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}

@@ -752,2 +755,5 @@ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.

const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
/**
* Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
*/
function int2octets(num) {

@@ -757,3 +763,2 @@ if (typeof num !== 'bigint')

if (!(_0n <= num && num < ORDER_MASK))
// n in [0..ORDER_MASK-1]
throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);

@@ -782,3 +787,3 @@ // works with order, can have different size than numToField!

const h1int = bits2int_modN(msgHash);
const d = normalizePrivateKey(privateKey); // validate private key, convert to bigint
const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
const seedArgs = [int2octets(d), int2octets(h1int)];

@@ -785,0 +790,0 @@ // extraEntropy. RFC6979 3.6: additional k' (optional).

@@ -124,6 +124,6 @@ "use strict";

P: ED25519_P,
a24: BigInt('121665'),
a: BigInt(486662),
montgomeryBits: 255,
nByteLength: 32,
Gu: '0900000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(9),
powPminus2: (x) => {

@@ -130,0 +130,0 @@ const P = ED25519_P;

@@ -105,7 +105,7 @@ "use strict";

exports.x448 = (0, montgomery_js_1.montgomery)({
a24: BigInt(39081),
a: BigInt(156326),
montgomeryBits: 448,
nByteLength: 57,
P: ed448P,
Gu: '0500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(5),
powPminus2: (x) => {

@@ -112,0 +112,0 @@ const P = ed448P;

@@ -132,3 +132,3 @@ import { hashToPrivateScalar } from './modular.js';

msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normalizePrivateKey(privateKey));
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G2.ProjectivePoint)

@@ -135,0 +135,0 @@ return sigPoint;

@@ -8,3 +8,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

validateObject(curve, {
a24: 'bigint',
a: 'bigint',
}, {

@@ -16,3 +16,3 @@ montgomeryBits: 'isSafeInteger',

powPminus2: 'function',
Gu: 'string',
Gu: 'bigint',
});

@@ -27,3 +27,3 @@ // Set defaults

const { P } = CURVE;
const modP = (a) => mod(a, P);
const modP = (n) => mod(n, P);
const montgomeryBits = CURVE.montgomeryBits;

@@ -50,2 +50,3 @@ const montgomeryBytes = Math.ceil(montgomeryBits / 8);

}
// Accepts 0 as well
function assertFieldElement(n) {

@@ -57,2 +58,4 @@ if (typeof n === 'bigint' && _0n <= n && n < P)

// x25519 from 4
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = (CURVE.a - BigInt(2)) / BigInt(4);
/**

@@ -69,4 +72,2 @@ *

const k = assertFieldElement(scalar);
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = CURVE.a24;
const x_1 = u;

@@ -149,4 +150,5 @@ let x_2 = _1n;

// Computes public key from private. By doing scalar multiplication of base point.
const GuBytes = encodeUCoordinate(CURVE.Gu);
function scalarMultBase(scalar) {
return scalarMult(scalar, CURVE.Gu);
return scalarMult(scalar, GuBytes);
}

@@ -158,5 +160,5 @@ return {

getPublicKey: (privateKey) => scalarMultBase(privateKey),
Gu: CURVE.Gu,
GuBytes: GuBytes,
};
}
//# sourceMappingURL=montgomery.js.map

@@ -113,4 +113,4 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

// Validates if priv key is valid and converts it to bigint.
// Supports options CURVE.normalizePrivateKey and CURVE.wrapPrivateKey.
function normalizePrivateKey(key) {
// Supports options allowedPrivateKeyLengths and wrapPrivateKey.
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;

@@ -203,3 +203,3 @@ if (lengths && typeof key !== 'bigint') {

static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}

@@ -401,4 +401,5 @@ // "Private method", don't use it directly

* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @param affinePoint optional point ot save cached precompute windows on it
* @returns New point

@@ -431,2 +432,4 @@ */

* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point

@@ -490,3 +493,3 @@ */

ProjectivePoint: Point,
normalizePrivateKey,
normPrivateKeyToScalar,
weierstrassEquation,

@@ -524,3 +527,3 @@ isWithinCurveOrder,

}
const { ProjectivePoint: Point, normalizePrivateKey, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
...CURVE,

@@ -532,3 +535,2 @@ toBytes(c, point, isCompressed) {

if (isCompressed) {
// TODO: hasEvenY
return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);

@@ -654,3 +656,3 @@ }

try {
normalizePrivateKey(privateKey);
normPrivateKeyToScalar(privateKey);
return true;

@@ -662,23 +664,23 @@ }

},
normPrivateKeyToScalar: normalizePrivateKey,
normPrivateKeyToScalar: normPrivateKeyToScalar,
/**
* Converts some bytes to a valid private key. Needs at least (nBitLength+64) bytes.
*/
hashToPrivateKey: (hash) => ut.numberToBytesBE(mod.hashToPrivateScalar(hash, CURVE_ORDER), CURVE.nByteLength),
/**
* Produces cryptographically secure private key from random of size (nBitLength+64)
* as per FIPS 186 B.4.1 with modulo bias being neglible.
*/
randomPrivateKey: () => utils.hashToPrivateKey(CURVE.randomBytes(Fp.BYTES + 8)),
randomPrivateKey: () => {
const rand = CURVE.randomBytes(Fp.BYTES + 8);
const num = mod.hashToPrivateScalar(rand, CURVE_ORDER);
return ut.numberToBytesBE(num, CURVE.nByteLength);
},
/**
* 1. Returns cached point which you can use to pass to `getSharedSecret` or `#multiply` by it.
* 2. Precomputes point multiplication table. Is done by default on first `getPublicKey()` call.
* If you want your first getPublicKey to take 0.16ms instead of 20ms, make sure to call
* utils.precompute() somewhere without arguments first.
* @param windowSize 2, 4, 8, 16
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
return point;

@@ -714,3 +716,4 @@ },

* Computes shared public key from private key and public key.
* Checks: 1) private key validity 2) shared key is on-curve
* Checks: 1) private key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param privateA private key

@@ -727,3 +730,3 @@ * @param publicB different public key

const b = Point.fromHex(publicB); // check for being on-curve
return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}

@@ -748,2 +751,5 @@ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.

const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
/**
* Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
*/
function int2octets(num) {

@@ -753,3 +759,2 @@ if (typeof num !== 'bigint')

if (!(_0n <= num && num < ORDER_MASK))
// n in [0..ORDER_MASK-1]
throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);

@@ -778,3 +783,3 @@ // works with order, can have different size than numToField!

const h1int = bits2int_modN(msgHash);
const d = normalizePrivateKey(privateKey); // validate private key, convert to bigint
const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
const seedArgs = [int2octets(d), int2octets(h1int)];

@@ -781,0 +786,0 @@ // extraEntropy. RFC6979 3.6: additional k' (optional).

@@ -121,6 +121,6 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

P: ED25519_P,
a24: BigInt('121665'),
a: BigInt(486662),
montgomeryBits: 255,
nByteLength: 32,
Gu: '0900000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(9),
powPminus2: (x) => {

@@ -127,0 +127,0 @@ const P = ED25519_P;

@@ -102,7 +102,7 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

export const x448 = montgomery({
a24: BigInt(39081),
a: BigInt(156326),
montgomeryBits: 448,
nByteLength: 57,
P: ed448P,
Gu: '0500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(5),
powPminus2: (x) => {

@@ -109,0 +109,0 @@ const P = ed448P;

@@ -101,2 +101,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toRawBytes(true).slice(1);

@@ -108,4 +109,5 @@ const numTo32b = (n) => numberToBytesBE(n, 32);

const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
const d = secp256k1.utils.normPrivateKeyToScalar(priv);
const d = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
const point = Point.fromPrivateKey(d); // P = d'⋅G; 0 < d' < n check is done inside

@@ -115,2 +117,6 @@ const scalar = point.hasEvenY() ? d : modN(-d); // d = d' if has_even_y(P), otherwise d = n-d'

}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x) {

@@ -128,2 +134,5 @@ if (!fe(x))

}
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args) {

@@ -163,2 +172,3 @@ return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));

* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/

@@ -165,0 +175,0 @@ function schnorrVerify(signature, message, publicKey) {

@@ -95,10 +95,10 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

}
function normalizePrivateKey(privKey) {
function normPrivKey(privKey) {
return cutils.bytesToHex(ensureBytes0x(privKey)).padStart(64, '0');
}
function getPublicKey0x(privKey, isCompressed = false) {
return starkCurve.getPublicKey(normalizePrivateKey(privKey), isCompressed);
return starkCurve.getPublicKey(normPrivKey(privKey), isCompressed);
}
function getSharedSecret0x(privKeyA, pubKeyB) {
return starkCurve.getSharedSecret(normalizePrivateKey(privKeyA), pubKeyB);
return starkCurve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
}

@@ -108,3 +108,3 @@ function sign0x(msgHash, privKey, opts) {

privKey = strip0x(privKey).padStart(64, '0');
return starkCurve.sign(ensureBytes0x(msgHash), normalizePrivateKey(privKey), opts);
return starkCurve.sign(ensureBytes0x(msgHash), normPrivKey(privKey), opts);
}

@@ -111,0 +111,0 @@ function verify0x(signature, msgHash, pubKey) {

@@ -47,3 +47,2 @@ export declare const P192: Readonly<{

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -99,3 +98,2 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -102,0 +100,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

@@ -47,3 +47,2 @@ export declare const P224: Readonly<{

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -99,3 +98,2 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -102,0 +100,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

@@ -48,3 +48,2 @@ import * as htf from './abstract/hash-to-curve.js';

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -100,3 +99,2 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -103,0 +101,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

@@ -48,3 +48,2 @@ import * as htf from './abstract/hash-to-curve.js';

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -100,3 +99,2 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -103,0 +101,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

@@ -48,3 +48,2 @@ import * as htf from './abstract/hash-to-curve.js';

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -100,3 +99,2 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
hashToPrivateKey: (hash: import("./abstract/utils.js").Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -103,0 +101,0 @@ precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType<bigint> | undefined) => import("./abstract/weierstrass.js").ProjPointType<bigint>;

{
"name": "@noble/curves",
"version": "0.7.0",
"version": "0.7.1",
"description": "Minimal, auditable JS implementation of elliptic curve cryptography",

@@ -5,0 +5,0 @@ "files": [

@@ -26,3 +26,3 @@ # noble-curves

([secp256k1](https://github.com/paulmillr/noble-secp256k1), [ed25519](https://github.com/paulmillr/noble-ed25519)).
See [In the wild](#in-the-wild) for real-world software that uses curves.
See [Resources](#resouces) for articles and real-world software that uses curves.

@@ -49,3 +49,3 @@ ### This library belongs to _noble_ crypto

For [Deno](https://deno.land), use it with npm specifier. In browser, you could also include the single file from
For [Deno](https://deno.land), use it with [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). In browser, you could also include the single file from
[GitHub's releases page](https://github.com/paulmillr/noble-curves/releases).

@@ -69,3 +69,3 @@

const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'
const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236';
const pub2 = secp256k1.getPublicKey(privHex); // keys & other inputs can be Uint8Array-s or hex strings

@@ -131,3 +131,3 @@

const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';
x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub);
x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases
x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);

@@ -190,2 +190,3 @@

// bls.pairing(PointG1, PointG2)
// Also, check out hash-to-curve examples below.
```

@@ -198,3 +199,3 @@

Precomputes are enabled for weierstrass and edwards BASE points of a curve. You could precompute any
other point (e.g. for ECDH) using `utils.precompute()` method.
other point (e.g. for ECDH) using `utils.precompute()` method: check out examples.

@@ -225,3 +226,3 @@ There are following zero-dependency algorithms:

```ts
export type CHash = {
type CHash = {
(message: Uint8Array): Uint8Array;

@@ -245,3 +246,3 @@ blockLen: number;

// T is usually bigint, but can be something else like complex numbers in BLS curves
export interface ProjPointType<T> extends Group<ProjPointType<T>> {
interface ProjPointType<T> extends Group<ProjPointType<T>> {
readonly px: T;

@@ -262,3 +263,3 @@ readonly py: T;

// Static methods for 3d XYZ points
export interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {
interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {
new (x: T, y: T, z: T): ProjPointType<T>;

@@ -274,3 +275,3 @@ fromAffine(p: AffinePoint<T>): ProjPointType<T>;

```ts
export interface SignatureType {
interface SignatureType {
readonly r: bigint;

@@ -287,5 +288,10 @@ readonly s: bigint;

// DER-encoded
toDERRawBytes(isCompressed?: boolean): Uint8Array;
toDERHex(isCompressed?: boolean): string;
toDERRawBytes(): Uint8Array;
toDERHex(): string;
}
type SignatureConstructor = {
new (r: bigint, s: bigint): SignatureType;
fromCompact(hex: Hex): SignatureType;
fromDER(hex: Hex): SignatureType;
};
```

@@ -321,5 +327,6 @@

const point = secq256k1.Point.BASE; // Elliptic curve Point class and BASE point static var.
const Point = secq256k1.ProjectivePoint;
const point = Point.BASE; // Elliptic curve Point class and BASE point static var.
point.add(point).equals(point.double()); // add(), equals(), double() methods
point.subtract(point).equals(secq256k1.Point.ZERO); // subtract() method, ZERO static var
point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var
point.negate(); // Flips point over x/y coordinate.

@@ -329,3 +336,3 @@ point.multiply(31415n); // Multiplication of Point by scalar.

point.assertValidity(); // Checks for being on-curve
point.toAffine(); // Converts to 2d affine xy coordinates
point.toAffine(); // Converts to 2d affine xy coordinates

@@ -335,2 +342,6 @@ secq256k1.CURVE.n;

secq256k1.CURVE.hash();
// precomputes
const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey));
fast.multiply(privKey); // much faster ECDH now
```

@@ -341,3 +352,4 @@

```ts
export type CurveFn = {
type SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array };
type CurveFn = {
CURVE: ReturnType<typeof validateOpts>;

@@ -356,4 +368,6 @@ getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;

utils: {
isValidPrivateKey(privateKey: PrivKey): boolean;
normPrivateKeyToScalar: (key: PrivKey) => bigint;
isValidPrivateKey(key: PrivKey): boolean;
randomPrivateKey: () => Uint8Array;
precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;
};

@@ -381,3 +395,3 @@ };

```ts
export interface ExtPointType extends Group<ExtPointType> {
interface ExtPointType extends Group<ExtPointType> {
readonly ex: bigint;

@@ -396,3 +410,3 @@ readonly ey: bigint;

// Static methods of Extended Point with coordinates in X, Y, Z, T
export interface ExtPointConstructor extends GroupConstructor<ExtPointType> {
interface ExtPointConstructor extends GroupConstructor<ExtPointType> {
new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;

@@ -409,9 +423,10 @@ fromAffine(p: AffinePoint<bigint>): ExtPointType;

import { twistedEdwards } from '@noble/curves/abstract/edwards';
import { div } from '@noble/curves/abstract/modular';
import { Field, div } from '@noble/curves/abstract/modular';
import { sha512 } from '@noble/hashes/sha512';
const Fp = Field(2n ** 255n - 19n);
const ed25519 = twistedEdwards({
a: -1n,
d: div(-121665n, 121666n, 2n ** 255n - 19n), // -121665n/121666n
P: 2n ** 255n - 19n,
d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p
Fp,
n: 2n ** 252n + 27742317777372353535851937790883648493n,

@@ -436,9 +451,8 @@ h: 8n,

```ts
export type CurveFn = {
type CurveFn = {
CURVE: ReturnType<typeof validateOpts>;
getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;
sign: (message: Hex, privateKey: Hex) => Uint8Array;
verify: (sig: SigType, message: Hex, publicKey: PubKey, context?: Hex) => boolean;
ExtendedPoint: ExtendedPointConstructor;
Signature: SignatureConstructor;
getPublicKey: (privateKey: Hex) => Uint8Array;
sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array;
verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean;
ExtendedPoint: ExtPointConstructor;
utils: {

@@ -461,3 +475,3 @@ randomPrivateKey: () => Uint8Array;

You must specify curve field, `a24` special variable, `montgomeryBits`, `nByteLength`, and coordinate `u` of generator point.
You must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`.

@@ -468,12 +482,8 @@ ```typescript

const x25519 = montgomery({
P: 2n ** 255n - 19n,
a24: 121665n, // TODO: change to a
Fp: Field(2n ** 255n - 19n),
a: 486662n,
Gu: 9n,
montgomeryBits: 255,
nByteLength: 32,
Gu: '0900000000000000000000000000000000000000000000000000000000000000',
// Optional params
powPminus2: (x: bigint): bigint => {
return mod.pow(x, P - 2, P);
},
// Optional param
adjustScalarBytes(bytes) {

@@ -492,7 +502,33 @@ bytes[0] &= 248;

Every curve has exported `hashToCurve` and `encodeToCurve` methods:
```ts
import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1';
import { randomBytes } from '@noble/hashes/utils';
console.log(hashToCurve(randomBytes()));
console.log(encodeToCurve(randomBytes()));
import { bls12_381 } from '@noble/curves/bls12-381';
bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' });
bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' });
```
If you need low-level methods from spec:
`expand_message_xmd` [(spec)](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1) produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
```ts
function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array;
function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array;
function expand_message_xmd(
msg: Uint8Array,
DST: Uint8Array,
lenInBytes: number,
H: CHash
): Uint8Array;
function expand_message_xof(
msg: Uint8Array,
DST: Uint8Array,
lenInBytes: number,
k: number,
H: CHash
): Uint8Array;
```

@@ -509,18 +545,2 @@

function hash_to_field(msg: Uint8Array, count: number, options: htfOpts): bigint[][];
type htfOpts = {
DST: string; // a domain separation tag defined in section 2.2.5
// p: the characteristic of F
// where F is a finite field of characteristic p and order q = p^m
p: bigint;
// m: the extension degree of F, m >= 1
// where F is a finite field of characteristic p and order q = p^m
m: number;
k: number; // the target security level for the suite in bits defined in section 5.1
expand?: 'xmd' | 'xof'; // option to use a message that has already been processed by expand_message_xmd
// Hash functions for: expand_message_xmd is appropriate for use with a
// wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others.
// BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247
// TODO: verify that hash is shake if expand==='xof' via types
hash: CHash;
};
```

@@ -559,6 +579,2 @@

The module also contains useful `hashToPrivateScalar` method which allows to create
scalars (e.g. private keys) with the modulo bias being neglible. It follows
FIPS 186 B.4.1. Requires at least 40 bytes of input for 32-byte private key.
```ts

@@ -576,5 +592,28 @@ import * as mod from '@noble/curves/abstract/modular';

mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion
mod.hashToPrivateScalar(sha512_of_something, secp256r1.n);
```
#### Creating private keys from hashes
Suppose you have `sha256(something)` (e.g. from HMAC) and you want to make a private key from it.
Even though p256 or secp256k1 may have 32-byte private keys,
and sha256 output is also 32-byte, you can't just use it and reduce it modulo `CURVE.n`.
Doing so will make the result key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/).
To avoid the bias, we implement FIPS 186 B.4.1, which allows to take arbitrary
byte array and produce valid scalars / private keys with bias being neglible.
Use [hash-to-curve](#abstracthash-to-curve-hashing-strings-to-curve-points) if you need
hashing to **public keys**; the function in the module instead operates on **private keys**.
```ts
import { p256 } from '@noble/curves/p256';
import { sha256 } from '@noble/hashes/sha256';
import { hkdf } from '@noble/hashes/hkdf';
const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2)
const derived = hkdf(sha256, someKey, undefined, 'application', 40); // 40 bytes
const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n);
```
### abstract/utils: General utilities

@@ -590,4 +629,4 @@

utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));
utils.numberToBytesBE(123n);
utils.numberToBytesLE(123n);
utils.numberToBytesBE(123n, 32);
utils.numberToBytesLE(123n, 64);
utils.numberToHexUnpadded(123n);

@@ -680,5 +719,5 @@ utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef]));

## In the wild
## Resources
Elliptic curve calculator: [paulmillr.com/ecc](https://paulmillr.com/ecc).
Article about some of library's features: [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). Elliptic curve calculator: [paulmillr.com/ecc](https://paulmillr.com/ecc)

@@ -690,2 +729,3 @@ - secp256k1

- BLS12-381
- Check out `bls12-381.ts` for articles about the curve
- Threshold sigs demo [genthresh.com](https://genthresh.com)

@@ -692,0 +732,0 @@ - BBS signatures [github.com/Wind4Greg/BBS-Draft-Checks](https://github.com/Wind4Greg/BBS-Draft-Checks) following [draft-irtf-cfrg-bbs-signatures-latest](https://identity.foundation/bbs-signature/draft-irtf-cfrg-bbs-signatures.html)

@@ -52,3 +52,2 @@ import { mod } from './abstract/modular.js';

isValidPrivateKey(privateKey: PrivKey): boolean;
hashToPrivateKey: (hash: Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -64,2 +63,6 @@ precompute: (windowSize?: number | undefined, point?: PointType<bigint> | undefined) => PointType<bigint>;

};
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
declare function lift_x(x: bigint): PointType<bigint>;

@@ -77,2 +80,3 @@ /**

* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/

@@ -79,0 +83,0 @@ declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean;

@@ -105,2 +105,3 @@ "use strict";

}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toRawBytes(true).slice(1);

@@ -112,4 +113,5 @@ const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32);

const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
const d = exports.secp256k1.utils.normPrivateKeyToScalar(priv);
const d = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
const point = Point.fromPrivateKey(d); // P = d'⋅G; 0 < d' < n check is done inside

@@ -119,2 +121,6 @@ const scalar = point.hasEvenY() ? d : modN(-d); // d = d' if has_even_y(P), otherwise d = n-d'

}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x) {

@@ -132,2 +138,5 @@ if (!fe(x))

}
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args) {

@@ -167,2 +176,3 @@ return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));

* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/

@@ -169,0 +179,0 @@ function schnorrVerify(signature, message, publicKey) {

@@ -260,3 +260,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normalizePrivateKey(privateKey));
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G2.ProjectivePoint) return sigPoint;

@@ -263,0 +263,0 @@ return Signature.encode(sigPoint);

@@ -14,7 +14,7 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
a24: bigint; // Related to d, but cannot be derived from it
a: bigint;
montgomeryBits: number;
powPminus2?: (x: bigint) => bigint;
xyToU?: (x: bigint, y: bigint) => bigint;
Gu: string;
Gu: bigint;
};

@@ -26,3 +26,3 @@ export type CurveFn = {

getPublicKey: (privateKey: Hex) => Uint8Array;
Gu: string;
GuBytes: Uint8Array;
};

@@ -34,3 +34,3 @@

{
a24: 'bigint',
a: 'bigint',
},

@@ -43,3 +43,3 @@ {

powPminus2: 'function',
Gu: 'string',
Gu: 'bigint',
}

@@ -56,3 +56,3 @@ );

const { P } = CURVE;
const modP = (a: bigint) => mod(a, P);
const modP = (n: bigint) => mod(n, P);
const montgomeryBits = CURVE.montgomeryBits;

@@ -81,2 +81,3 @@ const montgomeryBytes = Math.ceil(montgomeryBits / 8);

// Accepts 0 as well
function assertFieldElement(n: bigint): bigint {

@@ -88,2 +89,4 @@ if (typeof n === 'bigint' && _0n <= n && n < P) return n;

// x25519 from 4
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = (CURVE.a - BigInt(2)) / BigInt(4);
/**

@@ -100,4 +103,2 @@ *

const k = assertFieldElement(scalar);
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = CURVE.a24;
const x_1 = u;

@@ -181,4 +182,5 @@ let x_2 = _1n;

// Computes public key from private. By doing scalar multiplication of base point.
const GuBytes = encodeUCoordinate(CURVE.Gu);
function scalarMultBase(scalar: Hex): Uint8Array {
return scalarMult(scalar, CURVE.Gu);
return scalarMult(scalar, GuBytes);
}

@@ -191,4 +193,4 @@

getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),
Gu: CURVE.Gu,
GuBytes: GuBytes,
};
}

@@ -125,3 +125,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

ProjectivePoint: ProjConstructor<T>;
normalizePrivateKey: (key: PrivKey) => bigint;
normPrivateKeyToScalar: (key: PrivKey) => bigint;
weierstrassEquation: (x: T) => T;

@@ -207,4 +207,4 @@ isWithinCurveOrder: (num: bigint) => boolean;

// Validates if priv key is valid and converts it to bigint.
// Supports options CURVE.normalizePrivateKey and CURVE.wrapPrivateKey.
function normalizePrivateKey(key: PrivKey): bigint {
// Supports options allowedPrivateKeyLengths and wrapPrivateKey.
function normPrivateKeyToScalar(key: PrivKey): bigint {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;

@@ -292,3 +292,3 @@ if (lengths && typeof key !== 'bigint') {

static fromPrivateKey(privateKey: PrivKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}

@@ -494,4 +494,5 @@

* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @param affinePoint optional point ot save cached precompute windows on it
* @returns New point

@@ -524,2 +525,4 @@ */

* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point

@@ -580,3 +583,3 @@ */

ProjectivePoint: Point as ProjConstructor<T>,
normalizePrivateKey,
normPrivateKeyToScalar,
weierstrassEquation,

@@ -651,3 +654,2 @@ isWithinCurveOrder,

isValidPrivateKey(privateKey: PrivKey): boolean;
hashToPrivateKey: (hash: Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -677,3 +679,3 @@ precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;

ProjectivePoint: Point,
normalizePrivateKey,
normPrivateKeyToScalar,
weierstrassEquation,

@@ -688,3 +690,2 @@ isWithinCurveOrder,

if (isCompressed) {
// TODO: hasEvenY
return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);

@@ -813,3 +814,3 @@ } else {

try {
normalizePrivateKey(privateKey);
normPrivateKeyToScalar(privateKey);
return true;

@@ -820,27 +821,25 @@ } catch (error) {

},
normPrivateKeyToScalar: normalizePrivateKey,
normPrivateKeyToScalar: normPrivateKeyToScalar,
/**
* Converts some bytes to a valid private key. Needs at least (nBitLength+64) bytes.
*/
hashToPrivateKey: (hash: Hex): Uint8Array =>
ut.numberToBytesBE(mod.hashToPrivateScalar(hash, CURVE_ORDER), CURVE.nByteLength),
/**
* Produces cryptographically secure private key from random of size (nBitLength+64)
* as per FIPS 186 B.4.1 with modulo bias being neglible.
*/
randomPrivateKey: (): Uint8Array => utils.hashToPrivateKey(CURVE.randomBytes(Fp.BYTES + 8)),
randomPrivateKey: (): Uint8Array => {
const rand = CURVE.randomBytes(Fp.BYTES + 8);
const num = mod.hashToPrivateScalar(rand, CURVE_ORDER);
return ut.numberToBytesBE(num, CURVE.nByteLength);
},
/**
* 1. Returns cached point which you can use to pass to `getSharedSecret` or `#multiply` by it.
* 2. Precomputes point multiplication table. Is done by default on first `getPublicKey()` call.
* If you want your first getPublicKey to take 0.16ms instead of 20ms, make sure to call
* utils.precompute() somewhere without arguments first.
* @param windowSize 2, 4, 8, 16
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
return point;

@@ -876,3 +875,4 @@ },

* Computes shared public key from private key and public key.
* Checks: 1) private key validity 2) shared key is on-curve
* Checks: 1) private key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param privateA private key

@@ -887,3 +887,3 @@ * @param publicB different public key

const b = Point.fromHex(publicB); // check for being on-curve
return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}

@@ -911,6 +911,8 @@

const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
/**
* Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
*/
function int2octets(num: bigint): Uint8Array {
if (typeof num !== 'bigint') throw new Error('bigint expected');
if (!(_0n <= num && num < ORDER_MASK))
// n in [0..ORDER_MASK-1]
throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);

@@ -939,3 +941,3 @@ // works with order, can have different size than numToField!

const h1int = bits2int_modN(msgHash);
const d = normalizePrivateKey(privateKey); // validate private key, convert to bigint
const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
const seedArgs = [int2octets(d), int2octets(h1int)];

@@ -942,0 +944,0 @@ // extraEntropy. RFC6979 3.6: additional k' (optional).

@@ -141,6 +141,6 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

P: ED25519_P,
a24: BigInt('121665'),
a: BigInt(486662),
montgomeryBits: 255, // n is 253 bits
nByteLength: 32,
Gu: '0900000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(9),
powPminus2: (x: bigint): bigint => {

@@ -147,0 +147,0 @@ const P = ED25519_P;

@@ -125,7 +125,7 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

export const x448 = montgomery({
a24: BigInt(39081),
a: BigInt(156326),
montgomeryBits: 448,
nByteLength: 57,
P: ed448P,
Gu: '0500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
Gu: BigInt(5),
powPminus2: (x: bigint): bigint => {

@@ -132,0 +132,0 @@ const P = ed448P;

@@ -110,2 +110,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);

@@ -118,4 +119,5 @@ const numTo32b = (n: bigint) => numberToBytesBE(n, 32);

Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv: PrivKey) {
const d = secp256k1.utils.normPrivateKeyToScalar(priv);
const d = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
const point = Point.fromPrivateKey(d); // P = d'⋅G; 0 < d' < n check is done inside

@@ -125,2 +127,6 @@ const scalar = point.hasEvenY() ? d : modN(-d); // d = d' if has_even_y(P), otherwise d = n-d'

}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x: bigint): PointType<bigint> {

@@ -136,2 +142,5 @@ if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.

}
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args: Uint8Array[]): bigint {

@@ -176,2 +185,3 @@ return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));

* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/

@@ -178,0 +188,0 @@ function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {

@@ -97,10 +97,10 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

function normalizePrivateKey(privKey: Hex) {
function normPrivKey(privKey: Hex) {
return cutils.bytesToHex(ensureBytes0x(privKey)).padStart(64, '0');
}
function getPublicKey0x(privKey: Hex, isCompressed = false) {
return starkCurve.getPublicKey(normalizePrivateKey(privKey), isCompressed);
return starkCurve.getPublicKey(normPrivKey(privKey), isCompressed);
}
function getSharedSecret0x(privKeyA: Hex, pubKeyB: Hex) {
return starkCurve.getSharedSecret(normalizePrivateKey(privKeyA), pubKeyB);
return starkCurve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
}

@@ -110,3 +110,3 @@

if (typeof privKey === 'string') privKey = strip0x(privKey).padStart(64, '0');
return starkCurve.sign(ensureBytes0x(msgHash), normalizePrivateKey(privKey), opts);
return starkCurve.sign(ensureBytes0x(msgHash), normPrivKey(privKey), opts);
}

@@ -113,0 +113,0 @@ function verify0x(signature: Hex, msgHash: Hex, pubKey: Hex) {

@@ -45,3 +45,2 @@ import { ProjPointType } from './abstract/weierstrass.js';

isValidPrivateKey(privateKey: cutils.PrivKey): boolean;
hashToPrivateKey: (hash: cutils.Hex) => Uint8Array;
randomPrivateKey: () => Uint8Array;

@@ -48,0 +47,0 @@ precompute: (windowSize?: number | undefined, point?: ProjPointType<bigint> | undefined) => ProjPointType<bigint>;

@@ -98,11 +98,11 @@ "use strict";

}
function normalizePrivateKey(privKey) {
function normPrivKey(privKey) {
return cutils.bytesToHex(ensureBytes0x(privKey)).padStart(64, '0');
}
function getPublicKey0x(privKey, isCompressed = false) {
return exports.starkCurve.getPublicKey(normalizePrivateKey(privKey), isCompressed);
return exports.starkCurve.getPublicKey(normPrivKey(privKey), isCompressed);
}
exports.getPublicKey = getPublicKey0x;
function getSharedSecret0x(privKeyA, pubKeyB) {
return exports.starkCurve.getSharedSecret(normalizePrivateKey(privKeyA), pubKeyB);
return exports.starkCurve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
}

@@ -113,3 +113,3 @@ exports.getSharedSecret = getSharedSecret0x;

privKey = (0, exports.strip0x)(privKey).padStart(64, '0');
return exports.starkCurve.sign(ensureBytes0x(msgHash), normalizePrivateKey(privKey), opts);
return exports.starkCurve.sign(ensureBytes0x(msgHash), normPrivKey(privKey), opts);
}

@@ -116,0 +116,0 @@ exports.sign = sign0x;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc