Search code examples
node.jscryptographydiffie-hellman

custom private key with crypto in node.js


from: https://nodejs.org/api/crypto.html#crypto_class_ecdh

const alice_key = alice.generateKeys();

will generate a random private key and the corresponding public key.

But I would like to set my own private key: e8f32e723decf...

If I use :

alice.setPrivateKey("e8f32e723decf");

the object alice_key is not affected, so later:

const bob_secret = bob.computeSecret(alice_key, 'hex', 'hex');

will be wrong. Is there a way to do something like:

const alice_key = alice.generateKeys("e8f32e723decf");

Solution

  • First of all I suppose your hex string is missing a leading 0, so it should be 0e8f32e723decf.

    Then it depends on your node.js version, the implementation of ECDH.setPrivateKey() changed from 5.1 to 5.2


    node.js 5.0

    • You need to generate the keys and override them
    • You need to have the public and the private key
    • Working online example
    
    const crypto = require('crypto');
    
    // this is just to generate a private/public key pair
    const warmup = crypto.createECDH('secp521r1');
    warmup.generateKeys();
    const warmup_private_key = warmup.getPrivateKey();
    const warmup_public_key = warmup.getPublicKey();
    
    // convert it to hex string to match the example
    // you would store these strings somewhere I guess
    private_key = warmup_private_key.toString('hex');
    public_key = warmup_public_key.toString('hex');
    
    // now let's create the ciphers
    const alice = crypto.createECDH('secp521r1');
    const bob = crypto.createECDH('secp521r1');
    
    
    ----------
    
    
    // Bob gets created keys
    bob.generateKeys();
    
    // Generate Alice's keys - that's really annoying since you will override it
    alice.generateKeys();
    // now set the keys:
    alice.setPrivateKey(private_key, "hex");
    alice.setPublicKey(public_key, "hex");
    
    // Exchange and generate the secret...
    const alice_secret = alice.computeSecret(bob.getPublicKey());
    const bob_secret = bob.computeSecret(alice.getPublicKey());
    
    console.log("alice's shared secret: " + alice_secret.toString('hex') + "\n");
    console.log("bob's shared secret:   " + bob_secret.toString('hex') + "\n");
    
    console.log('shared secrets match: ' +  alice_secret.equals(bob_secret));
    

    node.js >= 5.2

    
    const crypto = require('crypto');
    const alice = crypto.createECDH('secp256k1');
    const bob = crypto.createECDH('secp256k1');
    bob.generateKeys();
    
    alice.setPrivateKey('0e8f32e723decf', 'hex');
    
    const alice_secret = alice.computeSecret(bob.getPublicKey());
    const bob_secret = bob.computeSecret(alice.getPublicKey());
    
    console.log(alice_secret.equals(bob_secret));