在我们日常开发工作中,为了数据安全问题对数据加密、解密是必不可少的。加密方式有很多种如常见的AES,RSA,MD5,SAH1,SAH256,DES等,这时候假如我们有一个封装的对应加密解密工具类可以直接调用,那这样可以节省不少的开发时间。今天推荐一款实用的.NET Core加密解密工具类库:NETCore.Encrypt。
NETCore.Encrypt是.NET Core加密解密工具类库,包括AES、RSA、MD5、SHA1、DES、SHA256、SHA384、SHA512等更多功能。
#region MD5
///
/// MD5 hash
///
/// The string to be encrypted.
/// The length of hash result , default value is .
///
public static string Md5(string srcString, MD5Length length = MD5Length.L32)
{
Check.Argument.IsNotEmpty(srcString, nameof(srcString));
string str_md5_out = string.Empty;
using (MD5 md5 = MD5.Create())
{
byte[] bytes_md5_in = Encoding.UTF8.GetBytes(srcString);
byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in);
str_md5_out = length == MD5Length.L32
? BitConverter.ToString(bytes_md5_out)
: BitConverter.ToString(bytes_md5_out, 4, 8);
str_md5_out = str_md5_out.Replace("-", "");
return str_md5_out;
}
}
#endregion
public static void MD5_Test() { var srcString = "追逐时光者"; var hashed = EncryptProvider.Md5(srcString); Console.WriteLine("MD5加密结果:" + hashed); }
///
/// RSA encrypt
///
/// public key
/// src string
/// rsa encryptPadding RSAEncryptionPadding.Pkcs1 for linux/mac openssl
/// set key is pem format,default is false
/// encrypted string
public static string RSAEncrypt(string publicKey, string srcString, RSAEncryptionPadding padding, bool isPemKey = false)
{
Check.Argument.IsNotEmpty(publicKey, nameof(publicKey));
Check.Argument.IsNotEmpty(srcString, nameof(srcString));
Check.Argument.IsNotNull(padding, nameof(padding));
RSA rsa;
if (isPemKey)
{
rsa = RsaProvider.FromPem(publicKey);
}
else
{
rsa = RSA.Create();
rsa.FromJsonString(publicKey);
}
using (rsa)
{
var maxLength = GetMaxRsaEncryptLength(rsa, padding);
var rawBytes = Encoding.UTF8.GetBytes(srcString);
if (rawBytes.Length > maxLength)
{
throw new OutofMaxlengthException($"'{srcString}' is out of max encrypt length {maxLength}", maxLength, rsa.KeySize, padding);
}
byte[] encryptBytes = rsa.Encrypt(rawBytes, padding);
return encryptBytes.ToHexString();
}
}
///
/// RSA decrypt
///
/// public key
/// src string
/// rsa encryptPadding RSAEncryptionPadding.Pkcs1 for linux/mac openssl
/// set key is pem format,default is false
/// encrypted string
public static string RSADecrypt(string privateKey, string srcString, RSAEncryptionPadding padding, bool isPemKey = false)
{
Check.Argument.IsNotEmpty(privateKey, nameof(privateKey));
Check.Argument.IsNotEmpty(srcString, nameof(srcString));
Check.Argument.IsNotNull(padding, nameof(padding));
RSA rsa;
if (isPemKey)
{
rsa = RsaProvider.FromPem(privateKey);
}
else
{
rsa = RSA.Create();
rsa.FromJsonString(privateKey);
}
using (rsa)
{
byte[] srcBytes = srcString.ToBytes();
byte[] decryptBytes = rsa.Decrypt(srcBytes, padding);
return Encoding.UTF8.GetString(decryptBytes);
}
}
#region Rsa加密&解密
public static void Rsa_Encrypt_Decrypt_Test(RsaSize size)
{
var rsaKey = EncryptProvider.CreateRsaKey(size);
var srcString = "追逐时光者";
var encrypted = EncryptProvider.RSAEncrypt(rsaKey.PublicKey, srcString);
Console.WriteLine("RSA加密结果:" + encrypted);
Console.WriteLine("\r\n");
var decrypted = EncryptProvider.RSADecrypt(rsaKey.PrivateKey, encrypted);
Console.WriteLine("RSA解密结果:" + decrypted);
}
#endregion
///
/// DES encrypt
///
/// Raw data byte array
/// Key, requires 24 bits
/// IV,requires 8 bits
/// Encrypted byte array
public static byte[] DESEncrypt(byte[] data, string key, string vector)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 24, nameof(key));
Check.Argument.IsNotEmpty(vector, nameof(vector));
Check.Argument.IsEqualLength(vector.Length, 8, nameof(vector));
return DESEncrypt(data, key, CipherMode.CBC, vector);
}
///
/// DES encrypt
///
/// Raw data
/// Key, requires 24 bits
///
/// default is PKCS7
/// IV,requires 8 bits
/// Encrypted byte array
private static byte[] DESEncrypt(byte[] data, string key, CipherMode cipherMode, string vector = "", PaddingMode paddingMode = PaddingMode.PKCS7)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 24, nameof(key));
using (MemoryStream Memory = new MemoryStream())
{
using (TripleDES des = TripleDES.Create())
{
byte[] plainBytes = data;
byte[] bKey = new byte[24];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
des.Mode = cipherMode;
des.Padding = paddingMode;
des.Key = bKey;
if (cipherMode == CipherMode.CBC)
{
byte[] bVector = new byte[8];
Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(bVector.Length)), bVector, bVector.Length);
des.IV = bVector;
}
using (CryptoStream cryptoStream = new CryptoStream(Memory, des.CreateEncryptor(), CryptoStreamMode.Write))
{
try
{
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
return Memory.ToArray();
}
catch (Exception ex)
{
return null;
}
}
}
}
}
///
/// DES encrypt
///
/// Raw data byte array
/// Key, requires 24 bits
/// IV,requires 8 bits
/// Encrypted byte array
public static byte[] DESDecrypt(byte[] data, string key, string vector)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 24, nameof(key));
Check.Argument.IsNotEmpty(vector, nameof(vector));
Check.Argument.IsEqualLength(vector.Length, 8, nameof(vector));
return DESDecrypt(data, key, CipherMode.CBC, vector);
}
///
/// DES decrypt
///
/// Encrypted data
/// Key, requires 24 bits
///
/// default is PKCS7
/// Decrypted byte array
private static byte[] DESDecrypt(byte[] data, string key, CipherMode cipherMode, string vector = "", PaddingMode paddingMode = PaddingMode.PKCS7)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 24, nameof(key));
byte[] encryptedBytes = data;
byte[] bKey = new byte[24];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
using (MemoryStream Memory = new MemoryStream(encryptedBytes))
{
using (TripleDES des = TripleDES.Create())
{
des.Mode = cipherMode;
des.Padding = paddingMode;
des.Key = bKey;
if (cipherMode == CipherMode.CBC)
{
byte[] bVector = new byte[8];
Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(bVector.Length)), bVector, bVector.Length);
des.IV = bVector;
}
using (CryptoStream cryptoStream = new CryptoStream(Memory, des.CreateDecryptor(), CryptoStreamMode.Read))
{
try
{
byte[] tmp = new byte[encryptedBytes.Length];
int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length);
byte[] ret = new byte[len];
Array.Copy(tmp, 0, ret, 0, len);
return ret;
}
catch
{
return null;
}
}
}
}
}
#region DES加密&解密
public static void DES_Encrypt_Decrypt_Test()
{
var srcString = "TEST DES Encrypt Decrypt";
string key = EncryptProvider.CreateDesKey();
string iv = EncryptProvider.CreateDesIv();
var srsDatas = Encoding.UTF8.GetBytes(srcString);
var encrypted = EncryptProvider.DESEncrypt(srsDatas, key, iv);
Console.WriteLine("DES加密结果:" + encrypted);
Console.WriteLine("\r\n");
var decrypted = EncryptProvider.DESDecrypt(encrypted, key, iv);
var decryptedStr = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("DES解密结果:" + decryptedStr);
}
#endregion
///
/// AES encrypt ( no IV)
///
/// Raw data
/// Key, requires 32 bits
/// Encrypted string
public static string AESEncrypt(string data, string key)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 32, nameof(key));
using (MemoryStream memory = new MemoryStream())
{
using (Aes aes = Aes.Create())
{
byte[] plainBytes = Encoding.UTF8.GetBytes(data);
byte[] bKey = new byte[32];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;
aes.Key = bKey;
using (CryptoStream cryptoStream = new CryptoStream(memory, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
try
{
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memory.ToArray());
}
catch (Exception ex)
{
return null;
}
}
}
}
}
///
/// AES decrypt( no IV)
///
/// Encrypted data
/// Key, requires 32 bits
/// Decrypted string
public static string AESDecrypt(string data, string key)
{
Check.Argument.IsNotEmpty(data, nameof(data));
Check.Argument.IsNotEmpty(key, nameof(key));
Check.Argument.IsEqualLength(key.Length, 32, nameof(key));
byte[] encryptedBytes = Convert.FromBase64String(data);
byte[] bKey = new byte[32];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
try
{
byte[] decryptedData = null; // decrypted data
using (MemoryStream memory = new MemoryStream(encryptedBytes))
{
using (Aes aes = Aes.Create())
{
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;
aes.Key = bKey;
using (CryptoStream decryptor = new CryptoStream(memory, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (MemoryStream tempMemory = new MemoryStream())
{
byte[] buffer = new byte[1024];
Int32 readBytes = 0;
while ((readBytes = decryptor.Read(buffer, 0, buffer.Length)) > 0)
{
tempMemory.Write(buffer, 0, readBytes);
}
decryptedData = tempMemory.ToArray();
return Encoding.UTF8.GetString(decryptedData);
}
}
}
}
}
catch
{
return null;
}
}
#region AES加密&解密
public static void Aes_Encrypt_Decrypt_Test()
{
var aesKey = EncryptProvider.CreateAesKey();
var key = aesKey.Key;
var srcString = "追逐时光者";
var encrypted = EncryptProvider.AESEncrypt(srcString, key);
Console.WriteLine("AES加密结果:" + encrypted);
Console.WriteLine("\r\n");
var decrypted = EncryptProvider.AESDecrypt(encrypted, key);
Console.WriteLine("AES解密结果:" + decrypted);
}
#endregion
更多项目实用功能和特性欢迎前往项目开源地址查看,别忘了给项目一个Star支持。
GitHub - myloveCc/NETCore.Encrypt: NETCore encrypt and decrypt tool,Include aes,des,rsa,md5,sha1,sha256,sha384,sha512
该项目已收录到C#/.NET/.NET Core优秀项目和框架精选中,关注优秀项目和框架精选能让你及时了解C#、.NET和.NET Core领域的最新动态和最佳实践,提高开发工作效率和质量。坑已挖,欢迎大家踊跃提交PR推荐或自荐(让优秀的项目和框架不被埋没
)。
https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.md
欢迎加入DotNetGuide技术社区微信交流群