在用Bouncy Castle的C#版API产生公钥和私钥 中产生了一对密钥对,可以用bouncy caslte提供的API进行保存

公钥方面的3个类,具体代码根据命名空间自行查看其源代码:

Org.BouncyCastle.Asn1.X509 . SubjectPublicKeyInfo

Org.BouncyCastle.X509 . SubjectPublicKeyInfoFactory

Org.BouncyCastle.Security . PublicKeyFactory

用法:

SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfoFactory .CreateSubjectPublicKeyInfo(rsaPublic);

//rsaPublic是产生的公钥,类型是AsymmetricKeyParameter/RsaKeyParameters,其中后者集成前者

AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory. CreateKey(subInfo);

私钥方面,但私钥保存到本地文件中时,可以选择加密保存,3DES with sha1,涉及到5个类:

Org.BouncyCastle.Asn1.Pkcs . PrivateKeyInfo

Org.BouncyCastle.Pkcs . PrivateKeyInfoFactory

Org.BouncyCastle.Security . PrivateKeyFactory

Org.BouncyCastle.Asn1.Pkcs . EncryptedPrivateKeyInfo

Org.BouncyCastle.Pkcs . EncryptedPrivateKeyInfoFactory

前面3个类的用法同上面公钥的类似:

PrivateKeyInfo privInfo = PrivateKeyInfoFactory .CreatePrivateKeyInfo(rsaPrivate);

AsymmetricKeyParameter testResult = (RsaPrivateCrtKeyParameters) PrivateKeyFactory .CreateKey(privInfo);

如果要加密保存私钥的话:

string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1
byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count=1000;
char[] password="123456".ToCharArray();
EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory .CreateEncryptedPrivateKeyInfo(
    alg,
    password,
    salt,
    count,
    privateKey);

从EncryptedPrivateKeyInfo 恢复出PrivateKeyInfo 则简单多了:

PrivateKeyInfo priInfo = PrivateKeyInfoFactory .CreatePrivateKeyInfo(password, enPrivateKeyInfo);

再导出私钥:

AsymmetricKeyParameter privateKey = PrivateKeyFactory .CreateKey(priInfo);

SubjectPublicKeyInfo和PrivateKeyInfo都提供了ToAsn1Object()方法,转换成很Asn1Object,再使用GetEncoded()方法,生成byte数组,然后保存到本地。编码是BER,当然DER也是可以。从本地读取文件时逆过程即可,把读取到的byte数组转换成Asn1Object对象,再使用GetInstance()方法。

测试代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.Security.Cryptography.X509Certificates;    // X509Certificate2
  7. using System.IO;
  8. using Org.BouncyCastle.Crypto.Generators;
  9. using Org.BouncyCastle.Crypto.Parameters;
  10. using Org.BouncyCastle.Crypto;
  11. using Org.BouncyCastle.Security;
  12. using Org.BouncyCastle.Crypto.Engines;  //IAsymmetricBlockCipher engine = new RsaEngine();
  13. using Org.BouncyCastle.Math;
  14. using Org.BouncyCastle.Asn1.X509; //X509Name
  15. using Org.BouncyCastle.X509;
  16. using Org.BouncyCastle.Utilities.Collections;   //X509V3CertificateGenerator
  17. using Org.BouncyCastle.Asn1.Pkcs;   //PrivateKeyInfo
  18. using Org.BouncyCastle.Pkcs;
  19. using Org.BouncyCastle.Asn1;
  20. namespace ConsoleApplication1
  21. {
  22. class Program
  23. {
  24. static void Main(string[] args)
  25. {
  26. //公钥和密钥的生成,并加密解密测试
  27. RsaKeyGeneratorTest();    //done!!!!!
  28. }
  29. private static void RsaKeyGeneratorTest()
  30. {
  31. //RSA密钥对的构造器
  32. RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
  33. //RSA密钥构造器的参数
  34. RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
  35. Org.BouncyCastle.Math.BigInteger.ValueOf(3),
  36. new Org.BouncyCastle.Security.SecureRandom(),
  37. 1024,   //密钥长度
  38. 25);
  39. //用参数初始化密钥构造器
  40. keyGenerator.Init(param);
  41. //产生密钥对
  42. AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
  43. //获取公钥和私钥
  44. AsymmetricKeyParameter publicKey = keyPair.Public;
  45. AsymmetricKeyParameter privateKey = keyPair.Private;
  46. if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
  47. {
  48. Console.WriteLine("failed key generation (1024) length test");
  49. }
  50. savetheKey(publicKey, privateKey);
  51. //一个测试……………………
  52. //输入,十六进制的字符串,解码为byte[]
  53. //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
  54. //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
  55. string input = "popozh RSA test";
  56. byte[] testData = Encoding.UTF8.GetBytes(input);
  57. //非对称加密算法,加解密用
  58. IAsymmetricBlockCipher engine = new RsaEngine();
  59. //公钥加密
  60. //从保存在本地的磁盘文件中读取公钥
  61. Asn1Object aobject = Asn1Object.FromStream(new FileStream(@"E:/Desktop/a.pub",FileMode.Open,FileAccess.Read));  //a.puk??
  62. SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.GetInstance(aobject);
  63. AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
  64. FileStream fs;
  65. engine.Init(true, testpublicKey);
  66. try
  67. {
  68. //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
  69. testData = engine.ProcessBlock(testData, 0, testData.Length);
  70. Console.WriteLine("加密完成!" + Environment.NewLine);
  71. fs = new FileStream(@"E:/Desktop/encryptedBytes", FileMode.Create, FileAccess.Write);
  72. fs.Write(testData, 0, testData.Length);
  73. fs.Close();
  74. Console.WriteLine("保存密文成功" + Environment.NewLine);
  75. }
  76. catch (Exception ex)
  77. {
  78. Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
  79. }
  80. //私钥解密
  81. //获取加密的私钥,进行解密,获得私钥
  82. fs = new FileStream(@"E:/Desktop/encryptedBytes", FileMode.Open, FileAccess.Read);
  83. byte[] anothertestdata = new byte[1024];
  84. fs.Read(anothertestdata, 0, anothertestdata.Length);
  85. fs.Close();
  86. Asn1Object aobj = Asn1Object.FromStream(new FileStream(@"E:/Desktop/a.pri", FileMode.Open, FileAccess.Read));   //a.pvk??
  87. EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);
  88. char[] password = "123456".ToCharArray();
  89. PrivateKeyInfo priKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri);    //解密
  90. AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);    //私钥
  91. engine.Init(false, anotherprivateKey);
  92. try
  93. {
  94. anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
  95. Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
  96. }
  97. catch (Exception e)
  98. {
  99. Console.WriteLine("failed - exception " + e.ToString());
  100. }
  101. Console.Read();
  102. }
  103. private static void savetheKey(AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey)
  104. {
  105. //保存公钥到文件
  106. SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
  107. Asn1Object aobject = publicKeyInfo.ToAsn1Object();
  108. byte[] pubInfoByte = aobject.GetEncoded();
  109. FileStream fs = new FileStream(@"E:/Desktop/a.pub", FileMode.Create, FileAccess.Write);
  110. fs.Write(pubInfoByte, 0, pubInfoByte.Length);
  111. fs.Close();
  112. //保存私钥到文件
  113. /*
  114. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
  115. aobject = privateKeyInfo.ToAsn1Object();
  116. byte[] priInfoByte = aobject.GetEncoded();
  117. fs = new FileStream(@"E:/Desktop/a.pri", FileMode.Create, FileAccess.Write);
  118. fs.Write(priInfoByte, 0, priInfoByte.Length);
  119. fs.Close();
  120. */
  121. string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1
  122. byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  123. int count=1000;
  124. char[] password="123456".ToCharArray();
  125. EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
  126. alg,
  127. password,
  128. salt,
  129. count,
  130. privateKey);
  131. byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
  132. fs = new FileStream(@"E:/Desktop/a.pri", FileMode.Create, FileAccess.Write);
  133. fs.Write(priInfoByte, 0, priInfoByte.Length);
  134. fs.Close();
  135. //还原
  136. //PrivateKeyInfo priInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enPrivateKeyInfo);
  137. //AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(priInfoByte);
  138. }
  139. }
  140. }

接下来就可以生成cer公钥证书或者pfx证书

在C#中保存Bouncy Castle生成的密钥对的更多相关文章

  1. 【Java密码学】使用Bouncy Castle生成数字签名、数字信封

    Bouncy Castle(轻量级密码术包)是一种用于 Java 平台的开放源码的轻量级密码术包,它支持大量的密码术算法,并提供 JCE 1.2.1 的实现.最近项目上正好用到了Bouncy Cast ...

  2. Tensorflow中保存模型时生成的各种文件区别和作用

    假如我们得到了如下的checkpoints, 上面的文件主要可以分成三类:一种是在保存模型时生成的文件,一种是我们在使用tensorboard时生成的文件,还有一种就是plugins这个文件夹,这个是 ...

  3. JAVA 解密pkcs7(smime.p7m)加密内容 ,公钥:.crt 私钥:.pem 使用Bouncy Castle生成数字签名、数字信封

    第三方使用公钥.crt加密后返回的内容,需要使用私钥解密.pem 返回内容格式如下 MIME-Version: 1.0 Content-Disposition: attachment; filenam ...

  4. 用Bouncy Castle的C#版API产生公钥和私钥

    开源API链接地址:The Legion of the Bouncy Castle Bouncy Castle,简称为BC,原本是java的一个开源JCE提供者,后来也提供了C#版本的API,我下载其 ...

  5. 加密 bouncy castle

    1.去官方站点下载Bouncy Castle的JCE Provider包 bcprov-ext-jdk15-145.jar 2.把jar文件复制到 $JAVA_HOME$\jre\lib\ext 目录 ...

  6. Entity Framework入门教程(6)--- 在线场景中保存数据

    在线场景中保存数据 在线场景中保存实体数据是一项相当容易的任务,因为使用的是同一个context,这个context会自动跟踪所有实体发生的更改. 下图说明了在线场景中的CUD(创建,更新,删除)操作 ...

  7. spark中saveAsTextFile如何最终生成一个文件

    原文地址: http://www.cnblogs.com/029zz010buct/p/4685173.html 一般而言,saveAsTextFile会按照执行task的多少生成多少个文件,比如pa ...

  8. Android中保存静态秘钥实践(转)

    本文我们将讲解一个Android产品研发中可能会碰到的一个问题:如何在App中保存静态秘钥以及保证其安全性.许多的移动app需要在app端保存一些静态字符串常量,其可能是静态秘钥.第三方appId等. ...

  9. EditPlus保存时不生成bak文件(转)

    如何设置EditPlus保存时不生成bak文件 EditPlus是一个强大的编辑工具,不单单是编辑文字强大,很多的刚开始学习编程语言的初学者会选择它,例如html,js,php,java.小编刚开始学 ...

随机推荐

  1. LeetCode Spiral Matrix II (技巧)

    题意: 从1开始产生连续的n2个数字,以螺旋的方式填满一个n*n的数组. 思路: 由于是填满一个矩阵,那么只需要每次都填一圈即可.应该注意特殊情况. 迭代: class Solution { publ ...

  2. Event Logging

    编号:1001 时间:2016年3月29日16:24:33 功能:Event Logging 技术简介 URL:http://blog.csdn.net/colorknight/article/det ...

  3. AIO、NIO、BIO

    AIO:异步非阻塞 NIO:同步非阻塞 BIO:同步阻塞 (1)同步 指的是用户进程触发IO操作并等待或者轮询的去查看IO操作是否就绪 (2)异步 指用户进程触发IO操作以后便开始做自己的事情,而当I ...

  4. CentOS6编译装载nbd模块

    今天突然发现CentOS系统没有nbd模块,只能重新装下,下面记录下整个编译过程: 系统:CentOS6.5 内核:2.6.32-431.el6.x86_64 [root@localhost ~]# ...

  5. discuz使用

    1.discuz登陆错误过多,后台删除ip SELECT * FROM `lang_common_admincp_session` 2.Discuz与UCenter通信失败的解决方法 应用与 UCen ...

  6. POJ 2253 Frogger

    题目链接:http://poj.org/problem?id=2253 Frogger Time Limit: 1000MS   Memory Limit: 65536K Total Submissi ...

  7. iPhone 上拨号键盘的发音规律

    上个学期在信号处理课上选做的题目和这个问题正好相关. 如焕杰同学所说,iPhone拨号音是使用双音多频信号(DTMF).双音多频信号是贝尔实验室发明的,通常用于发送被叫号码,它取代了早起的脉冲拨号方法 ...

  8. hihoCoder#1015 : KMP算法 (KMP模板)

    代码如下: # include<iostream> # include<cstdio> # include<cstring> # include<vector ...

  9. MAC 如何修改PATH

    http://hathaway.cc/post/69201163472/how-to-edit-your-path-environment-variables-on-mac

  10. C++泛型编程原理

    1.什么是泛型编程前面我们介绍的vector,list,map都是一种数据结构容器,容器本身的存储结构不同,各容器中存在的数据类型也可以不同.但我们在访问这些容器中数据时,拥有相同的方式.这种方式就叫 ...