您好,登錄后才能下訂單哦!
1. RSA加密與解密 -- 使用公鑰加密、私鑰解密
public class RSATool { public string Encrypt(string strText, string strPublicKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(strPublicKey); byte[] byteText = Encoding.UTF8.GetBytes(strText); byte[] byteEntry = rsa.Encrypt(byteText, false); return Convert.ToBase64String(byteEntry); } public string Decrypt(string strEntryText,string strPrivateKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(strPrivateKey); byte[] byteEntry = Convert.FromBase64String(strEntryText); byte[] byteText = rsa.Decrypt(byteEntry, false); return Encoding.UTF8.GetString(byteText); } public Dictionary<string,string> GetKey() { Dictionary<string, string> dictKey = new Dictionary<string, string>(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); dictKey.Add("PublicKey", rsa.ToXmlString(false)); dictKey.Add("PrivateKey", rsa.ToXmlString(true)); return dictKey; } }
測試:
RSATool myRSA = new RSATool(); Dictionary<string, string> dictK = new Dictionary<string, string>(); dictK = myRSA.GetKey(); string strText = "123456"; Console.WriteLine("要加密的字符串是:{0}", strText); string str1 = myRSA.Encrypt("123456", dictK["PublicKey"]); Console.WriteLine("加密后的字符串:{0}", str1); string str2 = myRSA.Decrypt(str1, dictK["PrivateKey"]); Console.WriteLine("解密后的字符串:{0}", str2);
2. RSA加密與解密 -- 使用同一個密鑰容器進行加密與解密
public class RSAToolX { public string Encrypt(string strText) { CspParameters CSApars = new CspParameters(); CSApars.KeyContainerName = "Test001"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSApars); byte[] byteText = Encoding.UTF8.GetBytes(strText); byte[] byteEntry = rsa.Encrypt(byteText, false); return Convert.ToBase64String(byteEntry); } public string Decrypt(string strEntryText) { CspParameters CSApars = new CspParameters(); CSApars.KeyContainerName = "Test001"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSApars); byte[] byteEntry = Convert.FromBase64String(strEntryText); byte[] byteText = rsa.Decrypt(byteEntry, false); return Encoding.UTF8.GetString(byteText); } }
測試 :
RSAToolX myRSA = new RSAToolX(); string strText = "123456"; Console.WriteLine("要加密的字符串是:{0}", strText); string str1 = myRSA.Encrypt("123456"); Console.WriteLine("加密后的字符串:{0}", str1); string str2 = myRSA.Decrypt(str1); Console.WriteLine("解密后的字符串:{0}", str2);
總結
以上所述是小編給大家介紹的C#中RSA加密與解密的實例詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。