C# 使用DES加密,解密字符串

1 DES类

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

namespace NoticeBoard
{
    /// <summary>
    /// DES加密解密算法
    /// </summary>
    public class DES
    {
        /// <summary>
        /// DES加密算法
        /// sKey为8位或16位
        /// </summary>
        /// <param name="pToEncrypt">需要加密的字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// DES解密算法
        /// sKey为8位或16位
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        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());
        }
    }

    /// <summary>  
    /// 对称加密解密算法类  
    /// </summary>  
    public class Rijndael
    {
        private SymmetricAlgorithm mobjCryptoService;
        private string Key;
        /// <summary>  
        /// 对称加密类的构造函数  
        /// </summary>  
        public void SymmetricMethod()
        {
            mobjCryptoService = new RijndaelManaged();
            Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
        }
        /// <summary>  
        /// 获得密钥  
        /// </summary>  
        /// <returns>密钥</returns>  
        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);
        }
        /// <summary>  
        /// 获得初始向量IV  
        /// </summary>  
        /// <returns>初试向量IV</returns>  
        private byte[] GetLegalIV()
        {
            string sTemp = "aclejaspwejgjdjfasrweojksdf$%#@!^[email protected]&#*ajke^[email protected]#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);
        }
        /// <summary>  
        /// 加密方法  
        /// </summary>  
        /// <param name="Source">待加密的串</param>  
        /// <returns>经过加密的串</returns>  
        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);
        }
        /// <summary>  
        /// 解密方法  
        /// </summary>  
        /// <param name="Source">待解密的串</param>  
        /// <returns>经过解密的串</returns>  
        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."; // 加密密钥

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringDecder(string str)
        {
            return dd.DesDecrypt(str, StringKey);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringEncoder(string str)
        {
            return dd.DesEncrypt(str, StringKey);
        }

        #endregion 

    }
}

3 方法调用:

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

时间: 2024-09-29 00:50:22

C# 使用DES加密,解密字符串的相关文章

DES加密解密字符串的JAVA实现(lp)

野火烧不尽,春风吹又生.众里寻他千百度,蓦然回首,那人却在灯火阑珊处.天作孽,犹可违,自作孽,不可活.山高月小,水落石出.晴川历历汉阳树,芳草萋萋鹦鹉洲. package test.des2.tt; /** * * 这个是真正实用的.修正了以前方法的只加密了前8位正确的bug. */ import java.security.*; import javax.crypto.*; public class DESPlus { private static String strDefaultKey =

C#DES加密解密字符串

1.添加引用 using System.Security.Cryptography; using System.IO; 2.添加默认密匙向量 //默认密钥向量 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 3.添加加密解密类 /// <summary> /// DES加密字符串 /// </summary> /// <param name="encry

使用C# DES解密java DES加密的字符串

转自 microAllen 最近需要使用C#的DES解密工具类解密字符串,但是要解密的字符串是使用java进行DES加密的,去网上查了关于C#和java关于DES加密解密的资料,发现可以相互加密解密的时候,java进行DES加密一般都会写成如下:public static byte[] encrypt(String message, String key) throws Exception {     Cipher cipher = Cipher.getInstance("DES/CBC/PKC

记录新项目中遇到的技术及自己忘记的技术点【DES加密解密,MD5加密,字符串压缩、解压,字符串截取等操作】

一.DES加密.解密 #region DES加密解密 /// <summary> /// 进行DES加密 /// </summary> /// <param name="pToEncrypt">要加密的字符串</param> /// <param name="sKey">密钥,必须为8位</param> /// <returns>以Base64格式返回的加密字符串</retur

des加密解密——java加密,php解密

最近在做项目中,遇到des加密解密的问题. 场景是安卓app端用des加密,php这边需要解密.之前没有接触过des这种加密解密算法,但想着肯定会有demo.因此百度,搜了代码来用.网上代码也是鱼龙混杂,好不容易测试在php这边测试加密和解密成功了.为确保安卓app端提交过来的加密参数能够解密出来,给定安卓人员一个字符串,让他们把des加密后的字符串给我,在php这边解密.结果一看,加密出来的字符串跟我这边加密出来的结果不一致,自然是解密不出来. 要来java的des算法代码,研究加密的过程,其

兼容PHP和Java的des加密解密代码分享

这篇文章主要介绍了兼容PHP和Java的des加密解密代码分享,适合如服务器是JAVA语言编写,客户端是PHP编写,并需要des加密解密的情况,需要的朋友可以参考下 php <?php class DES { var $key; var $iv; //偏移量 function DES($key, $iv=0) { $this->key = $key; if($iv == 0) { $this->iv = $key; } else { $this->iv = $iv; } } //加

DES加密解密的C++源程序

DES加密解密的C++源程序 --测试版本,希望大家多多交流 #include<iostream.h> #include"stdio.h" #include"math.h" #include "string.h" static char key[16][48]; static char Hex[16][4]; ////IP置换. int IP[64]= { 58,50,42,34,26,18,10,2,\ 60,52,44,36,28

C# Java DES加密解密

c#代码: public class DESHelper    {          /// <summary>        /// DES加密算法        /// </summary>        /// <param name="encryptString">要加密的字符串</param>        /// <param name="sKey">加密码Key</param>  

.net实现md5加密 sha1加密 sha256加密 sha384加密 sha512加密 des加密解密

写项目时,后台一直用md5加密,一天群里人问,除了MD5还有其它的加密方法吗?当时只知道还有个SHA,但怎么实现什么的都不清楚,于是当网上找了下,把几种常见的加密方法都整理了下,用winform写了个程序,如图: 关键代码 using System.Security;using System.Security.Cryptography;using System.Web;using System.IO; //MD5 不区分大小写的        //type 类型,16位还是32位,16位就是取3

Java加密解密字符串

http://www.cnblogs.com/vwpolo/archive/2012/07/18/2597232.html Java加密解密字符串 旧文重发:http://www.blogjava.net/vwpolo/archive/2009/12/05/304874.html#383365 import java.security.Key; import java.security.Security; import javax.crypto.Cipher; /** * DES加密和解密工具,