using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
namespace System
{
public static class EncryptHelper
{
///
/// AES秘钥(强烈要求.json自定义取出)
///
private const string AesKey = "OwenItc-*&$%RTj3";
///
/// AES偏移向量(强烈要求.json自定义取出)
///
private const string AesIV = "*&^KJ8a-Tj3*&$%R";
public static string AesEncrypt(string toEncryptString)
{
return AesEncrypt(toEncryptString, AesKey, AesIV);
}
///
/// AES加密
///
/// 待加密的明文
///
public static string AesEncrypt(this string toEncryptString, string aesKey, string aesIV)
{
var rijndaelCipher = new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128
};
var toEncryptBytes = Encoding.UTF8.GetBytes(toEncryptString);
var keyBytes = Encoding.UTF8.GetBytes(aesKey);
var ivBytes = Encoding.UTF8.GetBytes(aesIV);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] cipherBytes = transform.TransformFinalBlock(toEncryptBytes, 0, toEncryptBytes.Length);
return Convert.ToBase64String(cipherBytes);
}
public static string AesDecrpt(string toDecrpt)
{
return AesDecrpt(toDecrpt, AesKey, AesIV);
}
///
/// AES解密
///
///
///
public static string AesDecrpt(this string toDecrpt, string aesKey, string aesIV)
{
var key = Encoding.UTF8.GetBytes(aesKey);
var encryptedData = Convert.FromBase64String(toDecrpt);
var iv = Encoding.UTF8.GetBytes(aesIV);
var rDel = new RijndaelManaged
{
Key = key,
IV = iv,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var cTransform = rDel.CreateDecryptor();
var resultArray = cTransform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(resultArray);
}
public static string UrlEncode(string toEncryptString)
{
if (string.IsNullOrEmpty(toEncryptString)) return null;
return HttpUtility.UrlEncode(AesEncrypt(toEncryptString), Encoding.UTF8);
}
public static string UrlDecode(string toEncryptString)
{
if (string.IsNullOrEmpty(toEncryptString)) return null;
return AesDecrpt(toEncryptString);
}
public static string Decode(string toEncryptString)
{
if (string.IsNullOrEmpty(toEncryptString)) return null;
return AesDecrpt(HttpUtility.UrlDecode(toEncryptString, Encoding.UTF8));
}
public static string GetMd5(this string source)
{
if (string.IsNullOrEmpty(source)) return null;
MD5 md = MD5.Create();
byte[] bytes = md.ComputeHash(System.Text.Encoding.UTF8.GetBytes(source));
string dec = null;
foreach (byte b in bytes)
{
dec += b.ToString("x2");
}
return dec;
}
}
}