C# · 12月 19, 2021

DES加密解密

自己写的DES加密解密类,加密后生成Base64字符串,并去除’=’字符。

加密后替换掉’+’,这样加密后的字符串可以作为url参数传递。

using System; System.IO; System.Security.Cryptography; System.Text;namespace QuaEdu.Helper{ /// <summary> /// DES加密/解密类。 2014年3月15日 </summary> public class DESHelper { #region 默认密钥 <summary> 默认密钥 </summary> private static readonly string m_key = “simpo_s0611163″; #endregion #region ========加密======== <summary> 加密数据 </summary> <param name=”Text”>原文</param> <returns>密文</returns> string Encrypt(string Text) { return Encrypt(Text,m_key); } <param name=”sKey”>密钥string Text, sKey) { DESCryptoServiceProvider desKey = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(Text); byte[] keyByteArray = Encoding.Default.GetBytes(sKey); MD5CryptoServiceProvider md5 = MD5CryptoServiceProvider(); md5.ComputeHash(keyByteArray); desKey.Key = HalveByteArray(md5.Hash); desKey.IV = HalveByteArray(md5.Hash); MemoryStream ms = MemoryStream(); CryptoStream cs = CryptoStream(ms,desKey.CreateEncryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()).Replace(=”,””).Replace(+-“).Replace(/*); } #region ========解密======== 解密数据 string Decrypt( Decrypt(Text,1)”> sKey) { StringBuilder sb = StringBuilder(); if (Text.Length % 4 != ) { for (int i = 0; i < 4 – Text.Length % 4; i++) { sb.Append(); } } Text = Text.Replace(“) + sb.ToString(); DESCryptoServiceProvider desKey = Convert.FromBase64String(Text); Encoding.Default.GetString(ms.ToArray()); } #region 把字节数组缩短一半 把字节数组缩短一半 byte[] HalveByteArray(byte[] data) { byte[] result = new byte[data.Length / 2]; 0; i < result.Length; i++int x = (data[i * 2] + data[i * 2 + 1]) / ; result[i] = ()x; } result; } #endregion }}View Code