關於rsa非對稱加密、解密、簽名、驗簽


關於rsa加密有私鑰、公鑰

私鑰:對外不公開,供自己簽名對外輸出,對傳入的數據進行解密。

公鑰:對外公開,供外部人員對數據進行加密傳出,然后對傳入數據進行驗簽。

rsa對數據加密有長度限制,若長度可控的情況下,建議轉換byte[]進行分段加密傳輸,

若對於大文件的傳輸:

建議一:

使用des、aes進行加密大文件,將des/aes的密鑰使用rsa加密,使用(https/http)傳輸,這樣既能保證數據安全性也能提高性能。

建議二:

雙向簽名驗簽,將大文件進行簽名,將簽名和文件base64之后使用https一同傳輸。

建議二中的方式數據安全性則有https負責進行保護,數據的完整性則有簽名進行保護,防止數據篡改,

二中方法自己可以針對每個用戶都分配一個私鑰供用戶進行簽名,自己這端需要存儲每個用戶的公鑰進行驗簽,這樣保證多個用戶情況之下數據安全性。

測試數據:

 1             var xmlprikey ="";
 2             var xmlpubkey ="";
 3             rsa = new RSACryption();
 4             //待處理字符串
 5             var str="hello成功啊啊!¥%……&*(!@#$%^&*()@#$%^&*()_}::{>>?}{>?{?";
 6             var strlen= str.Length;
 7             rsa.RSAKey(out  xmlprikey, out  xmlpubkey);
 8             //加密
 9             var rsaencrypt=  rsa.RSAEncrypt(xmlpubkey, str);
10             //解密
11             var rsadecrypt = rsa.RSADecrypt(xmlprikey, rsaencrypt);
12             //獲取hash描述
13             var gethash="";
14             //獲取hash值是否成功
15             var hashbool= rsa.GetHash(str, ref gethash);
16             //簽名之后的數據
17             var strEncryptedSignatureData ="";
18             //rsa簽名
19             rsa.SignatureFormatter(xmlprikey,gethash, ref strEncryptedSignatureData);
20             //rsa驗簽
21             var SignatureDeformatter =rsa.SignatureDeformatter(xmlpubkey, gethash, strEncryptedSignatureData);
22             //加密之后數據
23             var strEnc="gVVqccxkEIQxMfkXxAmHup9/c0ZMhQzqLJpdrLwysaIaE+o/GFtINp6Q7o1eI4HOIxfdU7/9VEKdPEXakspooXVcH4GZkgWFRhe5VkM7Wj71RiUiEHa+o/H78Fn4q7B0JaiJjiUwfTIr0GHP5nMkPvYDiBZVfzuBARJCcjkrXVM=";
24             var strEncLen= strEnc.Length;   
View Code

rsa類庫:

    class RSACryption
    {
        #region RSA 加密解密

        #region RSA 的密鑰產生
        /// <summary>
        /// RSA產生密鑰
        /// </summary>
        /// <param name="xmlKeys">私鑰</param>
        /// <param name="xmlPublicKey">公鑰</param>
        public void RSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                xmlKeys = rsa.ToXmlString(true);
                xmlPublicKey = rsa.ToXmlString(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA加密函數
        //############################################################################## 
        //RSA 方式加密 
        //KEY必須是XML的形式,返回的是字符串 
        //該加密方式有長度限制的!
        //############################################################################## 

        /// <summary>
        /// RSA的加密函數
        /// </summary>
        /// <param name="xmlPublicKey">公鑰</param>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public string RSAEncrypt(string xmlPublicKey, string encryptString)
        {
            try
            {
                byte[] PlainTextBArray;
                byte[] CypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);
                CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
                Result = Convert.ToBase64String(CypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA的加密函數 
        /// </summary>
        /// <param name="xmlPublicKey">公鑰</param>
        /// <param name="EncryptString">待加密的字節數組</param>
        /// <returns></returns>
        public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
        {
            try
            {
                byte[] CypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                CypherTextBArray = rsa.Encrypt(EncryptString, false);
                Result = Convert.ToBase64String(CypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA的解密函數
        /// <summary>
        /// RSA的解密函數
        /// </summary>
        /// <param name="xmlPrivateKey">私鑰</param>
        /// <param name="decryptString">待解密的字符串</param>
        /// <returns></returns>
        public string RSADecrypt(string xmlPrivateKey, string decryptString)
        {
            try
            {
                byte[] PlainTextBArray;
                byte[] DypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                PlainTextBArray = Convert.FromBase64String(decryptString);
                DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA的解密函數 
        /// </summary>
        /// <param name="xmlPrivateKey">私鑰</param>
        /// <param name="DecryptString">待解密的字節數組</param>
        /// <returns></returns>
        public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
        {
            try
            {
                byte[] DypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                DypherTextBArray = rsa.Decrypt(DecryptString, false);
                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #endregion

        #region RSA數字簽名

        #region 獲取Hash描述表
        /// <summary>
        /// 獲取Hash描述表
        /// </summary>
        /// <param name="strSource">待簽名的字符串</param>
        /// <param name="HashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(string strSource, ref byte[] HashData)
        {
            try
            {
                byte[] Buffer;
                System.Security.Cryptography.HashAlgorithm sha = System.Security.Cryptography.HashAlgorithm.Create("SHA1");
                Buffer = Encoding.UTF8.GetBytes(strSource);
                HashData = sha.ComputeHash(Buffer);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 獲取Hash描述表
        /// </summary>
        /// <param name="strSource">待簽名的字符串</param>
        /// <param name="strHashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(string strSource, ref string strHashData)
        {
            try
            {
                //從字符串中取得Hash描述 
                byte[] Buffer;
                byte[] HashData;
                System.Security.Cryptography.HashAlgorithm sha = System.Security.Cryptography.HashAlgorithm.Create("SHA1");
                Buffer = Encoding.UTF8.GetBytes(strSource);
                HashData = sha.ComputeHash(Buffer);
                strHashData = Convert.ToBase64String(HashData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 獲取Hash描述表
        /// </summary>
        /// <param name="objFile">待簽名的文件</param>
        /// <param name="HashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
        {
            try
            {
                //從文件中取得Hash描述 
                System.Security.Cryptography.HashAlgorithm sha = System.Security.Cryptography.HashAlgorithm.Create("SHA1");
                HashData = sha.ComputeHash(objFile);
                objFile.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 獲取Hash描述表
        /// </summary>
        /// <param name="objFile">待簽名的文件</param>
        /// <param name="strHashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
        {
            try
            {
                //從文件中取得Hash描述 
                byte[] HashData;
                System.Security.Cryptography.HashAlgorithm sha = System.Security.Cryptography.HashAlgorithm.Create("SHA1");
                HashData = sha.ComputeHash(objFile);
                objFile.Close();
                strHashData = Convert.ToBase64String(HashData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA簽名
        /// <summary>
        /// RSA簽名
        /// </summary>
        /// <param name="strKeyPrivate">私鑰</param>
        /// <param name="HashbyteSignature">待簽名Hash描述</param>
        /// <param name="EncryptedSignatureData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(strKeyPrivate);
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                //設置簽名的算法為MD5 
                RSAFormatter.SetHashAlgorithm("SHA1");
                //執行簽名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA簽名
        /// </summary>
        /// <param name="strKeyPrivate">私鑰</param>
        /// <param name="HashbyteSignature">待簽名Hash描述</param>
        /// <param name="m_strEncryptedSignatureData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, ref string strEncryptedSignatureData)
        {
            try
            {
                byte[] EncryptedSignatureData;
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPrivate);
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                //設置簽名的算法為MD5 
                RSAFormatter.SetHashAlgorithm("SHA1");
                //執行簽名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
                strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA簽名
        /// </summary>
        /// <param name="strKeyPrivate">私鑰</param>
        /// <param name="strHashbyteSignature">待簽名Hash描述</param>
        /// <param name="EncryptedSignatureData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref byte[] EncryptedSignatureData)
        {
            try
            {
                byte[] HashbyteSignature;

                HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(strKeyPrivate);
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                //設置簽名的算法為MD5 
                RSAFormatter.SetHashAlgorithm("SHA1");
                //執行簽名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA簽名
        /// </summary>
        /// <param name="strKeyPrivate">私鑰</param>
        /// <param name="strHashbyteSignature">待簽名Hash描述</param>
        /// <param name="strEncryptedSignatureData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref string strEncryptedSignatureData)
        {
            try
            {
                byte[] HashbyteSignature;
                byte[] EncryptedSignatureData;
                HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPrivate);
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                //設置簽名的算法為MD5 
                RSAFormatter.SetHashAlgorithm("SHA1");
                //執行簽名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
                strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region RSA 簽名驗證
        /// <summary>
        /// RSA簽名驗證
        /// </summary>
        /// <param name="strKeyPublic">公鑰</param>
        /// <param name="HashbyteDeformatter">Hash描述</param>
        /// <param name="DeformatterData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的時候HASH算法為SHA1 
                RSADeformatter.SetHashAlgorithm("SHA1");
                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA簽名驗證
        /// </summary>
        /// <param name="strKeyPublic">公鑰</param>
        /// <param name="strHashbyteDeformatter">Hash描述</param>
        /// <param name="DeformatterData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, byte[] DeformatterData)
        {
            try
            {
                byte[] HashbyteDeformatter;
                HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的時候HASH算法為SHA1 
                RSADeformatter.SetHashAlgorithm("SHA1");
                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA簽名驗證
        /// </summary>
        /// <param name="strKeyPublic">公鑰</param>
        /// <param name="HashbyteDeformatter">Hash描述</param>
        /// <param name="strDeformatterData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, byte[] HashbyteDeformatter, string strDeformatterData)
        {
            try
            {
                byte[] DeformatterData;
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的時候HASH算法為SHA1 
                RSADeformatter.SetHashAlgorithm("SHA1");
                DeformatterData = Convert.FromBase64String(strDeformatterData);
                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA簽名驗證
        /// </summary>
        /// <param name="strKeyPublic">公鑰</param>
        /// <param name="strHashbyteDeformatter">Hash描述</param>
        /// <param name="strDeformatterData">簽名后的結果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, string strDeformatterData)
        {
            try
            {
                byte[] DeformatterData;
                byte[] HashbyteDeformatter;
                HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的時候HASH算法為SHA1 
                RSADeformatter.SetHashAlgorithm("SHA1");
                DeformatterData = Convert.FromBase64String(strDeformatterData);
                if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #endregion

    }
View Code

 原創地址:http://www.cnblogs.com/sydeveloper/archive/2012/08/11/2633624.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM