您的位置:首页 > 编程语言 > C#

实现一个简单C#DES加密类

2007-03-28 15:21 531 查看
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MyWinFormApp
{
    public class DEScrypt
    {
        #region "Private Fields"
        //向量,私钥,加密类提供类字段
        private byte[] _iv;
        private byte[] _encryptKey;
        private DES _desProvider;

        #endregion

        #region "Properities"

        /// <summary>
        /// 向量
        /// </summary>
        public byte[] IV
        {
            get
            {
                return this._iv;
            }
        }

        /// <summary>
        /// 加密私钥
        /// </summary>
        public byte[] Key
        {
            get
            {
                return this._encryptKey;
            }
        }

        protected DES DesProvider
        {
            get {
                return this._desProvider;
            }
        }
        #endregion

        #region Constructor
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public DEScrypt()
        {
            if (this._iv == null)
                this._iv = Encoding.ASCII.GetBytes("1234!@#$");
            if (this._encryptKey == null)
                this._encryptKey = Encoding.ASCII.GetBytes("5678%^&*");
            this._desProvider = new DESCryptoServiceProvider();
        }

        /// <summary>
        /// 传入私钥的构造函数
        /// </summary>
        /// <param name="encryptKey">私钥</param>
        public DEScrypt(string encryptKey):this()
        {
            if (string.IsNullOrEmpty(encryptKey))
                throw new Exception("私钥不能为空");
            this._encryptKey = Encoding.ASCII.GetBytes(encryptKey);
        }
        /// <summary>
        /// 带初始化向量和私钥的构造函数
        /// </summary>
        /// <param name="iv">初始化向量</param>
        /// <param name="encryptKey">私钥</param>
        public DEScrypt(string iv,string encryptKey):this()
        {
            if (string.IsNullOrEmpty(iv) || string.IsNullOrEmpty(encryptKey))
                throw new Exception("初始化向量或私钥不能为空");
            this._iv = Encoding.ASCII.GetBytes(iv);
            this._encryptKey = Encoding.ASCII.GetBytes(encryptKey);
        }
        #endregion

        #region "Methods"
        /// <summary>
        /// 加密输入的文本,返回一加密的字符串
        /// </summary>
        /// <param name="literalText">明文</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(string literalText)
        {
            byte[] toEncrypt = Encoding.Unicode.GetBytes(literalText);
            byte[] encrypted;

            //创建加DES加密转换器
            ICryptoTransform cryptor = this.DesProvider.CreateEncryptor(this.Key, this.IV);
            //开放内存流存放加密数据
            using (MemoryStream memoryEncryptStream = new MemoryStream())
            {
                //DES加密流连接内存流
                using(CryptoStream cryptoStream = new CryptoStream(memoryEncryptStream,cryptor,CryptoStreamMode.Write))
                {
                    cryptoStream.Write(toEncrypt,0,toEncrypt.Length);
                    cryptoStream.FlushFinalBlock();
                    encrypted = memoryEncryptStream.ToArray();
                }
            }
    
            return encrypted;
        }

        /// <summary>
        /// 解密文本
        /// </summary>
        /// <param name="cryptText">加密字符串</param>
        /// <returns>还原的明文</returns>
        public string Descrypt(byte[] encrypted)
        {
            byte[] descrypted = new byte[encrypted.Length];

            ICryptoTransform descryptor = this.DesProvider.CreateDecryptor(this.Key,this.IV);
            using (MemoryStream memoryDescryptStream = new MemoryStream(encrypted))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryDescryptStream, descryptor, CryptoStreamMode.Read))
                {
                    cryptoStream.Read(descrypted, 0, encrypted.Length);
                }
            }

           return Encoding.Unicode.GetString(descrypted);

       }
        #endregion
   }
}
 

//使用

 //显示加密字节数组到界面
        private void cryeptButton_Click(object sender, EventArgs e)
        {
            DEScrypt des = new DEScrypt();
            byte[] result = des.Encrypt(this.LiteralText.Text);
            System.Text.StringBuilder strBuilder = new StringBuilder(result.Length);
            for (int i = 0; i < result.Length; i++)
            {
                if (i > 0)
                    strBuilder.Append(',');
                strBuilder.Append(result[i]);
            }  
            this.cryptText.Text = strBuilder.ToString();
        }

        //还原
        private void descryptButton_Click(object sender, EventArgs e)
        {
            DEScrypt des = new DEScrypt();
            string[] result = this.cryptText.Text.Split(new char[] { ','});
            byte[] descrypt = new byte[result.Length];
            for (int i = 0; i < result.Length; i++)
            {
                descrypt[i] = byte.Parse(result[i]);
            }
            this.descryptText.Text = des.Descrypt(descrypt);
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐