123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
- namespace Bowin.Common.DES
- {
- public class DesAccessor: IDesAccessor
- {
- /// <summary>
- /// DES加密
- /// </summary>
- /// <param name="encryptString">待加密的字符串</param>
- /// <param name="key">加密密钥,8倍数</param>
- /// <param name="iv">加密IV,8倍数</param>
- /// <returns></returns>
- public string Encrypt(string encryptString, byte[] key, byte[] iv)
- {
- //byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
- byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- des.Mode = CipherMode.ECB;
- des.Padding = PaddingMode.PKCS7;
- MemoryStream mStream = new MemoryStream();
- CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
- cStream.Write(inputByteArray, 0, inputByteArray.Length);
- cStream.FlushFinalBlock();
- return Convert.ToBase64String(mStream.ToArray());
- }
- /// <summary>
- /// DES解密
- /// </summary>
- /// <param name="decryptString">待解密的字符串</param>
- /// <param name="key">解密密钥,要求为8位,和加密密钥相同</param>
- /// <param name="iv">解密IV,要求为8位,和加密密钥相同</param>
- /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
- public string Decrypt(string decryptString, byte[] key, byte[] iv)
- {
- try
- {
- //byte[] rgbKey = Encoding.UTF8.GetBytes(Key);
- byte[] inputByteArray = Convert.FromBase64String(decryptString);
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- des.Mode = CipherMode.ECB;
- des.Padding = PaddingMode.PKCS7;
- MemoryStream mStream = new MemoryStream();
- CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);
- cStream.Write(inputByteArray, 0, inputByteArray.Length);
- cStream.FlushFinalBlock();
- return Encoding.UTF8.GetString(mStream.ToArray());
- }
- catch
- {
- return "";
- }
- }
- public string DeDesToken(DesModel desModel)
- {
- byte[] vi = new byte[8];
- var dk = "MMmmHHss";
- vi = Encoding.UTF8.GetBytes("00000000");
- byte[] key = Encoding.UTF8.GetBytes(desModel.tm.ToString(dk));
- return Decrypt(desModel.token, key, vi);
- }
- }
- }
|