C#中RSA加密解密和簽名與驗證的實現

來源:互聯網
上載者:User

標籤:blog   java   使用   檔案   資料   os   

RSA密碼編譯演算法是一種非對稱式加密演算法。在公開金鑰加密標準和電子商業中RSA被廣泛使用。RSA是1977年由羅納德•李維斯特(Ron Rivest)、阿迪•薩莫爾(Adi Shamir)和倫納德•阿德曼(Leonard Adleman)一起提出的。當時他們三人都在麻省理工學院工作。RSA就是他們三人姓氏開頭字母拼在一起組成的。.Net的推出,我們能夠利用.Net Framework中的類提供的Data Encryption Service來保證資料安全。目前應用較為廣泛的加密方法是使用RSA演算法進行加密。在.Net Framework中與RSA密碼編譯演算法相關的類主要有兩個:RSA 類和RSACryptoServiceProvider 類。按照MSDN的說法RSA 類是“表示 RSA 演算法的所有實現均從中繼承的基類”,而RSACryptoServiceProvider 類是“使用密碼編譯服務提供者 (CSP) 提供的 RSA 演算法的實現執行不對稱式加密和解密”。另外,“表示 RSA 演算法的標準參數”的RSAParameters 結構也是很重要的,它儲存了RSA演算法的參數。這裡具體講述一下在C#中如何使用架構提供的RSA演算法來對我們的資訊加密、簽名、驗證簽名、解密的這個幾個步驟的實現        using System.Security.Cryptography;        using System.Management;        using Microsoft.Win32;        /// <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);            }        } 如果是要對發送的訊息進行加密和解密,加密時用公開金鑰,解密時用私密金鑰,即使密文被竊取也無法破解。如果是要對軟體進行註冊,產生註冊碼,則服務端將使用者的硬碟號用私密金鑰加密,用戶端用公開金鑰解密,解密後將用戶端的硬碟號進行MD5加密,將得到的結果和解密後的結果進行比較,如果相同,說明是註冊使用者,否則為非註冊使用者。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.