Beispiel #1
0
        private static void ReadOpenSSLKeyTest()
        {
            //待签名数据
            byte[] data = Encoding.UTF8.GetBytes("Hello World.");

            //读取OpenSSL产生的椭圆私钥和公钥
            CngKey privateKey = OpenSSLKeyECC.GetPrivateKey(@"..\..\TestData\prime256v1.key");
            CngKey pubKey     = OpenSSLKeyECC.GetPublicKey(@"..\..\TestData\prime256v1.pub");

            //使用私钥签名
            ECDsaCng dsa1 = new ECDsaCng(privateKey);

            dsa1.HashAlgorithm = CngAlgorithm.Sha256;
            byte[] signature = dsa1.SignData(data);

            //使用公钥验签
            ECDsaCng dsa2 = new ECDsaCng(pubKey);

            dsa2.HashAlgorithm = CngAlgorithm.Sha256;
            bool bVerified = dsa2.VerifyData(data, signature);

            if (bVerified)
            {
                Console.WriteLine("Verified");
            }
            else
            {
                Console.WriteLine("Not verified");
            }
        }
Beispiel #2
0
        private static void FullTest()
        {
            //待签名数据
            byte[] data = Encoding.UTF8.GetBytes("Text");

            //创建椭圆密钥对
            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
            keyCreationParameters.KeyUsage     = CngKeyUsages.Signing;
            CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters);

            byte[] privateKeyBlob = key.Export(CngKeyBlobFormat.EccPrivateBlob);
            byte[] publicKeyBlob  = key.Export(CngKeyBlobFormat.EccPublicBlob);

            //将Windows CNG的密钥转换为OpenSSL的ECC公钥和私钥,并保存到文件
            byte[] bytesPrivateKeyOpenSSL = OpenSSLKeyECC.ConvertPrivateBlob(privateKeyBlob);
            byte[] bytesPublicKeyOpenSSL  = OpenSSLKeyECC.ConvertPublicBlob(publicKeyBlob);
            FileTools.WriteToFile(@"..\..\TestData\privateKey.pem", bytesPrivateKeyOpenSSL);
            FileTools.WriteToFile(@"..\..\TestData\publicKey.pem", bytesPublicKeyOpenSSL);

            //读取密钥
            CngKey privateKey = OpenSSLKeyECC.GetPrivateKey(@"..\..\TestData\privateKey.pem");
            CngKey publicKey  = OpenSSLKeyECC.GetPublicKey(@"..\..\TestData\publicKey.pem");

            //使用私钥签名
            ECDsaCng dsa1 = new ECDsaCng(privateKey);

            dsa1.HashAlgorithm = CngAlgorithm.Sha256;
            byte[] signature = dsa1.SignData(data);

            //使用公钥验签
            ECDsaCng dsa2 = new ECDsaCng(publicKey);

            dsa2.HashAlgorithm = CngAlgorithm.Sha256;
            bool bVerified = dsa2.VerifyData(data, signature);

            if (bVerified)
            {
                Console.WriteLine("Verified");
            }
            else
            {
                Console.WriteLine("Not verified");
            }
        }