using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using NETCore.Encrypt;
namespace Common
{
///
/// 安全加密解密类
///
public class SafeTools
{
///
/// HmacSHA256加密
///
///
///
///
public static String HmacSHA256(String text, String key)
{
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] textBytes = encoding.GetBytes(text);
Byte[] keyBytes = encoding.GetBytes(key);
Byte[] hashBytes;
using (HMACSHA256 hash = new HMACSHA256(keyBytes))
hashBytes = hash.ComputeHash(textBytes);
return BitConverter.ToString(hashBytes).ToLower();
// return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
///
/// 将字符串转换成base64格式,使用UTF8字符集
///
/// 加密内容
///
public static string Base64Encode(string content)
{
byte[] bytes = Encoding.UTF8.GetBytes(content);
return Convert.ToBase64String(bytes);
}
///
/// 将base64格式,转换utf8
///
/// 解密内容
///
public static string Base64Decode(string content)
{
byte[] bytes = Convert.FromBase64String(content);
return Encoding.UTF8.GetString(bytes);
}
///
/// SHA-1加密
///
///
///
public static string SHA1(string Value)
{
return EncryptProvider.Sha1(Value);
}
///
/// DES对称加密字符串
///
/// 待加密的字符串
/// 加密密钥,要求为16位
/// 加密成功返回加密后的字符串,失败返回源串
public static string EncryptDES(string encryptString, string key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(key);
//用于对称算法的初始化向量(默认值)。
byte[] rgbIV = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
Aes 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());
}
catch (Exception ex)
{
throw ex;
}
}
///
/// DES对称解密字符串
///
/// 待解密的字符串
/// 解密密钥,要求16位
///
public static string DecryptDES(string decryptString, string key)
{
try
{
//用于对称算法的初始化向量(默认值)
byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
byte[] rgbKey = Encoding.UTF8.GetBytes(key);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
Aes DCSP = Aes.Create();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
}
}