如果项目要上线到公网中,那么我们就需要考虑安全问题;
即便是在内网使用,安全问题也同样不能忽视。
如果没有一套安全方案,那么我们的服务很有可能会被攻击。
安全方案主要有加签名进行数据效验、传输数据加密等。
1、加签SHA256
public static string GetSHA256Hash(string input)
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
2、RSA加密/解密
private readonly RSA _privateKeyRsaProvider;
private readonly RSA _publicKeyRsaProvider;
private readonly Encoding _encoding;
/// <param name="encoding">编码类型</param>
/// <param name="privateKey">私钥</param>
/// <param name="publicKey">公钥</param>
public RSAHelper(Encoding encoding, string privateKey, string publicKey = null)
{
_encoding = encoding;
if (!string.IsNullOrEmpty(privateKey))
{
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
}
if (!string.IsNullOrEmpty(publicKey))
{
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
}
}
//解密
public string Decrypt(string cipherText)
{
if (_privateKeyRsaProvider == null)
{
throw new Exception("_privateKeyRsaProvider is null");
}
return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
}
//加密
public string Encrypt(string text)
{
if (_publicKeyRsaProvider == null)
{
throw new Exception("_publicKeyRsaProvider is null");
}
return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1));
}
private readonly RSA _publicKeyRsaProvider;
private readonly Encoding _encoding;
/// <param name="encoding">编码类型</param>
/// <param name="privateKey">私钥</param>
/// <param name="publicKey">公钥</param>
public RSAHelper(Encoding encoding, string privateKey, string publicKey = null)
{
_encoding = encoding;
if (!string.IsNullOrEmpty(privateKey))
{
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
}
if (!string.IsNullOrEmpty(publicKey))
{
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
}
}
//解密
public string Decrypt(string cipherText)
{
if (_privateKeyRsaProvider == null)
{
throw new Exception("_privateKeyRsaProvider is null");
}
return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
}
//加密
public string Encrypt(string text)
{
if (_publicKeyRsaProvider == null)
{
throw new Exception("_publicKeyRsaProvider is null");
}
return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1));
}
3、AES加密/解密
/// <summary>
/// 加密不带偏移量
/// </summary>
/// <param name="input"></param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string EncryptByAES(string input, string key)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Mode = CipherMode.ECB;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.FeedbackSize = 128;
byte[] data3 = Enumerable.Range(0, key.Length / 2).Select(x => Byte.Parse(key.Substring(x * 2, 2), NumberStyles.HexNumber)).ToArray();
rijndaelManaged.Key = data3;
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
byte[] bytes = msEncrypt.ToArray();
//return Convert.ToBase64String(bytes);
return HexConvert.byteToHexStr(bytes);
}
}
}
}
/// 加密不带偏移量
/// </summary>
/// <param name="input"></param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string EncryptByAES(string input, string key)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Mode = CipherMode.ECB;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.FeedbackSize = 128;
byte[] data3 = Enumerable.Range(0, key.Length / 2).Select(x => Byte.Parse(key.Substring(x * 2, 2), NumberStyles.HexNumber)).ToArray();
rijndaelManaged.Key = data3;
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
byte[] bytes = msEncrypt.ToArray();
//return Convert.ToBase64String(bytes);
return HexConvert.byteToHexStr(bytes);
}
}
}
}
/// <summary>
/// 返回解密后的字符串
/// </summary>
/// <param name="input"></param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string DecryptByAES(string input, string key)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
//var buffer = Convert.FromBase64String(input);
var buffer = HexConvert.strToToHexByte(input);
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Mode = CipherMode.ECB;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.FeedbackSize = 128;
byte[] data3 = Enumerable.Range(0, key.Length / 2).Select(x => Byte.Parse(key.Substring(x * 2, 2), NumberStyles.HexNumber)).ToArray();
rijndaelManaged.Key = data3;
ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
using (MemoryStream msEncrypt = new MemoryStream(buffer))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}
/// 返回解密后的字符串
/// </summary>
/// <param name="input"></param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string DecryptByAES(string input, string key)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
//var buffer = Convert.FromBase64String(input);
var buffer = HexConvert.strToToHexByte(input);
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Mode = CipherMode.ECB;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.FeedbackSize = 128;
byte[] data3 = Enumerable.Range(0, key.Length / 2).Select(x => Byte.Parse(key.Substring(x * 2, 2), NumberStyles.HexNumber)).ToArray();
rijndaelManaged.Key = data3;
ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
using (MemoryStream msEncrypt = new MemoryStream(buffer))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}
4、数据转换
//字符串转换为字节数组
byte[] originalBytes = System.Text.Encoding.UTF8.GetBytes(originalText);
// 进行Base64编码
string base64Encoded = Convert.ToBase64String(originalBytes);
// 进行Base64解码
byte[] base64DecodedBytes = Convert.FromBase64String(base64Encoded);
//字节数组转字符串
string base64DecodedText = System.Text.Encoding.UTF8.GetString(base64DecodedBytes);
//16进制转base64字符串
byte[] enterpriseCode_ = HexConvert.strToToHexByte(data.enterpriseCode);
string enterpriseCode = Convert.ToBase64String(enterpriseCode_);
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
public static string byteToHexStr2(byte[] byteArray)
{
string hexString = BitConverter.ToString(byteArray);
return hexString.Replace("-", "");
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
byte[] originalBytes = System.Text.Encoding.UTF8.GetBytes(originalText);
// 进行Base64编码
string base64Encoded = Convert.ToBase64String(originalBytes);
// 进行Base64解码
byte[] base64DecodedBytes = Convert.FromBase64String(base64Encoded);
//字节数组转字符串
string base64DecodedText = System.Text.Encoding.UTF8.GetString(base64DecodedBytes);
//16进制转base64字符串
byte[] enterpriseCode_ = HexConvert.strToToHexByte(data.enterpriseCode);
string enterpriseCode = Convert.ToBase64String(enterpriseCode_);
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
public static string byteToHexStr2(byte[] byteArray)
{
string hexString = BitConverter.ToString(byteArray);
return hexString.Replace("-", "");
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}