using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using WingServerCommon.Log;
namespace WingServerCommon.Config
{
public class ConfigCrypter
{
// Defalt key vector
private byte[] _keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private string _defaultKey = "vinno123";
///
/// DES encrypt string.
///
/// String to be encrypted
/// encrypt key,8 characters
/// Return encrypted string while success,empty string will be return while failed.
public string EncryptDES(string encryptString, string encryptKey = "")
{
try
{
var needEncrypt = !IsBase64Formatted(encryptString);
if (needEncrypt)
{
encryptKey = string.IsNullOrEmpty(encryptKey) ? _defaultKey : encryptKey;
var rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
var rgbIV = _keys;
var inputByteArray = Encoding.UTF8.GetBytes(encryptString);
var dCSP = new DESCryptoServiceProvider();
var mStream = new MemoryStream();
var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
var asdsad = Convert.ToBase64String(mStream.ToArray());
return Convert.ToBase64String(mStream.ToArray());
}
else
{
return encryptString;
}
}
catch (Exception e)
{
Logger.WriteLineError($"Encrypt failed:{e}");
return string.Empty;
}
}
///
/// DES decrypt string
///
/// String to be decrypted
/// decrypt key,8 characters,same as encrypt key.
/// Return decrypted string while success,source string will be return while failed.
public string DecryptDES(string decryptString, string decryptKey = "")
{
if (string.IsNullOrEmpty(decryptString))
{
return string.Empty;
}
var needDecrypt = IsBase64Formatted(decryptString);
if (needDecrypt)
{
try
{
decryptKey = string.IsNullOrEmpty(decryptKey) ? _defaultKey : decryptKey;
var rgbKey = Encoding.UTF8.GetBytes(decryptKey);
var rgbIV = _keys;
var inputByteArray = Convert.FromBase64String(decryptString);
var DCSP = new DESCryptoServiceProvider();
var mStream = new MemoryStream();
var cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
var asdasd = Encoding.UTF8.GetString(mStream.ToArray());
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch (Exception e)
{
Logger.WriteLineError($"decrypt failed:{e}");
return decryptString;
}
}
return decryptString;
}
private bool IsBase64Formatted(string input)
{
try
{
Convert.FromBase64String(input);
return true;
}
catch
{
return false;
}
}
}
}