From 7b7d6d2ac98eae9dd6f44c57fcbfb8a444dc0612 Mon Sep 17 00:00:00 2001 From: Fuxing Loh Date: Sat, 17 Apr 2021 00:42:50 +0800 Subject: [PATCH] added lowr as default for getEllipticPairFromPrivateKey --- .../__tests__/elliptic.test.ts | 18 ++++++++++++++---- packages/jellyfish-crypto/src/elliptic.ts | 13 ++++++++++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/jellyfish-crypto/__tests__/elliptic.test.ts b/packages/jellyfish-crypto/__tests__/elliptic.test.ts index c5bc54d582..b1ce719326 100644 --- a/packages/jellyfish-crypto/__tests__/elliptic.test.ts +++ b/packages/jellyfish-crypto/__tests__/elliptic.test.ts @@ -109,8 +109,13 @@ describe('DER Signature: sign and verify', () => { return await shouldReturnPubKeyFromPubKey(privateKeyHex, publicKeyHex) }) - it('should sign hash Buffer and get signature', async () => { - return await shouldSignHashBufferGetSignature(privateKeyHex, hashHex, signatureHex) + it('should sign hash Buffer and verify signature', async () => { + const privateKey = Buffer.from(privateKeyHex, 'hex') + const curvePair = elliptic.getEllipticPairFromPrivateKey(privateKey) + + const hash = Buffer.from(hashHex, 'hex') + const signature = await curvePair.sign(hash) + expect(curvePair.verify(hash, signature)).toBeTruthy() }) it('should verify hash with signature', async () => { @@ -128,8 +133,13 @@ describe('DER Signature: sign and verify', () => { return await shouldReturnPubKeyFromPubKey(privateKeyHex, publicKeyHex) }) - it('should sign hash Buffer and get signature', async () => { - return await shouldSignHashBufferGetSignature(privateKeyHex, hashHex, signatureHex) + it('should sign hash Buffer and verify signature', async () => { + const privateKey = Buffer.from(privateKeyHex, 'hex') + const curvePair = elliptic.getEllipticPairFromPrivateKey(privateKey) + + const hash = Buffer.from(hashHex, 'hex') + const signature = await curvePair.sign(hash) + expect(curvePair.verify(hash, signature)).toBeTruthy() }) it('should verify hash with signature', async () => { diff --git a/packages/jellyfish-crypto/src/elliptic.ts b/packages/jellyfish-crypto/src/elliptic.ts index a951af071a..8932baefe7 100644 --- a/packages/jellyfish-crypto/src/elliptic.ts +++ b/packages/jellyfish-crypto/src/elliptic.ts @@ -62,7 +62,18 @@ class SECP256K1 implements EllipticPair { } async sign (hash: Buffer): Promise { - const signature = ecc.sign(hash, this.privKey) + let signature = ecc.sign(hash, this.privKey) + + const extraData = Buffer.alloc(32, 0) + let counter = 0 + + // if first try is lowR, skip the loop, for second try and on, add extra entropy counting up + while (signature[0] > 0x7f) { + counter++ + extraData.writeUIntLE(counter, 0, 6) + // @ts-expect-error + signature = ecc.signWithEntropy(hash, this.privKey, extraData) + } return DERSignature.encode(signature) }