C#版3DES加密解密简单示例

时间:2021-01-01 20:29:47
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.IO;

namespace _3DES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void CrypeBtn_Click(object sender, EventArgs e)
{
//实例化三倍DES服务提供者类
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

//随机生成密钥和IV向量
TDES.GenerateIV();
TDES.GenerateKey();

//执行加密
byte[] EncrypeByte = EncrypText(StrBox.Text, TDES.Key, TDES.IV);

//显示密文和密钥
KeyBox.Text = Encoding.ASCII.GetString(TDES.Key);
IVBox.Text = Encoding.ASCII.GetString(TDES.IV);
CrypeBox.Text = Encoding.UTF8.GetString(EncrypeByte);

//执行解密
Str2Box.Text = DecrypText(EncrypeByte, TDES.Key, TDES.IV);
}

#region 加密
/// <summary>
/// 执行三倍DES加密的方法
/// </summary>
/// <param name="Str">明文字符串</param>
/// <param name="Key">密钥</param>
/// <param name="IV">IV向量</param>
/// <returns>密文的字节序列</returns>
private byte[] EncrypText(string Str, byte[] Key, byte[] IV)
{
//创建一个内存流,用于存放密文
MemoryStream MS = new MemoryStream();

//创建一个三倍DES服务提供者对象
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

//创建一个加密流,用于加密操作
CryptoStream CS = new CryptoStream(MS,
TDES.CreateEncryptor(Key, IV),
CryptoStreamMode.Write);

//定义输入,执行加密操作
CS.Write(Encoding.UTF8.GetBytes(Str), 0, Str.Length);
CS.FlushFinalBlock();

//返回将密文的内存流转换为字节序列并返回
return MS.ToArray();
}
#endregion

#region 解密
/// <summary>
/// 执行三倍DES解密的方法
/// </summary>
/// <param name="CrypeText">密文的字节序列</param>
/// <param name="Key">密钥</param>
/// <param name="IV">IV向量</param>
/// <returns>明文的字符串</returns>
private string DecrypText(byte[] CrypeText, byte[] Key, byte[] IV)
{
//创建一个内存流,用于存放密文
MemoryStream MS = new MemoryStream(CrypeText);

//创建一个三倍DES服务提供者对象
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

//创建解密流
CryptoStream CS = new CryptoStream(MS,
TDES.CreateDecryptor(Key, IV),
CryptoStreamMode.Read);

//创建一个用于存放明文的容器(字节序列)
byte[] DecrypeBytes = new byte[CrypeText.Length];

//执行解密
CS.Read(DecrypeBytes, 0, CrypeText.Length);

//返回解密后的明文字符串
return Encoding.UTF8.GetString(DecrypeBytes);
}

#endregion
}

}


C#版3DES加密解密简单示例