• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

c# rsa加密解密详解

c# 搞代码 4年前 (2022-01-09) 20次浏览 已收录 0个评论

前言

RSA加密算法是一种非对称加密算法,简单来说,就是加密时使用一个钥匙,解密时使用另一个钥匙。

因为加密的钥匙是公开的,所又称公钥,解密的钥匙是不公开的,所以称为私钥。

密钥

关于RSA加密有很多文章,但几乎都只介绍了RSACryptoServiceProvider类的使用方法,如果只是走走看看,是没问题的,但真的想使用时,就会发现,你没有密钥字符串。。。

下面我们从获取密钥字符串开始逐步学习加密。

密钥字符串

每个安装过VisualStudio的电脑都可以找到一个文件—makecert.exe。

我电脑的makecert.exe地址:C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\makecert.exe

makecert.exe是用来生成证书的程序,我们可以借用该程序来获取密钥字符串。

编写生成证书的CreateCertWithPrivateKey函数,代码如下:

public static bool CreateCertWithPrivateKey(string subjectName, string<b>本文来源gao@!dai!ma.com搞$$代^@码!网</b> makecertPath)
{
  subjectName = "CN=" + subjectName;
  string param = " -pe -ss my -n \"" + subjectName + "\" ";
  try
  {
    Process p = Process.Start(makecertPath, param);
    p.WaitForExit();
    p.Close();
  }
  catch (Exception e)
  {
    return false;
  }
  return true;
}

调用证书生成函数,代码如下:

string keyName = "Kiba518.Licence";//证书的KEY
var ret = DataCertificate.CreateCertWithPrivateKey(keyName, @"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\makecert.exe");

刚刚生成的证书还存储在WINDOWS的证书存储区,现在我们通过证书的Key在证书存储区查找到证书,并将其到出(导出时需要指定密码),导出函数代码如下:

public static bool ExportToPfxFile(string subjectName, string pfxFileName,
  string password, bool isDelFromStore)
{
  subjectName = "CN=" + subjectName;
  X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
  store.Open(OpenFlags.ReadWrite);
  X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
  foreach (X509Certificate2 x509 in storecollection)
  {
    if (x509.Subject == subjectName)
    {
      byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
      using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create))
      {
        // Write the data to the file, byte by byte.
        for (int i = 0; i < pfxByte.Length; i++)
          fileStream.WriteByte(pfxByte[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 (pfxByte[i] != fileStream.ReadByte())
          {
            fileStream.Close();
            return false;
          }
        }
        fileStream.Close();
      }
      if (isDelFromStore == true)
        store.Remove(x509);
    }
  }
  store.Close();
  store = null;
  storecollection = null;
  return true;
}

调用导出函数,代码如下:

	
DataCertificate.ExportToPfxFile(keyName, "Kiba518.pfx", "123456", true);

运行完导出函数后,我们打开Debug文件夹,可以看到证书已经被成功导出了,如下图:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:c# rsa加密解密详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址