标签:
RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。 RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价。
.NET提供常用的加密算法类,支持RSA的类是RSACryptoServiceProvider(命名空间:System.Security.Cryptography),但只支持公钥加密,私钥解密。RSACryptoServiceProvider类包括:Modulus、Exponent、P、Q、DP、DQ、InverseQ、D等8个属性,其中Modulus和Exponent就是公钥,Modulus和D就是私钥,RSACryptoServiceProvider类提供导出公钥的方法,也提供导出私钥的方法,但导出的私钥包含上面8个属性,显然要用RSACryptoServiceProvider实现私钥加密公钥是不可行的。
从RSA的原理来看,公钥加密私钥解密和私钥加密公钥解密应该是等价的,在某些情况下,比如共享软件加密,我们需要用私钥加密注册码或注册文件,发给用户,用户用公钥解密注册码或注册文件进行合法性验证。
不对称密钥
.NET Framework 为不对称加密提供了 RSACryptoServiceProvider 和 DSACryptoServiceProvider 类。这些类在您使用默认构造函数创建新实例时创建一个公钥/私钥对。既可以存储不对称密钥以用在多个会话中,也可以只为一个会话生成不对称密钥。公钥可以被广泛地使用,私钥应被严密地保护起来。
每当创建不对称算法类的新实例时,都生成一个公钥/私钥对。创建该类的新实例后,可以用以下两种方法之一提取密钥信息:
两个方法都接受布尔值,该值指示是只返回公钥信息还是同时返回公钥和私钥信息。通过使用 ImportParameters 方法,可以将 RSACryptoServiceProvider 类初始化为 RSAParameters 结构的值。
下面的代码示例创建 RSACryptoServiceProvider 类的一个新实例,创建一个公钥/私钥对,并将公钥信息保存在RSAParameters 结构中
- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
- RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
一、公钥加密私钥解密
-
-
- public class RSAEncryptHelper
- {
-
-
-
-
-
-
-
- public string EncodeBase64(string code_type, string code)
- {
- string encode = "";
- byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
- try
- {
- encode = Convert.ToBase64String(bytes);
- }
- catch
- {
- encode = code;
- }
- return encode;
- }
-
-
-
-
-
-
-
- public string DecodeBase64(string code_type, string code)
- {
-
- string decode = "";
- byte[] bytes = Convert.FromBase64String(code);
- try
- {
- decode = Encoding.GetEncoding(code_type).GetString(bytes);
- }
- catch
- {
- decode = code;
- }
- return decode;
- }
-
-
-
-
- public static string GetLocalMac()
- {
- string mac = null;
- ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection queryCollection = query.Get();
- foreach (ManagementObject mo in queryCollection)
- {
- if (mo["IPEnabled"].ToString() == "True")
- mac = mo["MacAddress"].ToString();
- }
- return (mac);
- }
-
-
-
-
-
- public static string GetCpuID()
- {
- try
- {
-
- string cpuInfo = "";
- ManagementClass mc = new ManagementClass("Win32_Processor");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
- }
- moc = null;
- mc = null;
- return cpuInfo;
- }
- catch
- {
- return "unknow";
- }
- finally
- {
- }
-
- }
-
-
-
-
-
-
-
-
-
-
- public void RSAKey(string PrivateKeyPath, string PublicKeyPath)
- {
-
- try
- {
-
- RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
-
- this.CreatePrivateKeyXML(PrivateKeyPath, provider.ToXmlString(true));
-
- this.CreatePublicKeyXML(PublicKeyPath, provider.ToXmlString(false));
-
- }
-
- catch (Exception exception)
- {
-
- throw exception;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public string GetHash(string m_strSource)
- {
-
- HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
-
- byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
-
- byte[] inArray = algorithm.ComputeHash(bytes);
-
- return Convert.ToBase64String(inArray);
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
- {
-
- string str2;
-
- try
- {
-
- RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
-
- provider.FromXmlString(xmlPublicKey);
-
- byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
-
- str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
-
- }
-
- catch (Exception exception)
- {
-
- throw exception;
-
- }
-
- return str2;
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
- {
-
- string str2;
-
- try
- {
-
- RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
-
- provider.FromXmlString(xmlPrivateKey);
-
- byte[] rgb = Convert.FromBase64String(m_strDecryptString);
-
- byte[] buffer2 = provider.Decrypt(rgb, false);
-
- str2 = new UnicodeEncoding().GetString(buffer2);
-
- }
- catch (Exception exception)
- {
-
- throw exception;
-
- }
-
- return str2;
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public string SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature)
- {
-
- byte[] rgbHash = Convert.FromBase64String(m_strHashbyteSignature);
-
- RSACryptoServiceProvider key = new RSACryptoServiceProvider();
-
- key.FromXmlString(p_strKeyPrivate);
-
- RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
-
- formatter.SetHashAlgorithm("MD5");
-
- byte[] inArray = formatter.CreateSignature(rgbHash);
-
- return Convert.ToBase64String(inArray);
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
- {
-
- try
- {
-
- byte[] rgbHash = Convert.FromBase64String(p_strHashbyteDeformatter);
-
- RSACryptoServiceProvider key = new RSACryptoServiceProvider();
-
- key.FromXmlString(p_strKeyPublic);
-
- RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
-
- deformatter.SetHashAlgorithm("MD5");
-
- byte[] rgbSignature = Convert.FromBase64String(p_strDeformatterData);
-
- if (deformatter.VerifySignature(rgbHash, rgbSignature))
- {
-
- return true;
-
- }
-
- return false;
-
- }
-
- catch
- {
-
- return false;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
- public string GetHardID()
- {
-
- string HDInfo = "";
-
- ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
-
- ManagementObjectCollection moc1 = cimobject1.GetInstances();
-
- foreach (ManagementObject mo in moc1)
- {
-
- HDInfo = (string)mo.Properties["Model"].Value;
-
- }
-
- return HDInfo;
-
- }
-
-
-
-
-
-
-
-
-
-
-
- private string ReadReg(string key)
- {
-
- string temp = "";
-
- try
- {
-
- RegistryKey myKey = Registry.LocalMachine;
-
- RegistryKey subKey = myKey.OpenSubKey(@"SOFTWARE/JX/Register");
-
-
-
- temp = subKey.GetValue(key).ToString();
-
- subKey.Close();
-
- myKey.Close();
-
- return temp;
-
- }
-
- catch (Exception)
- {
-
- throw;
-
- }
-
-
-
- }
-
-
-
-
-
-
-
-
-
-
-
- private void WriteReg(string key, string value)
- {
-
- try
- {
-
- RegistryKey rootKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE/JX/Register");
-
- rootKey.SetValue(key, value);
-
- rootKey.Close();
-
- }
-
- catch (Exception)
- {
-
- throw;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public void CreatePublicKeyXML(string path, string publickey)
- {
-
- try
- {
-
- FileStream publickeyxml = new FileStream(path, FileMode.Create);
-
- StreamWriter sw = new StreamWriter(publickeyxml);
-
- sw.WriteLine(publickey);
-
- sw.Close();
-
- publickeyxml.Close();
-
- }
-
- catch
- {
-
- throw;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public void CreatePrivateKeyXML(string path, string privatekey)
- {
-
- try
- {
-
- FileStream privatekeyxml = new FileStream(path, FileMode.Create);
-
- StreamWriter sw = new StreamWriter(privatekeyxml);
-
- sw.WriteLine(privatekey);
-
- sw.Close();
-
- privatekeyxml.Close();
-
- }
-
- catch
- {
-
- throw;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public string ReadPublicKey(string path)
- {
-
- StreamReader reader = new StreamReader(path);
-
- string publickey = reader.ReadToEnd();
-
- reader.Close();
-
- return publickey;
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public string ReadPrivateKey(string path)
- {
-
- StreamReader reader = new StreamReader(path);
-
- string privatekey = reader.ReadToEnd();
-
- reader.Close();
-
- return privatekey;
-
- }
-
-
-
-
-
-
-
-
-
- public void InitialReg(string path)
- {
-
- Registry.LocalMachine.CreateSubKey(@"SOFTWARE/JX/Register");
-
- Random ra = new Random();
-
- string publickey = this.ReadPublicKey(path);
-
- if (Registry.LocalMachine.OpenSubKey(@"SOFTWARE/JX/Register").ValueCount <= 0)
- {
-
- this.WriteReg("RegisterRandom", ra.Next(1, 100000).ToString());
-
- this.WriteReg("RegisterPublicKey", publickey);
-
- }
-
- else
- {
-
- this.WriteReg("RegisterPublicKey", publickey);
-
- }
-
- }
- }
二、私钥加密公钥解密
-
-
-
-
-
-
-
-
- public static class RSAHelper
- {
-
-
-
- public const int DWKEYSIZE = 1024;
-
-
-
-
-
-
-
-
-
-
- #region 得到RSA的解谜的密匙对
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #endregion
-
- #region 检查明文的有效性 DWKEYSIZE/8-11 长度之内为有效 中英文都算一个字符
-
-
-
-
-
- public static bool CheckSourceValidate(string source)
- {
- return (DWKEYSIZE / 8 - 11) >= source.Length;
- }
- #endregion
-
- #region 组合解析密匙
-
-
-
-
-
-
- public static string ComponentKey(byte[] b1, byte[] b2)
- {
- List<byte> list = new List<byte>();
-
- list.Add((byte)b1.Length);
- list.AddRange(b1);
- list.AddRange(b2);
- byte[] b = list.ToArray<byte>();
- return Convert.ToBase64String(b);
- }
-
-
-
-
-
-
-
- private static void ResolveKey(string key, out byte[] b1, out byte[] b2)
- {
-
- byte[] b = Convert.FromBase64String(key);
-
- b1 = new byte[b[0]];
- b2 = new byte[b.Length - b[0] - 1];
-
- for (int n = 1, i = 0, j = 0; n < b.Length; n++)
- {
- if (n <= b[0])
- {
- b1[i++] = b[n];
- }
- else
- {
- b2[j++] = b[n];
- }
- }
- }
- #endregion
-
- #region 字符串加密解密 公开方法
-
-
-
-
-
-
- public static string EncryptString(string source, string key)
- {
- string encryptString = string.Empty;
- byte[] d;
- byte[] n;
- try
- {
- if (!CheckSourceValidate(source))
- {
- throw new Exception("source string too long");
- }
-
- ResolveKey(key, out d, out n);
- BigInteger biN = new BigInteger(n);
- BigInteger biD = new BigInteger(d);
- encryptString = EncryptString(source, biD, biN);
- }
- catch
- {
- encryptString = source;
- }
- return encryptString;
- }
-
-
-
-
-
-
-
- public static string DecryptString(string encryptString, string key)
- {
- string source = string.Empty;
- byte[] e;
- byte[] n;
- try
- {
-
- ResolveKey(key, out e, out n);
- BigInteger biE = new BigInteger(e);
- BigInteger biN = new BigInteger(n);
- source = DecryptString(encryptString, biE, biN);
- }
- catch
- {
- }
- return source;
- }
- #endregion
-
- #region 字符串加密解密 私有 实现加解密的实现方法
-
-
-
-
-
-
-
- private static string EncryptString(string source, BigInteger d, BigInteger n)
- {
- int len = source.Length;
- int len1 = 0;
- int blockLen = 0;
- if ((len % 128) == 0)
- len1 = len / 128;
- else
- len1 = len / 128 + 1;
- string block = "";
- StringBuilder result = new StringBuilder();
- for (int i = 0; i < len1; i++)
- {
- if (len >= 128)
- blockLen = 128;
- else
- blockLen = len;
- block = source.Substring(i * 128, blockLen);
- byte[] oText = System.Text.Encoding.Default.GetBytes(block);
- BigInteger biText = new BigInteger(oText);
- BigInteger biEnText = biText.modPow(d, n);
- string temp = biEnText.ToHexString();
- result.Append(temp).Append("@");
- len -= blockLen;
- }
- return result.ToString().TrimEnd(‘@‘);
- }
-
-
-
-
-
-
-
-
- private static string DecryptString(string encryptString, BigInteger e, BigInteger n)
- {
- StringBuilder result = new StringBuilder();
- string[] strarr1 = encryptString.Split(new char[] { ‘@‘ }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < strarr1.Length; i++)
- {
- string block = strarr1[i];
- BigInteger biText = new BigInteger(block, 16);
- BigInteger biEnText = biText.modPow(e, n);
- string temp = System.Text.Encoding.Default.GetString(biEnText.getBytes());
- result.Append(temp);
- }
- return result.ToString();
- }
- #endregion
-
-
-
-
-
-
-
-
- public static string EncodeBase64(string code_type, string code)
- {
- string encode = "";
- byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
- try
- {
- encode = Convert.ToBase64String(bytes);
- }
- catch
- {
- encode = code;
- }
- return encode;
- }
-
-
-
-
-
-
-
- public static string DecodeBase64(string code_type, string code)
- {
-
- string decode = "";
- byte[] bytes = Convert.FromBase64String(code);
- try
- {
- decode = Encoding.GetEncoding(code_type).GetString(bytes);
- }
- catch
- {
- decode = code;
- }
- return decode;
- }
-
-
-
-
-
-
-
- public static RSAParameters ReadKey(bool includePrivateparameters,string path)
- {
- using (StreamReader reader = new StreamReader(path))
- {
- string publickey = reader.ReadToEnd();
- RSACryptoServiceProvider rcp = new RSACryptoServiceProvider();
- rcp.FromXmlString(publickey);
- return rcp.ExportParameters(includePrivateparameters);
- }
- }
-
-
-
-
-
- public static string GetLocalMac()
- {
- string mac = null;
- ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection queryCollection = query.Get();
- foreach (ManagementObject mo in queryCollection)
- {
- if (mo["IPEnabled"].ToString() == "True")
- mac = mo["MacAddress"].ToString();
- }
- return (mac);
- }
-
-
-
-
-
- public static string GetCpuID()
- {
- try
- {
-
- string cpuInfo = "";
- ManagementClass mc = new ManagementClass("Win32_Processor");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
- }
- moc = null;
- mc = null;
- return cpuInfo;
- }
- catch
- {
- return "unknow";
- }
- finally
- {
- }
-
- }
-
-
-
-
-
-
-
-
-
- public static string GetHardID()
- {
-
- string HDInfo = "";
-
- ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
-
- ManagementObjectCollection moc1 = cimobject1.GetInstances();
-
- foreach (ManagementObject mo in moc1)
- {
-
- HDInfo = (string)mo.Properties["Model"].Value;
-
- }
-
- return HDInfo;
-
- }
-
-
-
-
-
-
-
-
-
-
-
- private static string ReadReg(string key)
- {
-
- string temp = "";
-
- try
- {
-
- RegistryKey myKey = Registry.LocalMachine;
-
- RegistryKey subKey = myKey.OpenSubKey(@"SOFTWARE/JX/Register");
-
-
-
- temp = subKey.GetValue(key).ToString();
-
- subKey.Close();
-
- myKey.Close();
-
- return temp;
-
- }
-
- catch (Exception)
- {
-
- throw;
-
- }
- }
-
-
-
-
-
-
-
-
-
-
-
- private static void WriteReg(string key, string value)
- {
- try
- {
-
- RegistryKey rootKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE/JX/Register");
-
- rootKey.SetValue(key, value);
-
- rootKey.Close();
-
- }
-
- catch (Exception)
- {
-
- throw;
-
- }
-
- }
-
-
- }
使用场景:如共享软件加密,我们需要用私钥加密注册码或注册文件,发给用户,用户用公钥解密注册码或注册文件进行合法性验证。
RSA算法实现激活码注册方式的原理如下:
1. 生成一对公钥E和私钥D(供软件注册模板和注册机使用);
2. 用户安装软件后,软件注册模板提取用户机器指纹信息(如:MAC地址、CPU序列号、硬盘序列号等),并通过其它的编码算法(如BASE64)生成一个申请码C;
3. 用户将申请码C发给软件开发商。软件开发商通过注册机采用私钥D加密申请码C后生成激活码F。软件供应商将激活码F发给用户。
4. 用户输入激活码F,软件注册模板采用公钥E对激活码F解码后生成G(即:用户机器特征信息),然后软件注册模板提取用户机器的特定信息后进行编码。将编码的结果与G进行比较,如果相等则用户合法,完成授权,否则授权失败。
- public partial class Form1 : Form
- {
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- string cpu = RSAHelper.GetCpuID();
- string _申请码C = RSAHelper.EncodeBase64("utf-8", cpu);
- textEdit申请码.Text = _申请码C;
- }
-
- private void simpleButton注册_Click(object sender, EventArgs e)
- {
- string publicKeyPath = @"C://PublicKey.xml";
- RSAParameters pm = RSAHelper.ReadKey(false, publicKeyPath);
-
- string _PublicKey = RSAHelper.ComponentKey(pm.Exponent, pm.Modulus);
-
- string cpu = RSAHelper.DecryptString(textEdit激活码.Text, _PublicKey);
- if (cpu == textEdit申请码.Text)
- {
- MessageBox.Show("注册成功");
- }
- else
- {
- MessageBox.Show("注册失败");
- }
- }
- }
-
-
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void simpleButton生成激活码_Click(object sender, EventArgs e)
- {
- string privateKeyPath = @"C://PrivateKey.xml";
- RSAParameters pm = RSAHelper.ReadKey(true, privateKeyPath);
- string _PrivateKey = RSAHelper.ComponentKey(pm.D, pm.Modulus);
- textEdit激活码.Text = RSAHelper.EncryptString(textEdit申请码.Text, _PrivateKey);
- }
- }
RSA不对称加密,公钥加密私钥解密,私钥加密公钥解密
标签:
原文地址:http://www.cnblogs.com/zhangruisoldier/p/4644582.html