前言
在我们日常开发工作中,为了数据安全问题对数据加密、解密是必不可少的。加密方式有很多种如常见的AES,RSA,MD5,SAH1,SAH256,DES等,这时候假如我们有一个封装的对应加密解密工具类可以直接调用,那这样可以节省不少的开发时间。今天推荐一款实用的.NET Core加密解密工具类库:NETCore.Encrypt。
项目介绍
NETCore.Encrypt是.NET Core加密解密工具类库,包括AES、RSA、MD5、SHA1、DES、SHA256、SHA384、SHA512等更多功能。
项目源码
MD5加密
封装方法
#regionMD5
///
///MD5hash
///
///Thestringtobeencrypted.
///Thelengthofhashresult,defaultvalueis.
///
publicstaticstringMd5(stringsrcString,MD5Lengthlength=MD5Length.L32)
{
Check.Argument.IsNotEmpty(srcString,nameof(srcString));
stringstr_md5_out=string.Empty;
using(MD5md5=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("-","");
returnstr_md5_out;
}
}
#endregion
调用结果
publicstaticvoidMD5_Test()
{
varsrcString="追逐时光者";
varhashed=EncryptProvider.Md5(srcString);
Console.WriteLine("MD5加密结果:"+hashed);
}
RSA加密&解密
封装方法
///
///RSAencrypt
///
///publickey
///srcstring
///rsaencryptPaddingRSAEncryptionPadding.Pkcs1forlinux/macopenssl
///setkeyispemformat,defaultisfalse
///encryptedstring
publicstaticstringRSAEncrypt(stringpublicKey,stringsrcString,RSAEncryptionPaddingpadding,boolisPemKey=false)
{
Check.Argument.IsNotEmpty(publicKey,nameof(publicKey));
Check.Argument.IsNotEmpty(srcString,nameof(srcString));
Check.Argument.IsNotNull(padding,nameof(padding));
RSArsa;
if(isPemKey)
{
rsa=RsaProvider.FromPem(publicKey);
}
else
{
rsa=RSA.Create();
rsa.FromJsonString(publicKey);
}
using(rsa)
{
varmaxLength=GetMaxRsaEncryptLength(rsa,padding);
varrawBytes=Encoding.UTF8.GetBytes(srcString);
if(rawBytes.Length>maxLength)
{
thrownewOutofMaxlengthException($"'{srcString}'isoutofmaxencryptlength{maxLength}",maxLength,rsa.KeySize,padding);
}
byte[]encryptBytes=rsa.Encrypt(rawBytes,padding);
returnencryptBytes.ToHexString();
}
}
///
///RSAdecrypt
///
///publickey
///srcstring
///rsaencryptPaddingRSAEncryptionPadding.Pkcs1forlinux/macopenssl
///setkeyispemformat,defaultisfalse
///encryptedstring
publicstaticstringRSADecrypt(stringprivateKey,stringsrcString,RSAEncryptionPaddingpadding,boolisPemKey=false)
{
Check.Argument.IsNotEmpty(privateKey,nameof(privateKey));
Check.Argument.IsNotEmpty(srcString,nameof(srcString)服务器托管网);
Check.Argument.IsNotNull(padding,nameof(padding));
RSArsa;
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);
returnEncoding.UTF8.GetString(decryptBytes);
}
}
调用结果
#regionRsa加密&解密
publicstaticvoidRsa_Encrypt_Decrypt_Test(RsaSizesize)
{
varrsaKey=EncryptProvider.CreateRsaKey(size);
varsrcString="追逐时光者";
varencrypted=EncryptProvider.RSAEncrypt(rsaKey.PublicKey,srcString);
Console.WriteLine("RSA加密结果:"+encrypted);
Console.WriteLine("rn");
vardecrypted=EncryptProvider.RSADecrypt(rsaKey.PrivateKey,encrypted);
Console.WriteLine("RSA解密结果:"+decrypted);
}
#endregion
DES加密&解密
封装方法
///
///DESencrypt
///
///Rawdatabytearray
///Key,requires24bits
///IV,requires8bits
///Encryptedbytearray
publicstaticbyte[]DESEncrypt(byte[]data,stringkey,stringvector)
{
Check.Argument.IsNotEmpty(data,nameof(d服务器托管网ata));
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));
returnDESEncrypt(data,key,CipherMode.CBC,vector);
}
///
///DESencrypt
///
///Rawdata
///Key,requires24bits
///
///
defaultisPKCS7
///IV,requires8bits
///Encryptedbytearray
privatestaticbyte[]DESEncrypt(byte[]data,stringkey,CipherModecipherMode,stringvector="",PaddingModepaddingMode=PaddingMode.PKCS7)
{
Check.Argument.IsNotEmpty(data,nameof(data));
Check.Argument.IsNotEmpty(key,nameof(key));
Check.Argument.IsEqualLength(key.Length,24,nameof(key));
using(MemoryStreamMemory=newMemoryStream())
{
using(TripleDESdes=TripleDES.Create())
{
byte[]plainBytes=data;
byte[]bKey=newbyte[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=newbyte[8];
Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(bVector.Length)),bVector,bVector.Length);
des.IV=bVector;
}
using(CryptoStreamcryptoStream=newCryptoStream(Memory,des.CreateEncryptor(),CryptoStreamMode.Write))
{
try
{
cryptoStream.Write(plainBytes,0,plainBytes.Length);
cryptoStream.FlushFinalBlock();
returnMemory.ToArray();
}
catch(Exceptionex)
{
returnnull;
}
}
}
}
}
///
///DESencrypt
///
///Rawdatabytearray
///Key,requires24bits
///IV,requires8bits
///Encryptedbytearray
publicstaticbyte[]DESDecrypt(byte[]data,stringkey,stringvector)
{
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));
returnDESDecrypt(data,key,CipherMode.CBC,vector);
}
///
///DESdecrypt
///
///Encrypteddata
///Key,requires24bits
///
///
defaultisPKCS7
///Decryptedbytearray
privatestaticbyte[]DESDecrypt(byte[]data,stringkey,CipherModecipherMode,stringvector="",PaddingModepaddingMode=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=newbyte[24];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)),bKey,bKey.Length);
using(MemoryStreamMemory=newMemoryStream(encryptedBytes))
{
using(TripleDESdes=TripleDES.Create())
{
des.Mode=cipherMode;
des.Padding=paddingMode;
des.Key=bKey;
if(cipherMode==CipherMode.CBC)
{
byte[]bVector=newbyte[8];
Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(bVector.Length)),bVector,bVector.Length);
des.IV=bVector;
}
using(CryptoStreamcryptoStream=newCryptoStream(Memory,des.CreateDecryptor(),CryptoStreamMode.Read))
{
try
{
byte[]tmp=newbyte[encryptedBytes.Length];
intlen=cryptoStream.Read(tmp,0,encryptedBytes.Length);
byte[]ret=newbyte[len];
Array.Copy(tmp,0,ret,0,len);
returnret;
}
catch
{
returnnull;
}
}
}
}
}
调用结果
#regionDES加密&解密
publicstaticvoidDES_Encrypt_Decrypt_Test()
{
varsrcString="TESTDESEncryptDecrypt";
stringkey=EncryptProvider.CreateDesKey();
stringiv=EncryptProvider.CreateDesIv();
varsrsDatas=Encoding.UTF8.GetBytes(srcString);
varencrypted=EncryptProvider.DESEncrypt(srsDatas,key,iv);
Console.WriteLine("DES加密结果:"+encrypted);
Console.WriteLine("rn");
vardecrypted=EncryptProvider.DESDecrypt(encrypted,key,iv);
vardecryptedStr=Encoding.UTF8.GetString(decrypted);
Console.WriteLine("DES解密结果:"+decryptedStr);
}
#endregion
AES加密&解密
封装方法
///
///AESencrypt(noIV)
///
///Rawdata
///Key,requires32bits
///Encryptedstring
publicstaticstringAESEncrypt(stringdata,stringkey)
{
Check.Argument.IsNotEmpty(data,nameof(data));
Check.Argument.IsNotEmpty(key,nameof(key));
Check.Argument.IsEqualLength(key.Length,32,nameof(key));
using(MemoryStreammemory=newMemoryStream())
{
using(Aesaes=Aes.Create())
{
byte[]plainBytes=Encoding.UTF8.GetBytes(data);
byte[]bKey=newbyte[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(CryptoStreamcryptoStream=newCryptoStream(memory,aes.CreateEncryptor(),CryptoStreamMode.Write))
{
try
{
cryptoStream.Write(plainBytes,0,plainBytes.Length);
cryptoStream.FlushFinalBlock();
returnConvert.ToBase64String(memory.ToArray());
}
catch(Exceptionex)
{
returnnull;
}
}
}
}
}
///
///AESdecrypt(noIV)
///
///Encrypteddata
///Key,requires32bits
///Decryptedstring
publicstaticstringAESDecrypt(stringdata,stringkey)
{
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=newbyte[32];
Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)),bKey,bKey.Length);
try
{
byte[]decryptedData=null;//decrypteddata
using(MemoryStreammemory=newMemoryStream(encryptedBytes))
{
using(Aesaes=Aes.Create())
{
aes.Mode=CipherMode.ECB;
aes.Padding=PaddingMode.PKCS7;
aes.KeySize=256;
aes.Key=bKey;
using(CryptoStreamdecryptor=newCryptoStream(memory,aes.CreateDecryptor(),CryptoStreamMode.Read))
{
using(MemoryStreamtempMemory=newMemoryStream())
{
byte[]buffer=newbyte[1024];
Int32readBytes=0;
while((readBytes=decryptor.Read(buffer,0,buffer.Length))>0)
{
tempMemory.Write(buffer,0,readBytes);
}
decryptedData=tempMemory.ToArray();
returnEncoding.UTF8.GetString(decryptedData);
}
}
}
}
}
catch
{
returnnull;
}
}
调用结果
#regionAES加密&解密
publicstaticvoidAes_Encrypt_Decrypt_Test()
{
varaesKey=EncryptProvider.CreateAesKey();
varkey=aesKey.Key;
varsrcString="追逐时光者";
varencrypted=EncryptProvider.AESEncrypt(srcString,key);
Console.WriteLine("AES加密结果:"+encrypted);
Console.WriteLine("rn");
vardecrypted=EncryptProvider.AESDecrypt(encrypted,key);
Console.WriteLine("AES解密结果:"+decrypted);
}
#endregion
项目源码地址
更多项目实用功能和特性欢迎前往项目开源地址查看,别忘了给项目一个Star支持。
https://github.com/myloveCc/NETCore.Encrypt
优秀项目和框架精选
该项目已收录到C#/.NET/.NET Core优秀项目和框架精选中,关注优秀项目和框架精选能让你及时了解C#、.NET和.NET Core领域的最新动态和最佳实践,提高开发工作效率和质量。坑已挖,欢迎大家踊跃提交PR推荐或自荐(让优秀的项目和框架不被埋没
)。
https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.md
DotNetGuide技术社区交流群
- DotNetGuide技术社区是一个面向.NET开发者的开源技术社区,旨在为开发者们提供全面的C#/.NET/.NET Core相关学习资料、技术分享和咨询、项目推荐、招聘资讯和解决问题的平台。
- 在这个社区中,开发者们可以分享自己的技术文章、项目经验、遇到的疑难技术问题以及解决方案,并且还有机会结识志同道合的开发者。
- 我们致力于构建一个积极向上、和谐友善的.NET技术交流平台,为广大.NET开发者带来更多的价值和成长机会。
欢迎加入DotNetGuide技术社区微信交流群
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net