RSA加密解密:私钥解密,公钥加密。
使用的命名空间:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
证书辅助类:
public sealed class DataCertificate
{
#region 生成证书
///
/// 根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
///
///
///
///
//参数为:makecert -r -pe -n "cn=MyCA" -$ commercial -a sha1 -b 08/05/2010 -e 01/01/2012 -cy authority -ss my -sr currentuser
//其中各部分的意义:
//-r: 自签名
//-pe: 将所生成的私钥标记为可导出。这样可将私钥包括在证书中。
//-n "cn=MyCA": 证书的subject name,.net自带类库中有X509Store类,可以在store中根据证书subject name,来找到改证书
//store参考:X509Store 类
//-$ commercial:指明证书商业使用。。。
//-a:指定签名算法。必须是 md5(默认值)或 sha1。
//-b 08/05/2010:证书有效期的开始时间,默认为证书的创建日期。格式为:mm/dd/yyyy
//-e 01/01/2012:指定有效期的结束时间。默认为 12/31/2039 11:59:59 GMT。格式同上
//-ss my:证书产生到my个人store区
//-sr currentuser:保持到计算机当前个人用户区,其他用户登录系统后则看不到该证书。。
public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)
{
subjectName = "CN=" + subjectName;
//string param = " -pe -ss my -n \"" + subjectName + "\" ";
string param = " -r -pe -ss my -n \"" + subjectName + "\" " + " -a sha256 -b 01/01/2019 -e 01/01/4019";
try
{
Process p = Process.Start(makecertPath, param);
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
return false;
}
return true;
}
#endregion
#region 文件导入导出
///
/// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
/// 并导出为pfx文件,同时为其指定一个密码
/// 并将证书从个人区删除(如果isDelFromstor为true)
///
/// 证书主题,不包含CN=
/// pfx文件名
/// pfx文件密码
/// 是否从存储区删除
///
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)
{
Debug.Print(string.Format("certificate name: {0}", x509.Subject));
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;
}
///
/// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
/// 并导出为CER文件(即,只含公钥的)
///
///
///
///
public static bool ExportToCerFile(string subjectName, string cerFileName)
{
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)
{
Debug.Print(string.Format("certificate name: {0}", x509.Subject));
//byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
byte[] cerByte = x509.Export(X509ContentType.Cert);
using (FileStream fileStream = new FileStream(cerFileName, 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();
return false;
}
}
fileStream.Close();
}
}
}
store.Close();
store = null;
storecollection = null;
return true;
}
#endregion
#region 从证书中获取信息
///
/// 根据私钥证书得到证书实体,得到实体后可以根据其公钥和私钥进行加解密
/// 加解密函数使用DEncrypt的RSACryption类
///
///
///
///
public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,
string password)
{
try
{
return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);
}
catch (Exception e)
{
return null;
}
}
///
/// 到存储区获取证书
///
///
///
public static X509Certificate2 GetCertificateFromStore(string subjectName)
{
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)
{
return x509;
}
}
store.Close();
store = null;
storecollection = null;
return null;
}
///
/// 根据公钥证书,返回证书实体
///
///
public static X509Certificate2 GetCertFromCerFile(string cerPath)
{
try
{
return new X509Certificate2(cerPath);
}
catch (Exception e)
{
return null;
}
}
#endregion
}
控制台应用程序:
class Program
{
// 解密
static string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPrivateKey);
byte[] rgb = Convert.FromBase64String(m_strDecryptString);
byte[] bytes = provider.Decrypt(rgb, false);
return new UnicodeEncoding().GetString(bytes);
}
///
/// RSA加密
///
///
///
///
static string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPublicKey);
byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
return Convert.ToBase64String(provider.Encrypt(bytes, false));
}
static void Main(string[] args)
{
string certificateName = "";//证书名
string keyPublic = "";
string keyPrivate = "";
certificateName = "SnlTaoKAB";
//X509Certificate2 privateCert = new X509Certificate2(pfxFilePath, pfxPassword, X509KeyStorageFlags.Exportable);
在本机store里面个人证书目录 里面创建一个的证书
makecert Win10对应目录 C:\Program Files (x86)\Windows Kits\8.0\bin\x64,不同版本Windows makecert目录可能不同
//DataCertificate.CreateCertWithPrivateKey(certificateName, "C:\\Program Files (x86)\\Windows Kits\\8.1\\bin\\x64\\makecert.exe");
DataCertificate.CreateCertWithPrivateKey(certificateName, "C:\\Program Files (x86)\\Windows Kits\\8.0\\bin\\x64\\makecert.exe");
//获取证书
X509Certificate2 c1 = DataCertificate.GetCertificateFromStore(certificateName);
keyPublic = c1.PublicKey.Key.ToXmlString(false); // 公钥
keyPrivate = c1.PrivateKey.ToXmlString(true); // 私钥
string cypher = RSAEncrypt(keyPublic, "程序员"); // 加密
string plain = RSADecrypt(keyPrivate, cypher); // 解密
System.Diagnostics.Debug.Assert(plain == "程序员");
第一次 从本机store里面个人证书目录读取已生成的cer证书 Copy 到指定的文件夹下
DataCertificate.ExportToCerFile(certificateName, "d:\\mycert\\" + certificateName + ".cer");
X509Certificate2 c2 = DataCertificate.GetCertFromCerFile("d:\\mycert\\" + certificateName + ".cer");
string keyPublic2 = c2.PublicKey.Key.ToXmlString(false);
bool b = keyPublic2 == keyPublic;
if (!b)
keyPublic2 = keyPublic;
string cypher2 = RSAEncrypt(keyPublic2, "程序员2"); // 加密
string plain2 = RSADecrypt(keyPrivate, cypher2); // 解密, cer里面并没有私钥,所以这里使用前面得到的私钥来解密
//生成证书得到公钥私钥以后重新调用 加解密
X509Certificate2 c2 = DataCertificate.GetCertFromCerFile("d:\\mycert\\" + certificateName + ".cer");
//keyPublic = "tZ6JUEO8A1gPE0+b2/QdxxgDmaKJvwD9hwXmxRaUc6OKlZ4QRNliLCDMvrgaXPF2S3QiqGmQnoeNPWF90IsaB/wxc4ayglEX8wl2yV8PARcQhx+V+wIJsBD0vVNk3sMBAfZrVrVJOZNkjUcAFmPYnPxkq/7y4HJFG+TCRNMVsRjreywK+CLrZFnYvUiw/xbNA6fJ03nkFDNoPsXAXVOUJv9J8FXiTirPx21aGJddy7AFlvNytgOru5F6pJYI76fe5YYGYYUVHjgIOCmkjcolwYt6AUmlmKG1bsGvd0Imacf5rKu32E8J8av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wSoeKdR9upERJMvDs= TMnaTY0Qcg5qhEB1+Mb5/QPDQzOpO+tlduALO23Kuubm+lYQ5sZUyHGv25lb0RAUkFqDFeyA0M9Y8Y8lCuXkjzU6depFZHay9a9OG8WJ7g5AcSuNltjbqC2y542dgnBU9gzUogySrVGAHdBFkQhwukH6tSgqIVR4PblI3Vr54uQ= L2nM5SRZr/HMNblhsgE/yNsPDYuuNCv5A8fZn/guFyZJppeWHbM2etixOtTrJPpwbHBMH/U3KPuwNqb95nR5/j2rV0KB1Z2ACBWfaiCj1SAFU5E+YUH973XtvoNH4RO9bpq7GO7Ix/wfkvZHIpE8WndVfMVY+Jk8S3Tj9n24uvua4HHsBxy1TeRdRHojWWVZm79aH+CFhGIemSHSVEKp+GfPhIUzMGXwfA6l4M4FSpb+XNbB7un29JjTNB8TV49qVY4QelpsS/J9v6eMg0GDYBJIcG0AkghrFWBGjVyHGUJJsZhGVYAxdJow4BWo+Y129LYtcZtznGhH4VsjpTNsfQ== ";
//string cypher2 = RSAEncrypt(keyPublic, "程序员2"); // 加密
//string plain2 = RSADecrypt(keyPrivate, cypher2); // 解密, cer里面并没有私钥,所以这里使用前面得到的私钥来解密
System.Diagnostics.Debug.Assert(plain2 == "程序员2");
// 生成一个pfx, 并且从store里面删除
DataCertificate.ExportToPfxFile(certificateName, "d:\\mycert\\" + certificateName + ".pfx", "111", true);
X509Certificate2 c3 = DataCertificate.GetCertificateFromPfxFile("d:\\mycert\\" + certificateName + ".pfx", "111");
string keyPublic3 = c3.PublicKey.Key.ToXmlString(false); // 公钥
string keyPrivate3 = c3.PrivateKey.ToXmlString(true); // 私钥
string cypher3 = RSAEncrypt(keyPublic3, "程序员3"); // 加密
string plain3 = RSADecrypt(keyPrivate3, cypher3); // 解密
System.Diagnostics.Debug.Assert(plain3 == "程序员3");
}
}
查看本机store里面个人证书
证书导出 为 Base64编码文件
2.跟着向导,一路下一步