码迷,mamicode.com
首页 > 其他好文 > 详细

步步为营-30-AES加密与解密

时间:2017-04-22 09:36:51      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:分享   end   man   forms   log   name   btn   nsf   bsp   

技术分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace AES
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();            
        }
      
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
           string toEncrypt = txtString.Text.Trim().ToString();
            string key = txtKey.Text.Trim().ToString();
            string iv = txtIv.Text.Trim().ToString();
           lblResult.Text = Encrypt(toEncrypt, key, iv);
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            string toEncrypt = txtString.Text.Trim().ToString();
            string key = txtKey.Text.Trim().ToString();
            string iv = txtIv.Text.Trim().ToString();
            lblResult.Text = Decrypt(toEncrypt, key, iv);
        }

        public static string Encrypt(string toEncrypt, string key, string iv)
        {


            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;

            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string toDecrypt, string key, string iv)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}
View Code

 

步步为营-30-AES加密与解密

标签:分享   end   man   forms   log   name   btn   nsf   bsp   

原文地址:http://www.cnblogs.com/YK2012/p/6746745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!