indutny / elliptic

Fast Elliptic Curve Cryptography in plain javascript
1.7k stars 381 forks source link

Missing leading zero when exporting as BN object #207

Closed hfossli closed 4 years ago

hfossli commented 4 years ago

When running this code

const key1 = ec.genKeyPair();
console.log(key1);
console.log(key1.getPrivate("hex"));
console.log(key1.getPrivate().toString("hex"));

I get

<Key priv: 0f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0 pub: null > 
0f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0
f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0 

But I expected

<Key priv: 0f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0 pub: null > 
0f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0
0f6fa353aea3d2a992eff69423b8479279b90fd00675e657b8d5d1cbf92709f0 

(notice the leading zero is missing when exporting the key as .getPrivate().toString("hex") instead of .getPrivate("hex"))

Is this a bug or is it by design?

fanatid commented 4 years ago

This happened because you need call toString as toString('hex', 2) for padding. If you check getPrivate code, you can see that getPrivate('hex') equal to getPrivate().toString(16, 2). https://github.com/indutny/elliptic/blob/60489415e545efdfd3010ae74b9726facbf08ca8/lib/elliptic/ec/key.js#L69-L74

hfossli commented 4 years ago

Aweeesome!🥰

hfossli commented 4 years ago

🤔 what if.... what if the key randomly has 2 or more leading zeros, wouldn't it then be better to say toString(16, 32)? Doesn't matter?

fanatid commented 4 years ago

Yes, right call will be toString(16, 32). Sorry for first wrong example.

hfossli commented 4 years ago

Thanks. I don't know. I know from secp256r1 that leading zeros is important if the first hex value is >= 80