ECDH-CngKey.Import异常:“参数不正确”

时间:2018-07-24 20:17:16

标签: exception import ecdh

我正在尝试为第一方生成公钥。然后生成一个共享密钥。 X和Y坐标提供给第二方的公共密钥。 我可以成功生成第一方的公钥。当我尝试通过CnKey.Import()使用第二方的公钥时,出现异常。代码如下所示:

public static void ecdh(ECDH_Parameters testParams)
{
    ECCurve curve = ECCurve.NamedCurves.nistP256;
    ECDiffieHellmanCng ecp1 = new ECDiffieHellmanCng(curve);

    // Generate public key for first party
    ecp1.HashAlgorithm = CngAlgorithm.Sha256;
    ecp1.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
    ecp1.GenerateKey(curve);

    // export the parameters into ECParameters structure
    ECParameters ecparam =  ecp1.ExportParameters(true);
    testParams.QIUTx = ecparam.Q.X; // X co-ordinate of first party public key
    testParams.QIUTy = ecparam.Q.Y; // Y co-ordinate of first party public key

    // For second party, X and Y co-ordinates are already provided. Combine them into 1 string
    String qavsx = BytesToHex.bytesToHex(testParams.QCAVSx);
    String qavsy = BytesToHex.bytesToHex(testParams.QCAVSy);
    String ecKey = qavsx + qavsy;

    // Convert the second party's pubkey into byte array from string
    byte[] arr = new byte[testParams.QCAVSx.Length + testParams.QCAVSy.Length];
    arr = ecKey.GetBytes();

    // Generate shared secret for first party using second party's pub key
    testParams.ZIUT = ecp1.DeriveKeyMaterial(CngKey.Import(arr, CngKeyBlobFormat.EccPublicBlob));   <--- ERROR!

    return;
}

public class ECDH_Parameters
{
    byte[] QCAVSx = new byte['?']; // second party pub key X-Co-ordinate
    byte[] QCAVSy = new byte['?']; // second party pub key Y-Co-ordinate
    byte[] QIUTx = new byte['?']; // first party pub key X-Co-ordinate
    byte[] QIUTy = new byte['?']; // first party pub key X-Co-ordinate
    byte[] ZIUT = new byte['?']; // first party shared secret 
}

我已经检查了DeriveKeyMaterial的用法,看起来我坚持使用该格式。我的代码有什么问题吗?

0 个答案:

没有答案