几种加解密方法:AES、DES、SHA数据加密

一般项目都会用上加密,刚好手上的项目就用到DES加密,就贴一些代码记录一下

DES加密步奏:

1.初始化两个字符串,一个为指定的秘钥,一个为初始化向量,要求是8个字符。

2.加密:秘钥、向量、需加密的字符串传换成byte[]类型;

           声明加密标准类,DESCryptoServiceProvider

       创建内存流,MemoryStream

           创建将数据流链接到加密转换的流,CryptoStream

           将需加密的字符串写入当前加密对象

           讲缓冲区的当前状态更新基础数据

           将基础数据转换成64位等效字符返回

3.解密:方法同上

public class Encrypt
    {
        private static string key = "^&_C*2s#";
        private static string iv = "*-d&js50";
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串
        /// <param name="encryptKey">加密密钥,要求为8位
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string DesEncrypt(string encryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(key);
                byte[] rgbIV = Encoding.UTF8.GetBytes(iv);
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string DesDecrypt(string decryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(key);
                byte[] rgbIV = Encoding.UTF8.GetBytes(iv);
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
    }

 

posted on 2016-06-30 14:41  烟灭  阅读(10833)  评论(0编辑  收藏  举报