频道栏目
首页 > 程序开发 > 软件开发 > C# > 正文
C# 使用DES加密,解密字符串
2016-07-15 09:59:21         来源:遇见--专栏  
收藏   我要投稿

1 DES类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace NoticeBoard
{
    /// 
    /// DES加密解密算法
    /// 
    public class DES
    {
        /// 
        /// DES加密算法
        /// sKey为8位或16位
        /// 
        /// 需要加密的字符串
        /// 密钥
        /// 
        public string DesEncrypt(string pToEncrypt, string sKey)
        {
            StringBuilder ret = new StringBuilder();

            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
            }
            catch
            {

            }
            return ret.ToString();
            //return a;
        }
        /// 
        /// DES解密算法
        /// sKey为8位或16位
        /// 
        /// 需要解密的字符串
        /// 密钥
        /// 
        public string DesDecrypt(string pToDecrypt, string sKey)
        {  
            MemoryStream ms = new MemoryStream();

            try
            {
                DESCryptoServiceProvider des = 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;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
              
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
               
            }
            catch
            {

            } 
            
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
    }

    ///   
    /// 对称加密解密算法类  
    ///   
    public class Rijndael
    {
        private SymmetricAlgorithm mobjCryptoService;
        private string Key;
        ///   
        /// 对称加密类的构造函数  
        ///   
        public void SymmetricMethod()
        {
            mobjCryptoService = new RijndaelManaged();
            Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
        }
        ///   
        /// 获得密钥  
        ///   
        /// 密钥  
        private byte[] GetLegalKey()
        {
            string sTemp = Key;
            mobjCryptoService.GenerateKey();
            byte[] bytTemp = mobjCryptoService.Key;
            int KeyLength = bytTemp.Length;
            if (sTemp.Length > KeyLength)
                sTemp = sTemp.Substring(0, KeyLength);
            else if (sTemp.Length < KeyLength)
                sTemp = sTemp.PadRight(KeyLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        ///   
        /// 获得初始向量IV  
        ///   
        /// 初试向量IV  
        private byte[] GetLegalIV()
        {
            string sTemp = "aclejaspwejgjdjfasrweojksdf$%#@!^!@&#*ajke^!@#jka";     //key 随便写。。
            mobjCryptoService.GenerateIV();
            byte[] bytTemp = mobjCryptoService.IV;
            int IVLength = bytTemp.Length;
            if (sTemp.Length > IVLength)
                sTemp = sTemp.Substring(0, IVLength);
            else if (sTemp.Length < IVLength)
                sTemp = sTemp.PadRight(IVLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        ///   
        /// 加密方法  
        ///   
        /// 待加密的串  
        /// 经过加密的串  
        public string Encrypto(string Source)
        {
            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            MemoryStream ms = new MemoryStream();
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return Convert.ToBase64String(bytOut);
        }
        ///   
        /// 解密方法  
        ///   
        /// 待解密的串  
        /// 经过解密的串  
        public string Decrypto(string Source)
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
    }


}

2 DES加解密方法静态封装

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Xml;


namespace NoticeBoard
{
    public class StaticClass
    {

        #region 加密解密

        public static DES dd = new DES();

        public static string StringKey = "A123456."; // 加密密钥

        /// 
        /// 解密
        /// 
        ///
        /// 
        public static string StringDecder(string str)
        {
            return dd.DesDecrypt(str, StringKey);
        }

        /// 
        /// 加密
        /// 
        ///
        /// 
        public static string StringEncoder(string str)
        {
            return dd.DesEncrypt(str, StringKey);
        }

        #endregion 

    }
}

3 方法调用:

 

 

直接调用 StringDecder 和 StringEncoder 方法就行了

 

点击复制链接 与好友分享!回本站首页
相关TAG标签 字符串
上一篇:c# 代码实现打开文件 文件夹以及选择文件功能
下一篇:C#抽象类与接口的区别
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站