码迷,mamicode.com
首页 > Windows程序 > 详细

C# DES

时间:2016-08-23 14:35:22      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:

DES加密

using System.Security.Cryptography;

和AES一样只知道 ECB CBC CFB模式的用法

技术分享
 static class MyDES
    {
        static PaddingMode[] padding = {
            PaddingMode.PKCS7,
            PaddingMode.ANSIX923,
            PaddingMode.ISO10126,
            PaddingMode.None,
            PaddingMode.Zeros
        };
        static public string Encrypt(string Message, string key,string IV, CipherMode Mode,int pad)
        {
            try
            {

                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                byte[] keyIV = Encoding.UTF8.GetBytes(IV); 
                byte[] inputByteArray = Encoding.UTF8.GetBytes(Message);

                DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();

                // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
                desProvider.Mode = Mode;
                desProvider.Padding = padding[pad];
                MemoryStream memStream = new MemoryStream();
                CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);

                crypStream.Write(inputByteArray, 0, inputByteArray.Length);
                crypStream.FlushFinalBlock();
                return Convert.ToBase64String(memStream.ToArray());

            }
            catch
            {
                MessageBox.Show("加密失败");
                return "";
            }

        }
       
        static public string Decrypt(string Message, string key, string IV, CipherMode Mode,int pad)
        {
            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                byte[] keyIV = Encoding.UTF8.GetBytes(IV);
                byte[] inputByteArray = Convert.FromBase64String(Message);

                DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();

                // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
                desProvider.Mode = Mode;
                desProvider.Padding = padding[pad];
                MemoryStream memStream = new MemoryStream();
                CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);

                crypStream.Write(inputByteArray, 0, inputByteArray.Length);
                crypStream.FlushFinalBlock();
                return Encoding.Default.GetString(memStream.ToArray());
            }
            catch {
                MessageBox.Show("解密失败");
                return "";
            }

        }
       
    }
MyDES

 

C# DES

标签:

原文地址:http://www.cnblogs.com/xzhblogs/p/5799019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!