一個可逆加密的例子

來源:互聯網
上載者:User
加密

    下面的代碼實現了一個可逆加密的方法。可以用於對Cookie,QueryString等加密處理。
  
  查看例子
  
  VB.net代碼
  
  <%@ Page Language="vb" AutoEventWireup="false" Codebehind="EncString.<a href="http://dev.21tx.com/web/asp/" target="_blank">ASP</a>x.vb"
   Inherits="aspx<a href="http://dev.21tx.com/web/" target="_blank">Web</a>.EncString" %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <HTML>
   <HEAD>
   <title>一個可逆加密的例子</title>
   <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
   <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
   <meta name="vs_defaultClientScript" content="<a href="http://dev.21tx.com/web/javascript/" target="_blank">JavaScript</a>">
   <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
   </HEAD>
   <body MS_POSITIONING="GridLayout">
   <asp:Label id="Label1" runat="server"></asp:Label>
   <p align="center">
   <form id="Form1" method="post" runat="server">
   <FONT face="宋體">
   <asp:TextBox id="TextBox1" runat="server" Width="96%"></asp:TextBox>
   <asp:RadioButtonList id="RadioButtonList1" runat="server" Font-Bold="True"
   RepeatDirection="Horizontal" AutoPostBack="True" OnSelectedIndexChanged="ShowRes">
   </asp:RadioButtonList>
   <asp:TextBox id="TextBox2" runat="server" Width="96%"></asp:TextBox>
   </FONT>
   </form>
   </p>
   </body>
  </HTML>
  
  後端代碼EncString.aspx.vb:
  Imports System
  Imports System.IO
  Imports System.Xml
  Imports System.Text
  Imports System.Security.Cryptography
  Public Class EncString
   Inherits System.Web.UI.Page
   Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
   Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox
   Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm
   Protected WithEvents Label1 As System.Web.UI.WebControls.Label
   Protected WithEvents RadioButtonList1 As System.Web.UI.WebControls.RadioButtonList
  
  #Region " Web Form Designer Generated Code "
  
   'This call is required by the Web Form Designer.
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  
   End Sub
  
   Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
  
  MyBase.Init
   'CODEGEN: This method call is required by the Web Form Designer
   'Do not modify it using the code editor.
   InitializeComponent()
   End Sub
  
  #End Region
  
   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
  
  MyBase.Load
   'Put user code to initialize the page here
   Label1.Text = "<h3 align='center'>一個可逆加密的例子</h3>"
   If Not IsPostBack Then
   Dim MyList As New ArrayList()
   MyList.Add("加密")
   MyList.Add("解密")
   RadioButtonList1.DataSource = MyList
   RadioButtonList1.DataBind()
   End If
   End Sub
  
   ' 加密
   Public Shared Function EncryptText(ByVal strText As String) As String
   Return Encrypt(strText, "&%#@?,:*")
   End Function
  
   '解密
   Public Shared Function DecryptText(ByVal strText As String) As String
   Return Decrypt(strText, "&%#@?,:*")
   End Function
  
   '加密函數
   Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
   Dim byKey() As Byte = {}
   Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
   Try
   byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
   Dim des As New DESCryptoServiceProvider()
   Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
   Dim ms As New MemoryStream()
   Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
   cs.Write(inputByteArray, 0, inputByteArray.Length)
   cs.FlushFinalBlock()
   Return Convert.ToBase64String(ms.ToArray())
   Catch ex As Exception
   Return ex.Message
   End Try
   End Function
  
   '解密函數
   Private Shared Function Decrypt(ByVal strText As String, ByVal sDecrKey As String) As String
   Dim byKey() As Byte = {}
   Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
   Dim inputByteArray(strText.Length) As Byte
   Try
   byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
   Dim des As New DESCryptoServiceProvider()
   inputByteArray = Convert.FromBase64String(strText)
   Dim ms As New MemoryStream()
   Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
   cs.Write(inputByteArray, 0, inputByteArray.Length)
   cs.FlushFinalBlock()
   Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
   Return encoding.GetString(ms.ToArray())
   Catch ex As Exception
   Return ex.Message
   End Try
   End Function
  
   Public Sub ShowRes(ByVal sender As Object, ByVal e As System.EventArgs)_
   Handles RadioButtonList1.SelectedIndexChanged
   If RadioButtonList1.SelectedIndex = 0 Then
   TextBox2.Text = EncryptText(TextBox1.Text)
   Else
   TextBox2.Text = DecryptText(TextBox1.Text)
   End If
   End Sub
  End Class

   C#代碼
  
  EncryptString.aspx
  
  <%@ Page language="c#" EnableViewState = "true" Codebehind="EncryptString.aspx.cs" AutoEventWireup="false" Inherits="eMeng.Exam.EncryptString" %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <HTML>
  <HEAD>
  <title>一個可逆加密的例子</title>
  <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
  <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body>
  <form id="Form1" method="post" runat="server">
  <p align="center">一個可逆加密的例子
  <asp:TextBox id="TextBox1" runat="server" Width="96%">http://dotnet.aspx.cc/</asp:TextBox>
  <asp:RadioButtonList id="RadioButtonList1" runat="server" Font-Bold="True" RepeatDirection="Horizontal"
  AutoPostBack="True"></asp:RadioButtonList>
  <asp:TextBox id="TextBox2" runat="server" Width="96%"></asp:TextBox>
  <asp:TextBox id="Textbox3" runat="server" Width="96%"></asp:TextBox>
  </p>
  </form>
  </body>
  </HTML>
  
  EncryptString.aspx.cs
  
  using System;
  using System.Collections;
  using System.ComponentModel;
  using System.Drawing;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;
  using System.IO;
  using System.Text;
  using System.Security.Cryptography;
  
  
  namespace eMeng.Exam
  {
  /// <summary>
  /// EncryptString 的摘要說明。
  /// </summary>
  public class EncryptString : System.Web.UI.Page
  {
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.WebControls.RadioButtonList RadioButtonList1;
  protected System.Web.UI.WebControls.TextBox TextBox2;
  protected System.Web.UI.WebControls.TextBox Textbox3;
  protected System.Web.UI.HtmlControls.HtmlForm Form1;
  
  private void Page_Load(object sender, System.EventArgs e)
  {
  // 在此處放置使用者代碼以初始化頁面
  if(!this.IsPostBack)
  {
  ArrayList MyList = new ArrayList();
  MyList.Add("加密");
  MyList.Add("解密");
  RadioButtonList1.DataSource = MyList;
  RadioButtonList1.DataBind();
  }
  }
  
  #region Web Form設計器產生的程式碼
  override protected void OnInit(EventArgs e)
  {
  //
  // CODEGEN: 該調用是 ASP.NET Web Form設計器所必需的。
  //
  InitializeComponent();
  base.OnInit(e);
  }
  /// <summary>
  /// 設計器支援所需的方法 - 不要使用代碼編輯器修改
  /// 此方法的內容。
  /// </summary>
  private void InitializeComponent()
  {
  this.RadioButtonList1.SelectedIndexChanged += new System.EventHandler(this.RadioButtonList1_SelectedIndexChanged);
  this.Load += new System.EventHandler(this.Page_Load);
  
  }
  #endregion
  
  private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)
  {
  if( RadioButtonList1.SelectedIndex == 0)
  TextBox2.Text = EncryptText(TextBox1.Text);
  else
  Textbox3.Text = DecryptText(TextBox2.Text);
  }
  // 加密
  public string EncryptText(String strText)
  {
  return Encrypt(strText, "&%#@?,:*");
  }
  
  //'解密
  public String DecryptText(String strText)
  {
  return Decrypt(strText, "&%#@?,:*");
  }
  //'加密函數
  private String Encrypt(String strText, String strEncrKey)
  {
  Byte[] byKey = {};
  Byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
  try
  {
  byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
  DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
  MemoryStream ms = new MemoryStream();
  CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
  cs.Write(inputByteArray, 0, inputByteArray.Length);
  cs.FlushFinalBlock();
  return Convert.ToBase64String(ms.ToArray());
  }
  catch(Exception ex)
  {
  return ex.Message;
  }
  }
  
  //'解密函數
  private String Decrypt(String strText, String sDecrKey)
  {
  Byte[] byKey = {};
  Byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
  Byte[] inputByteArray = new byte[strText.Length];
  try
  {
  byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
  DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  inputByteArray = Convert.FromBase64String(strText);
  MemoryStream ms = new MemoryStream();
  CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
  cs.Write(inputByteArray, 0, inputByteArray.Length);
  cs.FlushFinalBlock();
  System.Text.Encoding encoding = System.Text.Encoding.UTF8;
  return encoding.GetString(ms.ToArray());
  }
  catch(Exception ex)
  {
  return ex.Message;
  }
  }
  }
  }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.