让各个编码转换的方法 (b58_to_hex, hex_to_b32, ...) 在错误情况下返回 '' 而不是 null。不知道会不会导致其它地方的问题。

This commit is contained in:
luk
2024-11-03 11:50:21 +08:00
parent decdcab1e5
commit 62acb1c453
5 changed files with 88 additions and 530 deletions

32
test.js
View File

@@ -16,11 +16,7 @@ function ECPointDecompress (comp) {
var x = new bigInt(comp.substring(2), 16)
// y mod p = +-(x^3 + 7)^((p+1)/4) mod p
console.log('ECP x=', x.toString(), ' = ', x.toString(16))
var y = x
.modPow(3, prime)
.add(7)
.mod(prime)
.modPow(pIdent, prime)
var y = x.modPow(3, prime).add(7).mod(prime).modPow(pIdent, prime)
// If the parity doesn't match it's the *other* root
console.log('ECP y=', y.toString(), ' = ', y.toString(16))
if (y.mod(2).toJSNumber() !== signY) {
@@ -40,32 +36,17 @@ BigNumber = require('bignumber.js')
function uncompressPubkey (comp) {
// Consts for P256 curve. Adjust accordingly
const prime = new BigNumber('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 16).integerValue(),
pIdent = prime
.plus(1)
.idiv(4)
.integerValue()
pIdent = prime.plus(1).idiv(4).integerValue()
console.log('pIdent=', pIdent.toString(), ' = ', pIdent.toString(16))
var signY = new Number(comp[1]) - 2
var x = new BigNumber(comp.substring(2), 16).integerValue()
console.log('x=', x.toString(), ' = ', x.toString(16))
// y^2 = x^3 - 3x + b
var y = x
.pow(3)
.mod(prime)
.plus(7)
.mod(prime)
.pow(pIdent)
.mod(prime)
.integerValue()
var y = x.pow(3).mod(prime).plus(7).mod(prime).pow(pIdent).mod(prime).integerValue()
console.log('y=', y.toString(), ' = ', y.toString(16))
// If the parity doesn't match it's the *other* root
if (
y
.mod(2)
.integerValue()
.toNumber() !== signY
) {
if (y.mod(2).integerValue().toNumber() !== signY) {
// y = prime - y
y = prime.minus(y).integerValue()
}
@@ -129,10 +110,7 @@ crypto.createCipheriv('aes-256-cfb', Buffer.from(acc.prikey, 'hex'), Buffer.allo
////////////////////// crypto + PEM
toPEM = function (kp) {
let pubkey = crypto
.createECDH('secp256k1')
.setPrivateKey(kp.prikey, 'hex')
.getPublicKey('hex', 'compressed')
let pubkey = crypto.createECDH('secp256k1').setPrivateKey(kp.prikey, 'hex').getPublicKey('hex', 'compressed')
console.log('ECDH created publickey = ', pubkey)
let mykey = '308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b0201010420' + kp.prikey + 'a144034200' + pubkey
console.log(mykey)