aes加密与DES加密及解密算法实现 aes加密与DES加密及解密算法实现

2016-06-11

明文的加密与解密在文件传输等方面有比较广的应用。下面列出 AES,DES加密与解密方法:

aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aes.aspx.cs" Inherits="aes" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       
        <asp:Button ID="Button1"  runat="server" Text="AES 加密测试" onclick="Button1_Click"
             />
    &nbsp;<asp:Button ID="Button2"  runat="server" Text="DES 加密测试"
             onclick="Button2_Click" />
    </div>
    </form>
</body>
</html>


.cs 页面

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Security.Cryptography;
using System.Text;

public partial class aes : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {  
       

    }

    /// <summary>
    /// AES 加密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="sKey"></param>
    /// <returns></returns>
    protected string Encrypt(string data, string sKey)
    {
        try
        {
            RijndaelManaged aes = new RijndaelManaged();
            byte[] bData = UTF8Encoding.UTF8.GetBytes(data);
            aes.Key = UTF8Encoding.UTF8.GetBytes(sKey);
            aes.IV = UTF8Encoding.UTF8.GetBytes(sKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            ICryptoTransform iCryptoTransform = aes.CreateEncryptor();
            byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);

            // return Convert.ToBase64String(bResult); //返回base64加密;
            return ByteToHex(bResult);                //返回十六进制数据;
        }
        catch
        {
            throw;
        }
    }
    /// <summary>
    /// AES 解密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="sKey"></param>
    /// <returns></returns>
    protected string Decrypt(string data, string sKey)
    {
        try
        {
            RijndaelManaged aes = new RijndaelManaged();
            //byte[] bData = Convert.FromBase64String(data); //解密base64;
            byte[] bData = HexToByte(data);                  //16进制to byte[];
            aes.Key = UTF8Encoding.UTF8.GetBytes(sKey);
            aes.IV = UTF8Encoding.UTF8.GetBytes(sKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            ICryptoTransform iCryptoTransform = aes.CreateDecryptor();
            byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);
            return Encoding.UTF8.GetString(bResult);
        }
        catch
        {
            throw;
        }
    }


    /// <summary>
    /// AES  字节  转换成十六进制字符串字节数组
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
 
    private byte[] HexToByte(string msg) 
    { 
        //remove any spaces from the string 
        msg = msg.Replace(" ", ""); 
        //create a byte array the length of the 
        //divided by 2 (Hex is 2 characters in length) 
        byte[] comBuffer = new byte[msg.Length / 2]; 
        //loop through the length of the provided string 
        for (int i = 0; i < msg.Length; i += 2) 
            //convert each set of 2 characters to a byte 
            //and add to the array 
            comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16); 
        //return the array 
        return comBuffer; 
    }

    /// <summary>
    /// AES  十六进制字符串字节数组 转换 字节
    /// </summary>
    /// <param name="comByte"></param>
    /// <returns></returns>
    private string ByteToHex(byte[] comByte) 
    { 
        //create a new StringBuilder object 
        StringBuilder builder = new StringBuilder(comByte.Length * 3); 
        //loop through each byte in the array 
        foreach (byte data in comByte) 
            //convert the byte to a string and add to the stringbuilder 
            builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' ')); 
        //return the converted value 
        return builder.ToString().ToUpper().Replace(" ", ""); 
    }
    /// <summary>
    /// DES 加密算法
    /// </summary>
    /// <param name="message"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    protected string DESEncrypt(string message, string key)
    {
        DES des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Key = Encoding.UTF8.GetBytes(key);
        des.IV = Encoding.UTF8.GetBytes(key);

        byte[] bytes = Encoding.UTF8.GetBytes(message);
        byte[] resultBytes = des.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);

        return Convert.ToBase64String(resultBytes); //密文以base64返回;(可根据实际需要返回16进制数据;)
    }
    /// <summary>
    ///  DES 解密算法
    /// </summary>
    /// <param name="message"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    protected  string DESDecrypt(string message, string key)
    {
        DES des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Key = Encoding.UTF8.GetBytes(key);
        des.IV = Encoding.UTF8.GetBytes(key);

        byte[] bytes = Convert.FromBase64String(message);
        byte[] resultBytes = des.CreateDecryptor().TransformFinalBlock(bytes, 0, bytes.Length);

        return Encoding.UTF8.GetString(resultBytes);
    }
    /// <summary>
    /// AES 加密测试
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        string data = this.TextBox1.Text.Trim();         //数据明文;
        string sKey = "gfgfgfgfgfgfgfgf";                //注意密钥(Key)的长度;本例是16个字符(128位);
        string Encrypted = Encrypt(data, sKey);
        string Decrypted = Decrypt(Encrypted, sKey);

        Response.Write("AES加密码结果:" + Encrypted);
        Response.Write("<br>");
        Response.Write("AES解密码结果:" + Decrypted);
    }

 


    /// <summary>
    /// DES 加密测试
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {
        string data = this.TextBox1.Text.Trim();         //数据明文;
        string sKey = "56856854";                //密钥(Key)的长度;


        string Encrypted = DESEncrypt(data, sKey);
        string Decrypted = DESDecrypt(Encrypted, sKey);

        Response.Write("DES加密码结果:" + Encrypted);
        Response.Write("<br>");
        Response.Write("DES解密码结果:" + Decrypted);
    }
}