indutny / elliptic

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

why use derive method get ECDH key,i got different length #230

Open cqupt-yifanwu opened 4 years ago

cqupt-yifanwu commented 4 years ago

my code is

const serverPubKey = '04A742E3FE7F4AC8D20C5007261A2DCB3AAED7F039FEE724683C1350E3BEA47FC81E1CF4B2AAD04432B727A2615214D97E51C801D911D6DB235ADAD952A43C5864
const instance = new EC('p256') 
const ecKeyPair =instance.genKeyPair()
const ECDHKey = ecKeyPair.derive(serverPubKey).toString(16)

i expect the ECDHKey.length = 64, but sometimes i found ECDHKey.length = 63; One-tenth probability can got ECDHKey.length = 63, it may cause an error when i use ECDHKey to Encrypt my data

indutny commented 4 years ago

This is because .toString(16) doesn't pad the output. Try using .toBuffer('be', 64).toString('hex') instead.

cqupt-yifanwu commented 4 years ago

@indutny thx for replay, but when i try

.toBuffer('be', 64).toString('hex')

it cause another error

image

in bn.js

image

image

i try install buffer npm package, this question still alive, browser may not support use require in runtime

indutny commented 4 years ago

Oh, if you are using it not in Node - you can try .toString(16, 64)

cqupt-yifanwu commented 4 years ago

it is worked for me, thx~