c# BC证书生成

 //产生证书文件
    internal class CertificateGenerate
    {
        /// <summary>
        /// 公钥类型
        /// </summary>
        private PublicKeyKind publicKeyKind = PublicKeyKind.UNKNOWN;
        private AsymmetricCipherKeyPair createdkeyPair = null; 
        
        /// <summary>
        /// 创建公密钥对
        /// </summary>
        /// <returns></returns>
        protected virtual AsymmetricCipherKeyPair createRasKeyPair()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25);
            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            return keyPair;
        }

        /// <summary>
        /// 创建证书实体
        /// </summary>
        /// <returns></returns>
        private Framework.Basic.Crypto.X509.X509Certificate createX509Certificate(AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey)
        {
            IDictionary attrs = new Hashtable();
            attrs[X509Name.E] = "";
            attrs[X509Name.CN] = "";
            attrs[X509Name.O] = "";
            attrs[X509Name.C] = "";
            attrs[X509Name.L] = "";
            attrs[X509Name.T] = "";

            IList ord = new ArrayList();
            ord.Add(X509Name.E);
            ord.Add(X509Name.CN);
            ord.Add(X509Name.O);
            ord.Add(X509Name.C);
            ord.Add(X509Name.L);
            ord.Add(X509Name.T);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            certGen.SetNotAfter(DateTime.Today.AddYears(150));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(publicKey);
            certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)));
            UMS.Framework.Basic.Crypto.X509.X509Certificate x509 = certGen.Generate(new Asn1SignatureFactory("SHA1withRSA", privateKey, new SecureRandom()));

            x509.CheckValidity();
            x509.Verify(publicKey);
            return x509;
        }
                
        internal void CreateIfNotExist()
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            bool isExist = false;
            //轮询存储区中的所有证书
            foreach (X509Certificate2 myX509Certificate2 in store.Certificates)
            {
                if (myX509Certificate2.FriendlyName.Equals("" + publicKeyKind.ToString()))
                {
                    isExist = true;
                    break;
                }
            }
            if (!isExist)
            {
                //产生密钥对
                if (createdkeyPair == null)
                    createdkeyPair = createRasKeyPair();
                //获取公钥和密钥
                AsymmetricKeyParameter publicKey = createdkeyPair.Public;
                AsymmetricKeyParameter privateKey = createdkeyPair.Private;
                if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
                    throw new Exception("failed key generation (1024) length test");
                UMS.Framework.Basic.Crypto.X509.X509Certificate x509 = createX509Certificate(publicKey, privateKey);
                X509Certificate2 myPrivateCertificate = new X509Certificate2(x509.GetEncoded(), UMS.ITTS.Pidgen.Core.PublicKeyFactory.cerificatePassword, X509KeyStorageFlags.Exportable);
                myPrivateCertificate.FriendlyName = "" + publicKeyKind.ToString(); 
                myPrivateCertificate.PrivateKey = DotNetUtilities.ToRSA(privateKey as RsaPrivateCrtKeyParameters);
                store.Add(myPrivateCertificate);
            }
            store.Close(); 
        }

        //导出
        internal void Export(string path)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            //轮询存储区中的所有证书
            X509Certificate2 currrent = null;
            foreach (X509Certificate2 myX509Certificate2 in store.Certificates)
            {
                if (myX509Certificate2.FriendlyName.Equals("" + publicKeyKind.ToString()))
                {
                    currrent = myX509Certificate2;
                    break;
                }
            }
            if (currrent == null)
                throw new Exception("未找到相关证书文件.");
            byte[] cerByte = currrent.Export(X509ContentType.Cert);
            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                // Write the data to the file, byte by byte.     
                for (int i = 0; i < cerByte.Length; i++)
                    fileStream.WriteByte(cerByte[i]);
                // Set the stream position to the beginning of the file.     
                fileStream.Seek(0, SeekOrigin.Begin);
                // Read and verify the data.     
                for (int i = 0; i < fileStream.Length; i++)
                {
                    if (cerByte[i] != fileStream.ReadByte())
                    {
                        fileStream.Close();
                    }
                }
                fileStream.Close();
            }
            currrent = null;
        }

        internal PublicKeyKind PublicKeyKind
        {
            get
            {
                return this.publicKeyKind;
            }
            set
            {
                if (value != publicKeyKind)
                    this.publicKeyKind = value;
            }
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C#调用C#生成的DLL的步骤: 1.编写C#类库项目并生成DLL文件。 2.在调用DLL的C#项目中添加对DLL的引用。 3.在代码中使用DLL中的类和方法。 下面是一个简单的示例: 假设我们有一个名为“CSharpClassLib”的C#类库项目,其中包含一个名为“TestClass”的类,该类具有一个名为“Hello”的公共方法。 1.编写C#类库项目并生成DLL文件。 在Visual Studio中创建一个新的C#类库项目“CSharpClassLib”,并添加以下代码: ```csharp using System; namespace CSharpClassLib { public class TestClass { public void Hello() { Console.WriteLine("Hello from CSharpClassLib!"); } } } ``` 生成该项目,将生成一个名为“CSharpClassLib.dll”的DLL文件。 2.在调用DLL的C#项目中添加对DLL的引用。 在Visual Studio中创建一个新的C#控制台应用程序项目“MyDllDemo”,并将“CSharpClassLib.dll”文件复制到该项目的“bin\Debug”文件夹中。 右键单击“引用”文件夹,选择“添加引用”,然后选择“浏览”选项卡,浏览到“CSharpClassLib.dll”文件并添加它。 3.在代码中使用DLL中的类和方法。 在“Program.cs”文件中添加以下代码: ```csharp using System; using CSharpClassLib; namespace MyDllDemo { class Program { static void Main(string[] args) { TestClass test = new TestClass(); test.Hello(); Console.ReadKey(); } } } ``` 运行该项目,将输出“Hello from CSharpClassLib!”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值