1. 程式人生 > 實用技巧 >C# 私鑰加密,公鑰解密

C# 私鑰加密,公鑰解密

        /// <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(); //取得RSA容易裡的各種引數
RSAParameters p = rsaProvider.ExportParameters(true); return new RSAKey() { PublicKey = ComponentKey(p.Exponent, p.Modulus), PrivateKey = ComponentKey(p.D, p.Modulus) }; } #endregion #region 組合解析密匙 ///
<summary> /// 組合成密匙字串 /// </summary> /// <param name="b1"></param> /// <param name="b2"></param> /// <returns></returns> private 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(); 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 { source = encryptString; } 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

備註:BigInteger類爆紅,在nuget裡面搜尋引用。