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 類。這些類在您使用默認構造函數創建新實例時創建一個公鑰/私鑰對。既可以存儲不對稱密鑰以用在多個會話中,也可以只為一個會話生成不對稱密鑰。公鑰可以被廣泛地使用,私鑰應被嚴密地保護起來。
每當創建不對稱算法類的新實例時,都生成一個公鑰/私鑰對。創建該類的新實例后,可以用以下兩種方法之一提取密鑰信息:
-
ToXMLString 方法,它返回密鑰信息的 XML 表示形式。導出密鑰--xml形式的字符串
-
對應的方法:FromXmlString通過 XML 字符串中的密鑰信息初始化RSA 對象。 導入密鑰
-
ExportParameters 方法,它返回RSAParameters 結構以保存密鑰信息。導出密鑰--參數形式
- ImportParameters導入指定的RSAParameters。 (重寫RSA.ImportParameters(RSAParameters)。)導入密鑰
兩個方法都接受布爾值,該值指示是只返回公鑰信息還是同時返回公鑰和私鑰信息。通過使用 ImportParameters 方法,可以將 RSACryptoServiceProvider 類初始化為 RSAParameters 結構的值。
下面的代碼示例創建 RSACryptoServiceProvider 類的一個新實例,創建一個公鑰/私鑰對,並將公鑰信息保存在RSAParameters 結構中
- //Generate a public/private key pair.
- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
- //Save the public key information to an RSAParameters structure.
- RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
一、公鑰加密私鑰解密
- /// <summary>
- /// 公鑰加密,私鑰解密
- /// </summary>
- public class RSAEncryptHelper
- {
- /// <summary>
- /// 將字符串使用base64算法加密
- /// </summary>
- /// <param name="code_type">編碼類型</param>
- /// <param name="code">待加密的字符串</param>
- /// <returns>加密后的字符串</returns>
- public string EncodeBase64(string code_type, string code)
- {
- string encode = "";
- byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); //將一組字符編碼為一個字節序列.
- try
- {
- encode = Convert.ToBase64String(bytes); //將8位無符號整數數組的子集轉換為其等效的,以64為基的數字編碼的字符串形式.
- }
- catch
- {
- encode = code;
- }
- return encode;
- }
- /// <summary>
- /// 將字符串使用base64算法解密
- /// </summary>
- /// <param name="code_type">編碼類型</param>
- /// <param name="code">已用base64算法加密的字符串</param>
- /// <returns>解密后的字符串</returns>
- public string DecodeBase64(string code_type, string code)
- {
- string decode = "";
- byte[] bytes = Convert.FromBase64String(code); //將2進制編碼轉換為8位無符號整數數組.
- try
- {
- decode = Encoding.GetEncoding(code_type).GetString(bytes); //將指定字節數組中的一個字節序列解碼為一個字符串。
- }
- catch
- {
- decode = code;
- }
- return decode;
- }
- /// <summary>
- /// 獲取本機的MAC地址
- /// </summary>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 得到CPU序列號
- /// </summary>
- /// <returns></returns>
- public static string GetCpuID()
- {
- try
- {
- //獲取CPU序列號代碼
- string cpuInfo = "";//cpu序列號
- 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
- {
- }
- }
- /// <summary>
- /// 生成公私鑰
- /// </summary>
- /// <param name="PrivateKeyPath"></param>
- /// <param name="PublicKeyPath"></param>
- 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;
- }
- }
- /// <summary>
- /// 對原始數據進行MD5加密
- /// </summary>
- /// <param name="m_strSource">待加密數據</param>
- /// <returns>返回機密后的數據</returns>
- 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);
- }
- /// <summary>
- /// RSA加密
- /// </summary>
- /// <param name="xmlPublicKey">公鑰</param>
- /// <param name="m_strEncryptString">MD5加密后的數據</param>
- /// <returns>RSA公鑰加密后的數據</returns>
- 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;
- }
- /// <summary>
- /// RSA解密
- /// </summary>
- /// <param name="xmlPrivateKey">私鑰</param>
- /// <param name="m_strDecryptString">待解密的數據</param>
- /// <returns>解密后的結果</returns>
- 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;
- }
- /// <summary>
- /// 對MD5加密后的密文進行簽名
- /// </summary>
- /// <param name="p_strKeyPrivate">私鑰</param>
- /// <param name="m_strHashbyteSignature">MD5加密后的密文</param>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 簽名驗證
- /// </summary>
- /// <param name="p_strKeyPublic">公鑰</param>
- /// <param name="p_strHashbyteDeformatter">待驗證的用戶名</param>
- /// <param name="p_strDeformatterData">注冊碼</param>
- /// <returns></returns>
- 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;
- }
- }
- /// <summary>
- /// 獲取硬盤ID
- /// </summary>
- /// <returns>硬盤ID</returns>
- 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;
- }
- /// <summary>
- /// 讀注冊表中指定鍵的值
- /// </summary>
- /// <param name="key">鍵名</param>
- /// <returns>返回鍵值</returns>
- 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;//可能沒有此注冊項;
- }
- }
- /// <summary>
- /// 創建注冊表中指定的鍵和值
- /// </summary>
- /// <param name="key">鍵名</param>
- /// <param name="value">鍵值</param>
- 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;
- }
- }
- /// <summary>
- /// 創建公鑰文件
- /// </summary>
- /// <param name="path"></param>
- /// <param name="publickey"></param>
- 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;
- }
- }
- /// <summary>
- /// 創建私鑰文件
- /// </summary>
- /// <param name="path"></param>
- /// <param name="privatekey"></param>
- 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;
- }
- }
- /// <summary>
- /// 讀取公鑰
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public string ReadPublicKey(string path)
- {
- StreamReader reader = new StreamReader(path);
- string publickey = reader.ReadToEnd();
- reader.Close();
- return publickey;
- }
- /// <summary>
- /// 讀取私鑰
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public string ReadPrivateKey(string path)
- {
- StreamReader reader = new StreamReader(path);
- string privatekey = reader.ReadToEnd();
- reader.Close();
- return privatekey;
- }
- /// <summary>
- /// 初始化注冊表,程序運行時調用,在調用之前更新公鑰xml
- /// </summary>
- /// <param name="path">公鑰路徑</param>
- 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);
- }
- }
- }
二、私鑰加密公鑰解密
- /// <summary>
- /// 非對稱RSA加密類 可以參考
- /// http://www.cnblogs.com/hhh/archive/2011/06/03/2070692.html
- /// http://blog.csdn.net/zhilunchen/article/details/2943158
- /// http://www.cnblogs.com/yyl8781697/archive/2013/04/28/RSA.html
- /// 若是私匙加密 則需公鑰解密
- /// 反正公鑰加密 私匙來解密
- /// 需要BigInteger類來輔助
- /// </summary>
- public static class RSAHelper
- {
- /// <summary>
- /// RSA的容器 可以解密的源字符串長度為 DWKEYSIZE/8-11
- /// </summary>
- public const int DWKEYSIZE = 1024;
- /// <summary>
- /// RSA加密的密匙結構 公鑰和私匙
- /// </summary>
- //public struct RSAKey
- //{
- // public string PublicKey { get; set; }
- // public string PrivateKey { get; set; }
- //}
- #region 得到RSA的解謎的密匙對
- /// <summary>
- /// 得到RSA的解謎的密匙對
- /// </summary>
- /// <returns></returns>
- //public static RSAKey GetRASKey()
- //{
- // RSACryptoServiceProvider.UseMachineKeyStore = true;
- // //聲明一個指定大小的RSA容器
- // RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(DWKEYSIZE);
- // //取得RSA容易里的各種參數
- // RSAParameters p = rsaProvider.ExportParameters(true);
- // return new RSAKey()
- // {
- // PublicKey = ComponentKey(p.Exponent, p.Modulus),
- // PrivateKey = ComponentKey(p.D, p.Modulus)
- // };
- //}
- #endregion
- #region 檢查明文的有效性 DWKEYSIZE/8-11 長度之內為有效 中英文都算一個字符
- /// <summary>
- /// 檢查明文的有效性 DWKEYSIZE/8-11 長度之內為有效 中英文都算一個字符
- /// </summary>
- /// <param name="source"></param>
- /// <returns></returns>
- public static bool CheckSourceValidate(string source)
- {
- return (DWKEYSIZE / 8 - 11) >= source.Length;
- }
- #endregion
- #region 組合解析密匙
- /// <summary>
- /// 組合成密匙字符串
- /// </summary>
- /// <param name="b1"></param>
- /// <param name="b2"></param>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 解析密匙
- /// </summary>
- /// <param name="key">密匙</param>
- /// <param name="b1">RSA的相應參數1</param>
- /// <param name="b2">RSA的相應參數2</param>
- private static void ResolveKey(string key, out byte[] b1, out byte[] b2)
- {
- //從base64字符串 解析成原來的字節數組
- 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 字符串加密解密 公開方法
- /// <summary>
- /// 字符串加密
- /// </summary>
- /// <param name="source">源字符串 明文</param>
- /// <param name="key">密匙</param>
- /// <returns>加密遇到錯誤將會返回原字符串</returns>
- 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;
- }
- /// <summary>
- /// 字符串解密
- /// </summary>
- /// <param name="encryptString">密文</param>
- /// <param name="key">密鑰</param>
- /// <returns>遇到解密失敗將會返回空字符串</returns>
- 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 字符串加密解密 私有 實現加解密的實現方法
- /// <summary>
- /// 用指定的密匙加密
- /// </summary>
- /// <param name="source">明文</param>
- /// <param name="d">可以是RSACryptoServiceProvider生成的D</param>
- /// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
- /// <returns>返回密文</returns>
- 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('@');
- }
- /// <summary>
- /// 用指定的密匙加密
- /// </summary>
- /// <param name="source">密文</param>
- /// <param name="e">可以是RSACryptoServiceProvider生成的Exponent</param>
- /// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
- /// <returns>返回明文</returns>
- 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
- /// <summary>
- /// 將字符串使用base64算法加密
- /// </summary>
- /// <param name="code_type">編碼類型</param>
- /// <param name="code">待加密的字符串</param>
- /// <returns>加密后的字符串</returns>
- public static string EncodeBase64(string code_type, string code)
- {
- string encode = "";
- byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); //將一組字符編碼為一個字節序列.
- try
- {
- encode = Convert.ToBase64String(bytes); //將8位無符號整數數組的子集轉換為其等效的,以64為基的數字編碼的字符串形式.
- }
- catch
- {
- encode = code;
- }
- return encode;
- }
- /// <summary>
- /// 將字符串使用base64算法解密
- /// </summary>
- /// <param name="code_type">編碼類型</param>
- /// <param name="code">已用base64算法加密的字符串</param>
- /// <returns>解密后的字符串</returns>
- public static string DecodeBase64(string code_type, string code)
- {
- string decode = "";
- byte[] bytes = Convert.FromBase64String(code); //將2進制編碼轉換為8位無符號整數數組.
- try
- {
- decode = Encoding.GetEncoding(code_type).GetString(bytes); //將指定字節數組中的一個字節序列解碼為一個字符串。
- }
- catch
- {
- decode = code;
- }
- return decode;
- }
- /// <summary>
- /// 讀取公鑰或私鑰
- /// </summary>
- /// <param name="includePrivateparameters">為True則包含私鑰</param>
- /// <param name="path">Xml格式保存的完整公/私鑰路徑</param>
- /// <returns>公鑰或私鑰參數形式 </returns>
- 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);
- }
- }
- /// <summary>
- /// 獲取本機的MAC地址
- /// </summary>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 得到CPU序列號
- /// </summary>
- /// <returns></returns>
- public static string GetCpuID()
- {
- try
- {
- //獲取CPU序列號代碼
- string cpuInfo = "";//cpu序列號
- 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
- {
- }
- }
- /// <summary>
- /// 獲取硬盤ID
- /// </summary>
- /// <returns>硬盤ID</returns>
- 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;
- }
- /// <summary>
- /// 讀注冊表中指定鍵的值
- /// </summary>
- /// <param name="key">鍵名</param>
- /// <returns>返回鍵值</returns>
- 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;//可能沒有此注冊項;
- }
- }
- /// <summary>
- /// 創建注冊表中指定的鍵和值
- /// </summary>
- /// <param name="key">鍵名</param>
- /// <param name="value">鍵值</param>
- 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("注冊失敗");
- }
- }
- }
- /// <summary>
- /// 注冊機
- /// </summary>
- 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);
- }
- }
