elliptic icon indicating copy to clipboard operation
elliptic copied to clipboard

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

Open cqupt-yifanwu opened this issue 4 years ago • 4 comments

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

cqupt-yifanwu avatar Jul 10 '20 01:07 cqupt-yifanwu

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

indutny avatar Jul 10 '20 02:07 indutny

@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

cqupt-yifanwu avatar Jul 10 '20 03:07 cqupt-yifanwu

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

indutny avatar Jul 10 '20 03:07 indutny

it is worked for me, thx~

cqupt-yifanwu avatar Jul 10 '20 03:07 cqupt-yifanwu