C#winform的加密与解密源代码测试成功

来源:互联网 发布:mac搜狗五笔输入法 编辑:程序博客网 时间:2024/05/29 10:47



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());        }    }}

0 0
原创粉丝点击