using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Bowin.Common.DES
{
public class DesAccessor: IDesAccessor
{
///
/// DES加密
///
/// 待加密的字符串
/// 加密密钥,8倍数
/// 加密IV,8倍数
///
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());
}
///
/// DES解密
///
/// 待解密的字符串
/// 解密密钥,要求为8位,和加密密钥相同
/// 解密IV,要求为8位,和加密密钥相同
/// 解密成功返回解密后的字符串,失败返源串
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);
}
}
}