DES加密解密帮助类

    public class DESCrypto
    {
        /// <summary>
        /// 初始化des实例秘钥及向量
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static DESCryptoServiceProvider InitDESInstance(string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] salt = new byte[] { 0x0A, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xF1 };
            byte[] keyByte = Encoding.UTF8.GetBytes(key);
            Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(keyByte, salt, 8);
            Rfc2898DeriveBytes rfcIv = new Rfc2898DeriveBytes("0987654321", salt, 8);
            des.Key = rfcKey.GetBytes(8);
            des.IV = rfcIv.GetBytes(8);
            return des;
        }

        #region 基于Base64的加密解密(不其他格式的加解密方法配合使用)
        /// <summary>
        /// 基于Base64
        /// </summary>
        /// <param name="plaintext"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESEncryptBase64(string plaintext,string key)
        {
            DESCryptoServiceProvider des = InitDESInstance(key);
            byte[] dataByteArray = Encoding.UTF8.GetBytes(plaintext);
            string ciphertext = "";
            using (MemoryStream ms = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(dataByteArray, 0, dataByteArray.Length);
                cs.FlushFinalBlock();
                ciphertext = Convert.ToBase64String(ms.ToArray());
            }
            return ciphertext;
        }

        /// <summary>
        /// 基于Base64
        /// </summary>
        /// <param name="encrypt"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESDecryptBase64(string encrypt, string key)
        {
            DESCryptoServiceProvider des = InitDESInstance(key);
            byte[] dataByteArray = Convert.FromBase64String(encrypt);
            using (MemoryStream ms = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(dataByteArray, 0, dataByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        #endregion

        #region 基于2位十六进制格式的加密解密(不其他格式的加解密方法配合使用)
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plaintext">明文</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESEncrypt(string plaintext, string key)
        {
            DESCryptoServiceProvider des = InitDESInstance(key);
            StringBuilder sb = new StringBuilder();
            byte[] dataByteArray = Encoding.UTF8.GetBytes(plaintext);
            string ciphertext = "";
            using (MemoryStream ms = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(dataByteArray, 0, dataByteArray.Length);
                cs.FlushFinalBlock();
                //输出加密文本
                foreach (byte b in ms.ToArray())
                {
                    sb.AppendFormat("{0:X2}", b);
                }
                ciphertext = sb.ToString();
            }
            return ciphertext;

        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="ciphertext">密文</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESDecrypt(string ciphertext, string key)
        {
            DESCryptoServiceProvider des = InitDESInstance(key);
            byte[] dataByteArray = new byte[ciphertext.Length / 2];
            for (int x = 0; x < ciphertext.Length / 2; x++)
            {
                int i = (Convert.ToInt32(ciphertext.Substring(x * 2, 2), 16));
                dataByteArray[x] = (byte)i;
            }
            using (MemoryStream ms = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(dataByteArray, 0, dataByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        #endregion

        #region 文件加密解密(不其他格式的加解密方法配合使用)
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="sourceFile">文件的物理路径</param>
        /// <param name="encryptFile">文件的物理路径</param>
        /// <param name="key"></param>
        public static void DESEncryptFile(string sourceFile, string encryptFile, string key)
        {
            if (string.IsNullOrEmpty(sourceFile) || string.IsNullOrEmpty(encryptFile)||!File.Exists(sourceFile)) return;

            DESCryptoServiceProvider des = InitDESInstance(key);

            using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
            using (FileStream encryptStream = new FileStream(encryptFile, FileMode.Create, FileAccess.Write))
            {
                byte[] dataByteArray = new byte[sourceStream.Length];
                sourceStream.Read(dataByteArray, 0, dataByteArray.Length);
                using (CryptoStream cs = new CryptoStream(encryptStream, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(dataByteArray, 0, dataByteArray.Length);
                    cs.FlushFinalBlock();
                }
            }
        }

        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="encryptFile">文件的物理路径</param>
        /// <param name="decryptFile">文件的物理路径</param>
        /// <param name="key"></param>
        public static void DESDecryptFile(string encryptFile, string decryptFile, string key)
        {
            if (string.IsNullOrEmpty(encryptFile) || string.IsNullOrEmpty(decryptFile) || !File.Exists(encryptFile))return;

            DESCryptoServiceProvider des = InitDESInstance(key);

            using (FileStream encryptStream = new FileStream(encryptFile, FileMode.Open, FileAccess.Read))
            using (FileStream decryptStream = new FileStream(decryptFile, FileMode.Create, FileAccess.Write))
            {
                byte[] dataByteArray = new byte[encryptStream.Length];
                encryptStream.Read(dataByteArray, 0, dataByteArray.Length);
                using (CryptoStream cs = new CryptoStream(decryptStream, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(dataByteArray, 0, dataByteArray.Length);
                    cs.FlushFinalBlock();
                }
            }
        }

        /// <summary>
        /// 加密文本并输出到文件
        /// </summary>
        /// <param name="plaintext"></param>
        /// <param name="FileName">文件的物理路径</param>
        /// <param name="Key"></param>
        public static void DESEncryptTextToFile(string plaintext, string FileName, string key)
        {
            if (string.IsNullOrEmpty(FileName)) return;

            DESCryptoServiceProvider des = InitDESInstance(key);
            byte[] dataByteArray = Encoding.UTF8.GetBytes(plaintext);

            using (FileStream fStream = File.Open(FileName, FileMode.Create))
            using (CryptoStream cStream = new CryptoStream(fStream, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cStream.Write(dataByteArray, 0, dataByteArray.Length);
                cStream.FlushFinalBlock();
            }
        }

        /// <summary>
        /// 解密文件中的密文并返回
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static string DESDecryptTextFromFile(string FileName, string key)
        {
            if (string.IsNullOrEmpty(FileName)||!File.Exists(FileName)) return "";

            DESCryptoServiceProvider des = InitDESInstance(key);

            using (FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate))
            using (CryptoStream cStream = new CryptoStream(fStream, des.CreateDecryptor(), CryptoStreamMode.Read))
            using (StreamReader sReader = new StreamReader(cStream))
            {
                string val = sReader.ReadToEnd();
                return val;
            }
        }
        #endregion
    }

Tips:参考MSDN整理编写,比较全面。

DES加密解密帮助类,布布扣,bubuko.com

时间: 2024-10-03 05:35:05

DES加密解密帮助类的相关文章

DES加密解密工具类

import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto

DES加密/解密类。

/// <summary> /// DES加密/解密类. /// </summary> public class DESEncrypt { #region ========加密======== /// <summary> /// 加密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public s

加密解密工具类(Java,DES)

一个Java版的DES加密工具类,可以用来进行网络数据传输加密,保存密码的时候进行加密. import java.security.Key; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.I

DES加密解密类-java

import java.security.*; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * Copyright 2007 GuangZhou Cotel Co. Ltd. * All right reserved. * DES加密解密类. * @author <a

DES加密解密-&gt;java实现

DES加密解密涉及到的JAVA类 Cipher 此类为加密和解密提供密码功能.它构成了 Java Cryptographic Extension (JCE) 框架的核心. 为创建 Cipher 对象,应用程序调用 Cipher 的 getInstance 方法并将所请求转换 的名称传递给它.还可以指定提供者的名称(可选). 转换 是一个字符串,它描述为产生某种输出而在给定的输入上执行的操作(或一组操作).转换始终包括加密算法的名称(例如,DES),后面可能跟有一个反馈模式和填充方案. 转换具有以

PHP和.NET通用的加密解密函数类,均使用3DES加解密 .

以下为php代码 <PRE class=PHP name="code"> </PRE><PRE class=PHP name="code">PHP加解密函数:</PRE><PRE class=PHP name="code"> </PRE><PRE class=PHP name="code"> function encrypt($string)

MD5加密解密帮助类

using System; using System.Security.Cryptography; using System.Text; namespace Maticsoft.DBUtility { /// <summary> /// DES加密/解密类. /// </summary> public class DESEncrypt { public DESEncrypt() { } #region ========加密======== /// <summary> /

DES加密解密与AES加密解密

目录 [1]AES加密算法和DES加密算法的效率比较[2]AES和DES加密解密代码 随着开发时间的变长,当初认为比较难的东西,现在渐渐也就变的不那么难了!特别对于一些经常很少使用的类,时间长了之后渐渐就陌生了.所以在这里写一些日后可能会用到的加密与解密. 一.AES加密算法和DES加密算法的效率比较: 下面是在网上看到的一段关于“ES加密程序和一个AES加密程序,比较两个程序进行大文件加密的效率”: 实验步骤: 实验结果: 结果分析: 当文件很小时,两个程序加密的时间差不多.但是当文件变大时,

Discuz论坛写出的php加密解密处理类(代码+使用方法)

PHP加密解密也是常有的事,最近在弄相关的东西,发现discuz论坛里的PHP加密解密处理类代码,感觉挺不错,在用的时候,要参考Discuz论坛的passport相关函数,后面我会附上使用方法,先把类代码帖上来: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <?php /*