RSA加密、解密
RSA是三个人的姓氏开头字母
aspx前台代码- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TextBox ID="txtName" runat="server" Height="50" Width="200"></asp:TextBox>
- <asp:Button ID="btnEncrypt" runat="server" Text="加密" OnClick="btnEncrypt_Click" />
- <asp:Button ID="btnDecryption" runat="server" Text="解密" OnClick="btnDecryption_Click" />
- <asp:TextBox ID="txtResult" runat="server" Height="50" Width="200"></asp:TextBox>
- </div>
- </form>
- </body>
复制代码 aspx.cs后台代码- using System;
- using System.Security.Cryptography;
- using System.Text;
- namespace WebApplication1
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- private CspParameters param = new CspParameters();
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- /// <summary>
- /// 加密按钮点击方法
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnEncrypt_Click(object sender, EventArgs e)
- {
- param = new CspParameters();
- param.KeyContainerName = "gransys";//密匙容器的名称,保持加密解密一致才能解密成功
- using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
- {
- byte[] plaindata = Encoding.Default.GetBytes(txtName.Text);//将要加密的字符串转换为字节数组
- byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
- txtResult.Text = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
- }
- }
- /// <summary>
- /// 解密按钮点击方法
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnDecryption_Click(object sender, EventArgs e)
- {
- param = new CspParameters();
- param.KeyContainerName = "gransys";
- using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
- {
- byte[] encryptdata = Convert.FromBase64String(this.txtName.Text);
- byte[] decryptdata = rsa.Decrypt(encryptdata, false);
- txtResult.Text = Encoding.Default.GetString(decryptdata);
- }
- }
- }
- }
复制代码 |