Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了
Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架
Asp.Net Core 2.0 项目实战(3)NCMVC角色权限管理前端UI预览及下载
Asp.Net Core 2.0 项目实战(4)ADO.NET操作数据库封装、 EF Core操作及实例
Asp.Net Core 2.0 项目实战(5)Memcached踩坑,基于EnyimMemcachedCore整理MemcachedHelper帮助类。
Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例
Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密
Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类
Asp.Net Core 2.0 项目实战(9) 日志记录,基于Nlog或Microsoft.Extensions.Logging的实现及调用实例
Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级
本文目录
1. 摘要
2. MD5加密封装3. AES的加密、解密
4. DES加密/解密
5. 总结
1. 摘要
C#中常用的一些加密和解密方案,如:md5加密、RSA加密与解密和DES加密等,Asp.Net Core 2.0下该如何调整与使用我们以前常用的解加密算法类呢,下面是我整理的MD5加密、AES&DES对称加解密、Encrypt&Decrypt加解密完整实例。希望能给大家提供一些参考和帮助。
2. MD5加密封装
MD5常用加密FormsAuthentication.HashPasswordForStoringInConfigFile在Net Freamwork4.5以后就不在支持,下面整理了32位或16位下的几个方法,以及不同写法,最后一个由从老版本迁移过来,后续淘汰不用。
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text; namespace NC.Common
{
/// <summary>
/// 此类获取md5加密值均为大写,如果要获取小写:MD5Comm.Get32MD5One(xx).ToLower();或完善此类。
/// </summary>
public class MD5Comm
{
#region --Expired code--
///// <summary>
///// MD5加密
///// </summary>
//public string Md5(string txt)
//{
// //return FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");//此方法nf4.5后不再支持
//}
//public string Md5Pass(string pwd)
//{
// return Md5(pwd + "Jiahao");
//}
#endregion /// <summary>
/// 此代码示例通过创建哈希字符串适用于任何 MD5 哈希函数 (在任何平台) 上创建 32 个字符的十六进制格式哈希字符串
/// 官网案例改编
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string Get32MD5One(string source)
{
using (MD5 md5Hash = MD5.Create())
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
StringBuilder sBuilder = new StringBuilder();
for (int i = ; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
} string hash = sBuilder.ToString();
return hash.ToUpper();
}
}
/// <summary>
/// 获取16位md5加密
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string Get16MD5One(string source)
{
using (MD5 md5Hash = MD5.Create())
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
//转换成字符串,并取9到25位
string sBuilder = BitConverter.ToString(data, , );
//BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
sBuilder = sBuilder.Replace("-", "");
return sBuilder.ToString().ToUpper();
}
}
//// <summary>
/// </summary>
/// <param name="strSource">需要加密的明文</param>
/// <returns>返回32位加密结果,该结果取32位加密结果的第9位到25位</returns>
public static string Get32MD5Two(string source)
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
//获取密文字节数组
byte[] bytResult = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(source));
//转换成字符串,32位
string strResult = BitConverter.ToString(bytResult);
//BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
strResult = strResult.Replace("-", "");
return strResult.ToUpper();
}
//// <summary>
/// </summary>
/// <param name="strSource">需要加密的明文</param>
/// <returns>返回16位加密结果,该结果取32位加密结果的第9位到25位</returns>
public static string Get16MD5Two(string source)
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
//获取密文字节数组
byte[] bytResult = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(source));
//转换成字符串,并取9到25位
string strResult = BitConverter.ToString(bytResult, , );
//BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
strResult = strResult.Replace("-", "");
return strResult.ToUpper();
}
/// <summary>
/// 自定义MD5函数,32位,从老版本迁移过来,后续淘汰不用。与Get32MD5One重复
/// </summary>
public static string Get32MD5Old(string str)
{
byte[] b = Encoding.UTF8.GetBytes(str);
b = new MD5CryptoServiceProvider().ComputeHash(b);
string ret = "";
for (int i = ; i < b.Length; i++)
ret += b[i].ToString("x").PadLeft(, ''); return ret.ToUpper();
}
}
}
3. AES的加密、解密
上面我们介绍了MD5加密封装,接下来分享给大家供大家参考一下AES加密、解密,AES要注意的是32位密匙。AES 加密解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography; namespace NC.Common
{
/// <summary>
/// 加密
/// </summary>
public class AES
{
//默认密钥向量
private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F }; public static string Encode(string encryptString, string encryptKey)
{
encryptKey = GetSubString(encryptKey,, , "");
encryptKey = encryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor(); byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, , inputData.Length); return Convert.ToBase64String(encryptedData);
} public static string Decode(string decryptString, string decryptKey)
{
try
{
decryptKey = GetSubString(decryptKey,, , "");
decryptKey = decryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor(); byte[] inputData = Convert.FromBase64String(decryptString);
byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, , inputData.Length); return Encoding.UTF8.GetString(decryptedData);
}
catch
{
return "";
} } public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
{
string myResult = p_SrcString; Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
foreach (char c in Encoding.UTF8.GetChars(bComments))
{ //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
{
//if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
//当截取的起始位置超出字段串长度时
if (p_StartIndex >= p_SrcString.Length)
return "";
else
return p_SrcString.Substring(p_StartIndex,
((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
}
} if (p_Length >= )
{
byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString); //当字符串长度大于起始位置
if (bsSrcString.Length > p_StartIndex)
{
int p_EndIndex = bsSrcString.Length; //当要截取的长度在字符串的有效长度范围内
if (bsSrcString.Length > (p_StartIndex + p_Length))
{
p_EndIndex = p_Length + p_StartIndex;
}
else
{ //当不在有效范围内时,只取到字符串的结尾 p_Length = bsSrcString.Length - p_StartIndex;
p_TailString = "";
} int nRealLength = p_Length;
int[] anResultFlag = new int[p_Length];
byte[] bsResult = null; int nFlag = ;
for (int i = p_StartIndex; i < p_EndIndex; i++)
{
if (bsSrcString[i] > )
{
nFlag++;
if (nFlag == )
nFlag = ;
}
else
nFlag = ; anResultFlag[i] = nFlag;
} if ((bsSrcString[p_EndIndex - ] > ) && (anResultFlag[p_Length - ] == ))
nRealLength = p_Length + ; bsResult = new byte[nRealLength]; Array.Copy(bsSrcString, p_StartIndex, bsResult, , nRealLength); myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + p_TailString;
}
} return myResult;
} }
}
4. DES加密/解密
除了MD5加密、AES加密/解密之外还经常用到DES加密、解密,注意的是DES的密匙是8位的,这里有家婆MD5加密一起使用。
using System;
using System.Security.Cryptography;
using System.Text; namespace NC.Common
{
/// <summary>
/// DES加密/解密类。
/// </summary>
public class DESEncrypt
{ #region --加密-- /// <summary>
/// 加密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Encrypt(string Text)
{
return Encrypt(Text, "ncmvc");
}
/// <summary>
/// 加密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string Text, string sKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
string md5SKey = MD5Comm.Get32MD5One(sKey).Substring(, );
des.Key = ASCIIEncoding.ASCII.GetBytes(md5SKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5SKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
catch { return "error"; }
} #endregion #region --解密-- /// <summary>
/// 解密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Decrypt(string Text)
{
return Decrypt(Text, "ncmvc");
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string Text, string sKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / ;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = ; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * , ), );
inputByteArray[x] = (byte)i;
}
string md5SKey = MD5Comm.Get32MD5One(sKey).Substring(, );
des.Key = ASCIIEncoding.ASCII.GetBytes(md5SKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5SKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
catch { return "error"; }
} #endregion }
}
5. 总结
Asp.Net Core 2.0下加解密封装类分享给大家,供参考!文中有不合理之处望告知,欢迎批评指正。以前做项目常用的几种加密方式,在Net Core2.0下经过重新整理,好的延续,不合理方法弃用。相关案例使用方法欢迎大家继续关注《Asp.Net Core 2.0项目实战》系列。