0.2.2 • Published 5 months ago

curve-p256 v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

curve-p256

This is a JS implementation of secp256r1 (P-256) elliptic curve algorithm, used for ECDH & ECDSA signatures. This library is extract from @noble/curves.

In addition, I added support for Wechat Mini Programs. Since @noble/curves relies on the instance methods of Crypto in Web Crypto API, but Wechat Mini Programs do not support them yet, I implemented these methods myself.


这是一个 JS 实现的 secp256r1 (P-256) 椭圆曲线算法库,用于 ECDHECDSA 签名。这个库是从@noble/curves 中提取出来的。

另外,我对微信小程序做了支持。由于 @noble/curves 依赖了 Web Crypto APICrypto 的实例方法,但小程序尚未支持,所以我实现了这些方法。

Usage

NPM:

npm i curve-p256

YARN:

yarn add curve-p256

Example:

import { p256, bytesToHex } from 'curve-p256';

const privateKey = p256.utils.randomPrivateKey();
const publicKey = p256.getPublicKey(privateKey); // Convert private key to public.

// publicKeyHex looks like: '0339e1f15f1b22e4d4c5b9556a6bb316b8ed1ef33ac92adc4c677d3b5d7a3aa111'
const publicKeyHex = bytesToHex(publicKey);

// ECDSA signature scheme
const msg = 'Hello world!';
const sig = p256.sign(msg, privateKey); // Sign msg with private key.
const sig2 = p256.sign(msg, privateKey, { prehash: true }); // hash(msg)
const isValid = p256.verify(sig, msg, privateKey); // Verify if sig is correct.

// ECDH: Elliptic Curve Diffie-Hellman
const someonesPublicKey = '02fd492bc63582520bea1e06edb2ad311569607d58080679c95239d57aa1bc1d1b';
const sharedSecret = p256.getSharedSecret(privateKey, someonesPublicKey);

Utils

import { bytesToHex, hexToBytes, concatBytes } from 'curve-p256';

// hex = 'deadbeef'
const hex = bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));

// bytes = Uint8Array.from([0xde, 0xad, 0xbe, 0xef])
const bytes = hexToBytes('deadbeef');

// bytes = Uint8Array.from([0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef])
const concated = concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef]));

Speed

Benchmark results on Apple M2 with node v20:

p256
init x 38 ops/sec @ 26ms/op
getPublicKey x 6,530 ops/sec @ 153μs/op
sign x 5,074 ops/sec @ 197μs/op
verify x 626 ops/sec @ 1ms/op

ecdh
p256 x 511 ops/sec @ 1ms/op