using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace Interact.TeleSales
{
/// <summary>
/// DesUtil 的摘要说明。
/// </summary>
public class DesUtil
{
public DesUtil()
{
}

//解密方法
public static string Decrypt(string data,string key)
{
//一般为从Base64转换,此处不是
byte[] buf = Encoding.UTF8.GetBytes(data);
int len = data.Length;
byte[] inputByteArray = new byte[len / 2];
for(int i = 0; i < len; i = i + 2)
{
string tmp = ASCIIEncoding.ASCII.GetString(buf, i, 2);
inputByteArray[i/2] = (byte)Convert.ToInt32(tmp, 16);
}
//byte[] inputByteArray = Convert.FromBase64String(data);

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
// java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
des.Mode = CipherMode.ECB;
des.Key = UTF8Encoding.UTF8.GetBytes(key);

try
{
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

return Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
return "";
}
}
//加密方法
public static string Encrypt(string data,string key)
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(data);
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();

// java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
desProvider.Mode = CipherMode.ECB;
desProvider.Key = UTF8Encoding.UTF8.GetBytes(key);
MemoryStream memStream = new MemoryStream();
CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(), CryptoStreamMode.Write);

crypStream.Write(inputByteArray, 0, inputByteArray.Length);
crypStream.FlushFinalBlock();

byte[] outputByteArray = memStream.ToArray();
//一般为转换为Base64,此处不是
//string ret = Convert.ToBase64String(outputByteArray);

int len = outputByteArray.Length;
StringBuilder strout = new StringBuilder();
for(int i = 0; i<len; i++)
{
strout.AppendFormat("{0:X2}", outputByteArray[i]);
}
return strout.ToString();
}
}
}

posted on 2020-08-19 13:30  没入门就放弃  阅读(1163)  评论(0编辑  收藏  举报