Diffie Hellman Key exchange with .Net Cryptography

Hello,

I am attempting to perform a Diffie Hellman Keyexchange with a server running on .Net.

However, the secretKey I am creating on the client side does not match with the secretKey on the server side, which I have for testing purposes.

I can import the server secret key as a SymetricKey, and if I use it to seal and open a box, it works. However, if I seal the box with my client key, I can not open it with the server shared key.

I create the SymetricKey like this:

let sharedHash = SHA256.self
let sharedInfo = serverPublicKey.rawRepresentation
let sharedLength = 32
let symetricKey = sharedSecret.x963DerivedSymmetricKey(
    using: sharedHash,
    sharedInfo: Data(),
    outputByteCount: sharedLength)

The server key is created using .Net like this:

            bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            bob.HashAlgorithm = CngAlgorithm.Sha256;
            bobPublicKey = bob.PublicKey.ToByteArray();
            bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob));

My assumption is the keys should be the same. Is that correct?

How can I find out what format the server key is in? The .Net documentation is not particularly precise on that

You can find a Playground of my code, and when you google for ECDiffieHellmanCng Class, you will find an example on what .Net does.

Any help is appreciated

Replies

How can I find out what format the server key is in?

My cheat for that is On Cryptographic Key Formats.

With problems like this I usually start by getting things working in ‘loopback’ mode on one platform, partly so that I understand the basics and partly so that I can understand the data formats it expects. I then repeat that process on the other platform. Now that I know the data formats that I expect in each case, I can compare the two to see if they make sense.

On the Apple CryptoKit front, I have a loopback example here.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thank you for your reply. Loopbacks and further experimentation, as well as reading code from .Net and Android got me the solution:

        let symmetricKey = sharedSecret.withUnsafeBytes { rawBufferPointer in
            var sha = SHA256()
            sha.update(bufferPointer: rawBufferPointer)
            let digest = sha.finalize()
            return SymmetricKey(data: digest)
        }
        return symmetricKey

My biggest question here is: Is this x9.63 or hkdf, and I am simply using these functions wrong? Or is this derivation method missing from CryptoKit?