Skip to content

Commit 13d7c9f

Browse files
author
Ian Tan
committed
fix(crypto): return compressed public keys only
1 parent 992aaa4 commit 13d7c9f

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

src/__tests__/util.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe('utils', () => {
1919
it('should recover a public key from a private key', () => {
2020
pairs.forEach(({private: priv, public: expected}) => {
2121
const actual = util.getPubKeyFromPrivateKey(priv);
22-
expect(actual).toEqual(expected);
22+
expect(actual).toEqual(util.compressPublicKey(expected));
2323
});
2424
});
2525

src/util.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
// another public or private blockchain network. This source code is provided ‘as is’ and no
88
// warranties are given as to title or non-infringement, merchantability or fitness for purpose
99
// and, to the extent permitted by law, all liability for your use of the code is disclaimed.
10+
import BN from 'bn.js';
1011
import randomBytes from 'randombytes';
1112
import elliptic from 'elliptic';
1213
import hashjs from 'hash.js';
@@ -63,14 +64,25 @@ export const getAddressFromPrivateKey = (privateKey: string) => {
6364
* getPubKeyFromPrivateKey
6465
*
6566
* takes a hex-encoded string (private key) and returns its corresponding
66-
* hex-encoded 32-byte public key.
67+
* hex-encoded 33-byte public key.
6768
*
6869
* @param {string} privateKey
6970
* @returns {string}
7071
*/
7172
export const getPubKeyFromPrivateKey = (privateKey: string) => {
7273
const keyPair = secp256k1.keyFromPrivate(privateKey, 'hex');
73-
return keyPair.getPublic(false, 'hex');
74+
return keyPair.getPublic(true, 'hex');
75+
};
76+
77+
/**
78+
* compressPublicKey
79+
*
80+
* @param {string} publicKey - 65-byte public key, a point (x, y)
81+
*
82+
* @returns {string}
83+
*/
84+
export const compressPublicKey = (publicKey: string): string => {
85+
return secp256k1.keyFromPublic(publicKey, 'hex').getPublic(true, 'hex');
7486
};
7587

7688
/**

typings/elliptic.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ declare module 'elliptic' {
3838
interface EC {
3939
curve: Curve;
4040
keyFromPrivate(priv: string, enc: string): KeyPair;
41-
keyFromPublic(pub: BN, enc: string): KeyPair;
41+
keyFromPublic(pub: string, enc: string): KeyPair;
4242
}
4343

4444
interface KeyPair {

0 commit comments

Comments
 (0)