Creating an ECC Private/Public key with native C#

后端 未结 2 806
失恋的感觉
失恋的感觉 2021-01-06 01:32

I\'ve been looking around for hours on Google and Microsoft\'s Crypto API on how to generate a public and private ECC key pair. The ECDiffieHellmanCng Class (ht

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 02:17

    I believe this is what you are looking for? If yes, please mark as (my first!) answer :-)

    Most of this related to the CngKey, that can be used in many variations.

        static void test1()
        {
            CngKey k;
    
            if (CngKey.Exists("myECDH", CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey))
            {
                k = CngKey.Open("myECDH", CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey);
            }
            else
            {
                k = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, "myECDH", new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey,
                KeyUsage = CngKeyUsages.AllUsages,
                Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                UIPolicy = new CngUIPolicy(CngUIProtectionLevels.None)
            });
            }
    
            byte[] privateBytes = k.Export(CngKeyBlobFormat.EccPrivateBlob);
            byte[] publicBytes = k.Export(CngKeyBlobFormat.EccPublicBlob);
    
            //This:
            var privateTester1 =
                new ECDiffieHellmanCng(CngKey.Import(privateBytes, CngKeyBlobFormat.EccPrivateBlob,
                    CngProvider.MicrosoftSoftwareKeyStorageProvider));
    
            //Or that:
            var privateTester2 = new ECDiffieHellmanCng(k);
        }
    

提交回复
热议问题