using System;using System.Text;using System.Windows.Forms;using System.Security.Cryptography;using System.IO;namespace WindowsFormsapplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } PRivate void button1_Click(object sender, EventArgs e)//加密 { DES desjiami = new DES(); textBox2.Text =desjiami.Encrypt(textBox1.Text, "goodmany"); } private void button2_Click(object sender, EventArgs e)//解密 { DES desjiami = new DES(); textBox1.Text = desjiami.Decrypt(textBox2.Text, "goodmany"); } } public class DES { public string Encrypt(string pToEncrypt, string sKey)//加密方法 { DESCryptoServiceProvider desCSP = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); desCSP.Key = ASCIIEncoding.ASCII.GetBytes(sKey); desCSP.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, desCSP.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder SB= new StringBuilder(); foreach (byte b in ms.ToArray()) { SB.AppendFormat("{0:X2}", b); } SB.ToString(); return SB.ToString(); } public string Decrypt(string pToDecrypt, string sKey)//解密 { DESCryptoServiceProvider desCSP = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } desCSP.Key = ASCIIEncoding.ASCII.GetBytes(sKey); desCSP.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, desCSP.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } }}
新闻热点
疑难解答