using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace com.QH.QPGame.Utility
{
/// <summary>
/// 数据加密标准 (DES)是一种加密算法
/// </summary>
public class DESEncryption
{
private static byte[] Keys = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
/// <summary>
/// DES解密
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string Decrypt(string decryptString, string decryptKey)
{
decryptKey = TextUtility.CutLeft(decryptKey, 8);//取字符串前八位的小方法
decryptKey = decryptKey.PadRight(8, ' ');
byte[] bytes = Encoding.UTF8.GetBytes(decryptKey);
byte[] keys = Keys;
byte[] buffer = Convert.FromBase64String(decryptString);
var provider = new DESCryptoServiceProvider();
var stream = new MemoryStream();
var stream2 = new CryptoStream(stream, provider.CreateDecryptor(bytes, keys), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string Encrypt(string encryptString, string encryptKey)
{
encryptKey = TextUtility.CutLeft(encryptKey, 8);//取字符串前八位的小方法
encryptKey = encryptKey.PadRight(8, ' ');
byte[] bytes = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] keys = Keys;
byte[] buffer = Encoding.UTF8.GetBytes(encryptString);
var provider = new DESCryptoServiceProvider();
var stream = new MemoryStream();
var stream2 = new CryptoStream(stream, provider.CreateEncryptor(bytes, keys), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
return Convert.ToBase64String(stream.ToArray());
}
}
}