RSA加密與解密、數字簽名與驗證數字簽名

RSA加密算法是一種非對稱加密算法。在公鑰加密標準和電子商業中RSA被廣泛使用。RSA是1977年由羅納德•李維斯特(Ron Rivest)、阿迪•薩莫爾(Adi Shamir)和倫納德•阿德曼(Leonard Adleman)一起提出的。當時他們三人都在麻省理工學院工作。RSA就是他們三人姓氏開頭字母拼在一起組成的。.Net的推出,我們能夠利用.Net Framework中的類提供的加密服務來保證數據安全。目前應用較爲廣泛的加密方法是使用RSA算法進行加密。在.Net Framework中與RSA加密算法相關的類主要有兩個:RSA 類和RSACryptoServiceProvider 類。按照MSDN的說法RSA 類是“表示 RSA 算法的所有實現均從中繼承的基類”,而RSACryptoServiceProvider 類是“使用加密服務提供程序 (CSP) 提供的 RSA 算法的實現執行不對稱加密和解密”。另外,“表示 RSA 算法的標準參數”的RSAParameters 結構也是很重要的,它保存了RSA算法的參數。

 

這是本人剛剛寫的RSA加密與解密、數字簽名與驗證數字簽名的一個簡單例子

希望對初學者能起到一定作用

 

    class RSAEncode
    {
        public RSACryptoServiceProvider MyRsa;
        public RSAEncode()
        {
            MyRsa = new RSACryptoServiceProvider();
        }
        public void RSAKey(out string XmlKey,out string XmlPublicKey)
        {
            try
            {
                XmlKey = MyRsa.ToXmlString(true);
                XmlPublicKey = MyRsa.ToXmlString(false);
                string xx = MyRsa.ToXmlString(true);
                //Console.Write(XmlKey + "/n");
                //Console.Write(xx);
                //WriteInKeys("E://key.xml", XmlKey);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }
        }
        /////加密
        public string RSAEncodeData(string XmlPublicKey, string InputString)
        {
            byte[] BlankStr;
            byte[] EncodeStr;
            int len, len1,blockLen;
            string temp;
            string result="";
            try
            {
                len = InputString.Length;
                if (len % 128 == 0) len1 = len / 128;
                else len1 = len / 128 + 1;
                MyRsa.FromXmlString(XmlPublicKey);
                for (int i = 0; i < len1; i++)
                {
                    if (len >= 128)
                        blockLen = 128;
                    else blockLen = len;
                    len -= blockLen;
                    BlankStr = (new UnicodeEncoding()).GetBytes(InputString.Substring(i * 128, blockLen));
                    EncodeStr = MyRsa.Encrypt(BlankStr, false);
                    temp = Convert.ToBase64String(EncodeStr);
                    result += temp;
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        ////解密
        public string RSADecodeData(string PrivateKey, string InputString)
        {
            string result="";
            byte[] EncodeStr;
            byte[] BlankStr;
            int len, len1, blockLen;
            string temp;
            try
            {
                len = InputString.Length;
                if (len % 256 == 0) len1 = len / 256;
                else len1 = len / 256 + 1;
                MyRsa.FromXmlString(PrivateKey);
                for (int i = 0; i < len1; i++)
                {
                    if (len >= 256)
                        blockLen = 256;
                    else blockLen = len;
                    len -= blockLen;
                    EncodeStr = Convert.FromBase64String(InputString.Substring(i*256,blockLen));
                    BlankStr=MyRsa.Decrypt(EncodeStr, false);
                    temp =(new UnicodeEncoding()).GetString(BlankStr);
                    result += temp;
                }
                return result;
               
                //Console.Write(result);
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        ////獲取hash簽名
        public bool GetHash(string SendData, out string CreateHashSign)
        {
            try
            {
                byte[] Buffer;
                byte[] HashData;
                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(SendData);
                HashData = MD5.ComputeHash(Buffer);
                CreateHashSign = Convert.ToBase64String(HashData);
                //Console.Write(CreateHashSign);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //return true;
            }
        }
        /// <summary>
        /// 簽名
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="HashSign"></param>
        /// <param name="EncodedSignData"></param>
        /// <returns></returns>

        public bool SignatureFormatter(string PrivateKey, string HashSign, out string EncodedSignData)
        {
            try
            {
                byte[] ByteHashSign;
                byte[] ByteData;
                ByteHashSign = Convert.FromBase64String(HashSign);
                //ByteData = Convert.FromBase64String(EncodedData);
                MyRsa.FromXmlString(PrivateKey);
                RSAPKCS1SignatureFormatter RSAFormat = new RSAPKCS1SignatureFormatter(MyRsa);
                RSAFormat.SetHashAlgorithm("MD5");

                ByteData = RSAFormat.CreateSignature(ByteHashSign);

                EncodedSignData = Convert.ToBase64String(ByteData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //驗證簽名
        //p_strHashbyteDeformatter
        //p_strDeformatterData
        public bool SignatureDeformatter(string PublicKey, string p_strHashbyteDeformatter, string p_strDeformatterData)
        {
           try
           {
                byte[] DeformatterData;
                byte[] HashbyteDeformatter;

                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的時候HASH算法爲MD5
                RSADeformatter.SetHashAlgorithm("MD5");

                DeformatterData =Convert.FromBase64String(p_strDeformatterData);

                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
           }
           catch(Exception ex)
           {
            throw ex;
           }
       }
        ///寫入密鑰
        ///
        private void WriteInKeys(string path,string key)
        {
            FileStream File = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(File);
            sw.WriteLine(key);
            sw.Close();
            File.Close();
        }
        ///讀取密鑰
        ///
        public bool ReadKeys(string path, out string Keys)
        {
            try
            {
                StreamReader sr = new StreamReader(path);
                XmlPublicKey = sr.ReadToEnd();
                sr.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

上面是加密解密簽名驗證的類 

結合自己的理解  RSA加密解密的就一句話:公鑰加密 私鑰解密 私鑰簽名 公鑰驗證

不足之處還忘指出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章