📄 cer.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace WindowsApplication1
{
/// <summary>
/// 使用RSACryptoServiceProvider和X509Certificate2进行证书加密解密
/// 平台:.NET 2.0
/// </summary>
public class CertificateEncryptedDecrypted
{
static string mDigitalCertificateName = "";
[Description("证书名称")]
public static string DigitalCertificateName
{
get
{
return mDigitalCertificateName;
}
set
{
mDigitalCertificateName = value;
}
}
/// <summary>
/// 获取密文
/// </summary>
/// <param name="cPlainStringToEncrypt">明文</param>
/// <returns></returns>
public static string GetEncryptedText(string cPlainStringToEncrypt)
{
X509Store store = new X509Store(StoreName.My);
X509Certificate2 x509_2 = null;
store.Open(OpenFlags.ReadWrite);
if (mDigitalCertificateName.Length > 0)
{
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.SubjectName.Name.Contains(mDigitalCertificateName))
{
x509_2 = cert;
break;
}
}
if (x509_2 == null)
throw new Exception("不能找到证书:" + mDigitalCertificateName);
}
else
{
x509_2 = store.Certificates[0];
}
try
{
string PlainString = cPlainStringToEncrypt.Trim();
byte[] cipherbytes = ASCIIEncoding.ASCII.GetBytes(PlainString);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;
byte[] cipher = rsa.Encrypt(cipherbytes, false);
return Convert.ToBase64String(cipher);
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 获取译文
/// </summary>
/// <param name="cEncryptedStringToDecrypt">密文</param>
/// <returns></returns>
public static string GetDecryptedText(string cEncryptedStringToDecrypt)
{
X509Store store = new X509Store(StoreName.My);
X509Certificate2 x509_2 = null;
store.Open(OpenFlags.ReadWrite);
if (mDigitalCertificateName.Length > 0)
{
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.SubjectName.Name.Contains(mDigitalCertificateName))
{
x509_2 = cert;
break;
}
}
if (x509_2 == null)
throw new Exception("不能找到证书:" + mDigitalCertificateName);
}
else
{
x509_2 = store.Certificates[0];
}
try
{
byte[] cipherbytes = Convert.FromBase64String(cEncryptedStringToDecrypt);
if (x509_2.HasPrivateKey)
{
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PrivateKey;
byte[] plainbytes = rsa.Decrypt(cipherbytes, false);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetString(plainbytes);
}
else
{
throw new Exception("证书没有使用私钥");
}
}
catch (Exception e)
{
throw e;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -