Janso123
Janso123

Reputation: 200

ECDH nodejs and C# key exchange

I've lost my self and I need help to go in the right direction :) I have nodejs server that have to exchange some critical data with the server that is written in C#, so in that case, I want my data to be encrypted somehow. I was thinking about AES, and to safely exchange keys i want to use ECDH but I don't know how to make it work correctly... If I'm thinking right way I can make my C# "allice" side like this :

ECDiffieHellman alice = ECDiffieHellman.Create(ECCurve.NamedCurves.brainpoolP192t1);
var aliceKey = alice.PublicKey;
var ketyToExport = Convert.ToBase64String(aliceKey.ToByteArray());
//send ketyToExport to nodejs
//KEY FROM nodejs
var key1 = Convert.FromBase64String("BIzSJ1dmTXpSS8rqkVFISZ+vumhqXYMWfWoU5vB9GHhOtxxDInu/GZ92VJpqhrE3vw==").ToList();
var keyType = new byte[] { 0x45, 0x43, 0x4B, 0x31 };
var keyLength = new byte[] { 0x20, 0x00, 0x00, 0x00 };
key1.RemoveAt(0);
key1 = keyType.Concat(keyLength).Concat(key1).ToList();
byte[] bobKeyBytes = key1.ToArray();
//and I have a problem with that line bellow, I do not know how to make it work
var aliceSecret = alice.DeriveKeyMaterial(/*ECDiffieHellmanPublicKey bobKeyBytes*/);

And nodejs "Bob" side like this:

const crypto = require("crypto");
const bob = crypto.createECDH('brainpoolP192t1')
const bobKey = bob.generateKeys('base64');
var bobLength = Buffer.from(bobKey, 'base64').length;
//send bobkey to c#
//recive alicekey
var tmp = "RUNLUBgAAAAR9C7kO2o+vxNT/UBvvEuJHNdI8NfU4fUxUT431ER1q3kJbeUVHepoG5SWUM2NHj8="
var aliceKeyBuffer = Buffer.from(tmp, 'base64');
var aliceKey = Buffer.alloc(bobLength)
aliceKeyBuffer.copy(aliceKey, 1, 8);
aliceKey[0] = 4;
bob.computeSecret(aliceKey);
//create aes 
//get mesage and iv ...

Okay so I've made some adjustments to all of that but right now I don't know what to do about this line how to make it work... var aliceSecret = alice.DeriveKeyMaterial(/*ECDiffieHellmanPublicKey bobKeyBytes*/);

#BIG EDIT I got help in ECDiffieHellmanPublicKey from ByteArray (using ECDiffieHellman NamedCurves) and now I have another problem -_- my node js code didn't change from above but c# looks like:

using (ECDiffieHellman alice = ECDiffieHellman.Create(ECCurve.NamedCurves.brainpoolP256r1))
{
    var alicePublicKey = Convert.ToBase64String(alice.PublicKey.ToByteArray());
    //NODEJS brainpoolP256r1 publickey 
    var key1 = Convert.FromBase64String("BASsbkule53ARqlMBA8hYysyyoRi3xGxGnSzIJ2fS5FlLniQD/zYiiGUVydmO/BBkQwVTUo5f4OMCxVNtQ/LuMQ=");
    byte[] keyX = new byte[key1.Length / 2];
    byte[] keyY = new byte[keyX.Length];
    Buffer.BlockCopy(key1, 1, keyX, 0, keyX.Length);
    Buffer.BlockCopy(key1, 1 + keyX.Length, keyY, 0, keyY.Length);
    ECParameters parameters = new ECParameters
    {
        Curve = ECCurve.NamedCurves.brainpoolP256r1,
        Q =
        {
            X = keyX,
            Y = keyY,
        },
    };
    byte[] derivedKey;
    using (ECDiffieHellman bob = ECDiffieHellman.Create(parameters))
    using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
    {
        derivedKey = alice.DeriveKeyFromHash(bobPublic, HashAlgorithmName.SHA256);
    }
    var aliceKey = Convert.ToBase64String(derivedKey);
    byte[] encryptedMessage = null;
    byte[] iv = null;
    // Send(aliceKey, "Secret message", out encryptedMessage, out iv);
}

and it is working but it gives me different secret keys ... out of bob.computeSecret(aliceKey) i got iIoH9aJoWf3666QQ6X+kj4iUKrk9j+hbRuXbhgs7YzM= and out of alice.DeriveKeyFromHash(bobPublic, HashAlgorithmName.SHA256); I got wJ7O4Hm2Jxs1FcLx6KaMmENvqdTQJPZ/YNSs1+MQDOQ= if I'm thinking correctly they should be equal. am I thinking wrong?

#EDIT DONE !!

So this adding this code on end of js file gave me what I needed.

const hash = crypto.createHash('sha256');
var tt = bob.computeSecret(aliceKey);
hash.update(tt);
console.log(hash.digest('base64'));

Upvotes: 1

Views: 1777

Answers (2)

Matt Goodrich
Matt Goodrich

Reputation: 143

The above answer helped me a lot. I am using secp521r1/nistP521 to do the key generation in both NodeJS and C#. In my case, a call to alice.PublicKey.ToByteArray() would result in an exception:

Unhandled exception. System.PlatformNotSupportedException: Operation is not supported on this platform.
   at System.Security.Cryptography.ECDiffieHellmanImplementation.ECDiffieHellmanSecurityTransforms.ECDiffieHellmanSecurityTransformsPublicKey.ToByteArray()

According to an issue logged with the dotnet runtime team here:

ECDiffieHellmanPublicKey.ToByteArray() doesn't have a (standards-)defined export format. The version used by ECDiffieHellmanPublicKeyCng is Windows-specific, and only works for NIST P-256 (secp256r1), NIST P-384 (secp384r1), and NIST P-521 (secp521r1).

To create a copy of a key you should use the ExportParameters() method to obtain the rich ECParameters object; which can then be sent through ECDiffieHellman.Create(ECParameters) and the PublicKey property of that object be read to get back a second instance of ECDiffieHellmanPublicKey.

Assuming I send my X and Y from Alice to Bob (I used hex instead of base64), the corresponding process to arrive at the same shared secret on the NodeJS side looks like this:

// Alice's public key X, Y coordinates from DotNet Core
const aliceHexX = '00248F624728B17196B22005742C13D80D3DFF75BCA74AF865195E5A29F41C013653B0931BC544245402EDD7922F38692F38DCCF780CF1A9E27D3CFB5E09E53883C0';
const aliceHexY = '0043517F3B2EF33ED70EFA2BC4163E9B99558A7C2ECB7C659A12EA4024633CFA8B9FC997F0A42D30759B4280FDADC13A67A3E7BB0227047C907FAAE92E7716E8A10D';

const alicePublicKeyXBytes = Buffer.from(aliceHexX, 'hex');
const alicePublicKeyYBytes = Buffer.from(aliceHexY, 'hex');
const alicePublicKey = Buffer.concat([Buffer.from([0x04]), alicePublicKeyXBytes, alicePublicKeyYBytes])
const bobSecret = bob.computeSecret(alicePublicKey);

const hash = crypto.createHash('sha256');
hash.update(bobSecret);
const sharedSecret = hash.digest('hex');
console.log(`Shared Secret: ${sharedSecret.toString('hex')}`);

Upvotes: 1

Janso123
Janso123

Reputation: 200

##SOLUTION##

C#

class Program
{
    static void Main(string[] args)
    {
        using (ECDiffieHellman alice = ECDiffieHellman.Create(ECCurve.NamedCurves.brainpoolP256r1))
        {
            var alicePublicKey = Convert.ToBase64String(alice.PublicKey.ToByteArray());
            //send alicePublicKey
            var nodejsKey = ""; //NODEJS brainpoolP256r1 publickey  base64
            byte[] nodejsKeyBytes= Convert.FromBase64String(nodejsKey);

            var aliceKey = Convert.ToBase64String(getDeriveKey(nodejsKeyBytes,alice));
            byte[] encryptedMessage = null;
            byte[] iv = null;
            // Send(aliceKey, "Secret message", out encryptedMessage, out iv);
        }
    }
    static byte[] getDeriveKey(byte[] key1, ECDiffieHellman alice)
    {
        byte[] keyX = new byte[key1.Length / 2];
        byte[] keyY = new byte[keyX.Length];
        Buffer.BlockCopy(key1, 1, keyX, 0, keyX.Length);
        Buffer.BlockCopy(key1, 1 + keyX.Length, keyY, 0, keyY.Length);
        ECParameters parameters = new ECParameters
        {
            Curve = ECCurve.NamedCurves.brainpoolP256r1,
            Q =
            {
                X = keyX,
                Y = keyY,
            },
        };
        byte[] derivedKey;
        using (ECDiffieHellman bob = ECDiffieHellman.Create(parameters))
        using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
        {
            return derivedKey = alice.DeriveKeyFromHash(bobPublic, HashAlgorithmName.SHA256);
        }
    }
}

NODEJS

const crypto = require("crypto");
const bob = crypto.createECDH('brainpoolP256r1')
bob.generateKeys();
const bobKey = bob.getPublicKey('base64');
var bobLength = Buffer.from(bobKey, 'base64').length;
//send bobkey to c#
//recive alicekey

var alicePublicKey = "RUNLUCAAAAB/xP7JhSIhYIYAijyC2zHu7obB5CwfK/ynQPxcRAIhBI6OLRRcHyPo61AhfSZN3qA2vGDfWO2mrdWWvqqhVaDf";
var aliceKeyBuffer = Buffer.from(alicePublicKey, 'base64');
var aliceKey = Buffer.alloc(bobLength)
aliceKeyBuffer.copy(aliceKey, 1, 8);
aliceKey[0] = 4;
const hash = crypto.createHash('sha256');
var tt = bob.computeSecret(aliceKey);
var bobSecretKey = hash.update(tt).digest('base64');

big thanks for @bartonjs and @Maarten Bodewes

Upvotes: 2

Related Questions