From eec8f6184c54be7d4c67e5ef0db592d2bc11cb44 Mon Sep 17 00:00:00 2001 From: Justin Starry Date: Wed, 28 Aug 2019 10:45:17 -0400 Subject: [PATCH] fix: reject base58 public keys that are too short (#474) --- web3.js/src/publickey.js | 6 +++++- web3.js/test/publickey.test.js | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/web3.js/src/publickey.js b/web3.js/src/publickey.js index cd2d9810ac..c2fc63b434 100644 --- a/web3.js/src/publickey.js +++ b/web3.js/src/publickey.js @@ -19,7 +19,11 @@ export class PublicKey { this._bn = new BN(value.substring(2), 16); } else { // assume base 58 encoding by default - this._bn = new BN(bs58.decode(value)); + const decoded = bs58.decode(value); + if (decoded.length != 32) { + throw new Error(`Invalid public key input`); + } + this._bn = new BN(decoded); } } else { this._bn = new BN(value); diff --git a/web3.js/test/publickey.test.js b/web3.js/test/publickey.test.js index 3129c06523..d861573a5e 100644 --- a/web3.js/test/publickey.test.js +++ b/web3.js/test/publickey.test.js @@ -51,6 +51,10 @@ test('invalid', () => { '135693854574979916511997248057056142015550763280047535983739356259273198796800000', ); }).toThrow(); + + expect(() => { + new PublicKey('12345'); + }).toThrow(); }); test('equals', () => { @@ -170,6 +174,14 @@ test('toBuffer', () => { ); expect(key2.toBuffer()).toHaveLength(32); expect(key2.toBase58()).toBe('11111111111111111111111111111111'); + + const key3 = new PublicKey(0); + expect(key3.toBuffer()).toHaveLength(32); + expect(key3.toBase58()).toBe('11111111111111111111111111111111'); + + const key4 = new PublicKey('0x0'); + expect(key4.toBuffer()).toHaveLength(32); + expect(key4.toBase58()).toBe('11111111111111111111111111111111'); }); test('equals (II)', () => {