标签:
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 ""; } } }
标签:
原文地址:http://www.cnblogs.com/xzhblogs/p/5799019.html