Raghu
Raghu

Reputation: 3091

How to sign a message using ECDSA with an ECDiffieHellman instance in .net framework 4.7.1?

Assume that ECDiffieHellman instance can be used for signing also.

If I have valid ECDiffieHellman (ECDH) instance, how do I go about creating a signature using ECDSA using ECDH instance in .net framework?

I figured that I could verify the signature in following way:

        ECDiffieHellman ecdh;   //Already have this instance
        var verifyKey = CngKey.Import(ecdh.PublicKey.ToByteArray(), CngKeyBlobFormat.EccPublicBlob);
        var ecDsa = new ECDsaCng(verifyKey);
        var dataBytes = ASCIIEncoding.ASCII.GetBytes("Hello!");
        var verifyResult = ecDsa.VerifyData(dataBytes, signatureBytesToCheck, HashAlgorithmName.SHA256);

I tried to follow the similar model for CngKey for private key (for signing). I am having trouble at creating CngKey with private key bytes.

        ECDiffieHellman ecdh;   //Already have this instance
        var ecdhParams = ecdhCasd.ExportParameters(true);
        var ecdhPrivateKeyBytes = ecdhParams.D;
        var signingKey = CngKey.Import(ecdhPrivateKeyBytes, CngKeyBlobFormat.EccPrivateBlob);

I tried using GenericPrivateBlob, EccFullPrivateBlob for format. Still nothing worked.

Am I on the correct path? If so, what am I doing wrong?

Upvotes: 3

Views: 2116

Answers (2)

bartonjs
bartonjs

Reputation: 33256

In addition to exporting the key properties you should be able to do it with non-exportable keys:

ECDiffieHellmanCng ecdhChg = ecdh as ECDiffieHellmanCng;

// Export is required.
if (ecdhCng == null)
    return null;

return new ECDsa(ecdhCng.Key);

This is because on Windows CNG "ECDSA" keys are only allowed to do ECDSA; but "ECDH" keys can do both ECDSA and ECDH. At least, that's true for software private keys.

.NET started allowing ECDsaCng to be created over an ECDH key in .NET 4.6.2, so if you have the ECC ExportParameters methods available this should already work for you.

Upvotes: 1

Raghu
Raghu

Reputation: 3091

I was much closer than I thought. I finally figured that I simply had to use Create method instead of Import method as shown below:

    ECDiffieHellman ecdh;   //Already have this instance
    var ecdhParams = ecdhCasd.ExportParameters(true);
    var signer = ECDsa.Create(ecFullParams);
    var signedBytes = ecDsa.SignData(dataBytes, HashAlgorithmName.SHA256);

If I have only public key to verify:

    ECDiffieHellmanPublicKey ecdhPk; //Compute this with public key bytes
    var ecPkParams = ecdhPk.ExportParameters();
    var verifier = ECDsa.Create(ecPkParams);
    var verifyResult = verifier.VerifyData(bytesToBeVerified, signatureBytesToCheck, HashAlgorithmName.SHA256);

Upvotes: 1

Related Questions