RSA實(shí)現(xiàn)C# 加密詳解
RSA實(shí)現(xiàn)C# 加密首先我們來(lái)了解下什么是RSA ,它屬于不對(duì)稱(chēng)加密,其原理就是使用一個(gè)公鑰一個(gè)私鑰,公鑰可以公開(kāi)用以加密,私鑰嚴(yán)格保密用于解密,那么這樣大家知道了RSA 適合于數(shù)據(jù)量不大的加密,比如加密對(duì)稱(chēng)加密的密鑰。
RSA實(shí)現(xiàn)C# 加密的過(guò)程實(shí)例:
RSACryptoServiceProvider 的名稱(chēng)空間是:
- System.Security.
- CryptographyRSACryptoServiceProvider
- rsaSend = new RSACryptoServiceProvider();
- string plaintext = "明文"; //明文
- byte[] ciphertext = rsaSend.Encrypt(
- System.Text.Encoding.UTF8.GetBytes(plaintext), false);
- //加密后
- lbl.Text = Convert.ToBase64String(ciphertext);
- //顯示加密后的,為了顯示不可見(jiàn)字符,使用的是 Base64 編碼。
使用 RSACryptoServiceProvider() 創(chuàng)建 RSACryptoServiceProvider 實(shí)例時(shí),自動(dòng)產(chǎn)生密鑰。
RSA 實(shí)際應(yīng)用中是:接收方產(chǎn)生公鑰和私鑰,發(fā)送方用其公鑰加密,再把加密后的內(nèi)容發(fā)送給接收方。
CspParameters 的名稱(chēng)空間是:
- System.Security.CryptographyCspParameters cpSend =
- new CspParameters(); //Csp = Cryptography Service Provider
- CspParameters cpReceive = new CspParameters();
- cpSend.KeyContainerName = "SendTestContainer";
- cpReceive.KeyContainerName =
- "ReceiveTestContainer";
- RSACryptoServiceProvider rsaSend =
- new RSACryptoServiceProvider(cpSend); ;
- RSACryptoServiceProvider rsaReceive =
- new RSACryptoServiceProvider(cpReceive);
- rsaSend.FromXmlString(rsaReceive.ToXmlString(false));
- //發(fā)送方使用接收方給它的公鑰進(jìn)行加密
- string plaintext =
- "前幾天我碰到一個(gè)朋友,約我跟馬賊打架,
- 我立馬答應(yīng)了他,因?yàn)槲矣X(jué)得這件事好無(wú)聊。";
- byte[] ciphertext =
- rsaSend.Encrypt(System.Text.Encoding.UTF8.GetBytes(
- plaintext), false); //加密后
- byte[] decryption =
- rsaReceive.Decrypt(ciphertext, false); //解密后
- lbl.Width = 760;
- lbl.Text = "";
- lbl.Text +=
- Convert.ToBase64String(ciphertext) + "﹤br /﹥";
- //顯示加密后的
- lbl.Text +=
- System.Text.Encoding.UTF8.GetString(decryption) + "﹤br /﹥";
- //顯示解密后的
- lbl.Text +=
- Server.HtmlEncode(rsaSend.ToXmlString(false)) + "﹤br /﹥";
- //顯示發(fā)送方公鑰
- lbl.Text +=
- Server.HtmlEncode(rsaReceive.ToXmlString(true)) + "﹤br /﹥";
- //顯示接收方公鑰和私鑰
- lbl.Text +=
- Server.HtmlEncode(rsaReceive.ToXmlString(false)) + "﹤br /﹥";
- //顯示接收方公鑰
- rsaSend.PersistKeyInCsp = true; //密鑰要保存起來(lái)
- //rsaSend.Clear();
- rsaReceive.PersistKeyInCsp = true;
- //rsaReceive.Clear();
在上面的代碼中,我們使用 CspParameters 將密鑰保存起來(lái),ToXmlString 和 FromXmlString 將接收方的公鑰告訴給發(fā)送方。
RSA實(shí)現(xiàn)C# 加密的實(shí)際操作就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C# 加密以及RSA的應(yīng)用有所幫助。
【編輯推薦】