using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace FileServerApi.Common
{
public class DESEncrypt
{
#region 加密解密法
//默认密钥向量
private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
///
/// DES加密字符串
///
/// 待加密的字符串
/// 加密密钥,要求为16位
/// 加密成功返回加密后的字符串,失败返回源串
public static string EncryptDES(string encryptString, string encryptKey = "upload#20180319#down")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
var DCSP = Aes.Create();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
//return Convert.ToBase64String(mStream.ToArray());
return BytesToHex(mStream.ToArray());
}
catch (Exception ex)
{
return ex.Message + encryptString;
}
}
///
/// DES解密字符串
///
/// 待解密的字符串
/// 解密密钥,要求为16位,和加密密钥相同
/// 解密成功返回解密后的字符串,失败返源串
public static string DecryptDES(string decryptString, string decryptKey = "upload#20180319#down")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16));
byte[] rgbIV = Keys;
//byte[] inputByteArray = Convert.FromBase64String(decryptString);
byte[] inputByteArray = HexToBytes(decryptString);
var DCSP = Aes.Create();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
Byte[] inputByteArrays = new byte[inputByteArray.Length];
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch (Exception ex)
{
return ex.Message + decryptString;
}
}
public static byte[] HexToBytes(string Hex)
{
int num = (int)Math.Round((double)(((double)Hex.Length) / 2));
byte[] buffer = new byte[(num - 1) + 1];
int num3 = num - 1;
for (int i = 0; i <= num3; i++)
{
string s = Hex.Substring(i * 2, 2);
buffer[i] = (byte)int.Parse(s, NumberStyles.HexNumber);
}
return buffer;
}
public static string BytesToHex(byte[] bytes)
{
StringBuilder builder = new StringBuilder();
int num2 = bytes.Length - 1;
for (int i = 0; i <= num2; i++)
{
builder.AppendFormat("{0:X2}", bytes[i]);
}
return builder.ToString();
}
#endregion
}
}