2019-2-20C#开发中常用加密解密方法解析

时间:2023-10-29 10:17:56

C#开发中常用加密解密方法解析

一、MD5加密算法

我想这是大家都常听过的算法,可能也用的比较多。那么什么是MD5算法呢?MD5全称是

message-digest algorithm 5【|ˈmesidʒ|-|daiˈdʒest|-|ˈælɡəriðəm|】,简单的说就是单向的加密,即是说无法根据密文推导出明文。

MD5主要用途:

1、对一段信息生成信息摘要,该摘要对该信息具有唯一性,可以作为数字签名。

2、用于验证文件的有效性(是否有丢失或损坏的数据),

3、对用户密码的加密,

4、在哈希函数中计算散列值

从上边的主要用途中我们看到,由于算法的某些不可逆特征,在加密应用上有较好的安全性。通过使用MD5加密算法,我们输入一个任意长度的字节串,都会生成一个128位的整数。所以根据这一点MD5被广泛的用作密码加密。下面我就像大家演示一下怎样进行密码加密。

先看下演示效果:

具体代码如下:

首先需要引入命名空间:

using System.Security;
using System.Security.Cryptography;
private void btnmd5_Click(object sender, EventArgs e)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] palindata = Encoding.Default.GetBytes(txtyuan.Text);//将要加密的字符串转换为字节数组
byte[] encryptdata=md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
txtjiami.Text = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
}

这里我们需要注意的是,不论是在加密的过程中,加密前要将加密字符串转为字节数组,加密后也要生成密文的字节数据,然后再转化为密文。

二、RSA加密算法

在谈RSA加密算法之前,我们需要先了解下两个专业名词,对称加密非对称加密

对称加密即:含有一个称为密钥的东西,在消息发送前使用密钥对消息进行加密,在对方收到消息之后,使用相同的密钥进行解密

非对称加密即:加密和解密使用不同的密钥的一类加密算法。这类加密算法通常有两个密钥A和B,使用密钥A加密数据得到的密文,只有密钥B可以进行解密操作(即使密钥A也无法解密),相反,使用了密钥B加密数据得到的密文,只有密钥A可以解密。这两个密钥分别称为私钥和公钥,顾名思义,私钥就是你个人保留,不能公开的密钥,而公钥则是公开给加解密操作的另一方的。根据不同用途,对数据进行加密所使用的密钥也不相同(有时用公钥加密,私钥解密;有时相反用私钥加密,公钥解密)。非对称加密的代表算法是RSA算法。

了解了这两个名词下面来讲,RSA加密算法。RSA取名来自开发他们三者的名字。RSA是目前最有影响力的公钥加密算法,多用于数据加密和数字签名。虽然有这么大的影响力,但是同时它也有一些弊端,它产生密钥很麻烦,受到素数产生技术的限制,因而难以做到一次一密,分组长度太大等。

下面通过示例演示使用RSA加密、解密,引用名称空间System.Security.Cryptography;

//加密
private string Encryption(string express)
{
CspParameters param = new CspParameters();
param.KeyContainerName = "oa_erp_dowork";//密匙容器的名称,保持加密解密一致才能解密成功
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
{
byte[] plaindata = Encoding.Default.GetBytes(express);//将要加密的字符串转换为字节数组
byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
}
} //解密
private string Decrypt(string ciphertext)
{
CspParameters param = new CspParameters();
param.KeyContainerName = "oa_erp_dowork";
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
{
byte[] encryptdata = Convert.FromBase64String(ciphertext);
byte[] decryptdata = rsa.Decrypt(encryptdata, false);
return Encoding.Default.GetString(decryptdata);
}
}

  

下面我再通过一个示例向大家演示,通过使用RSA加密算法产出公匙和私匙

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
using (StreamWriter sw = new StreamWriter(Server.MapPath("PublicKey.xml")))//产生公匙
{
sw.WriteLine(rsa.ToXmlString(false));
}
using (StreamWriter sw = new StreamWriter(Server.MapPath("PrivateKey.xml")))//产生私匙(也包含私匙)
{
sw.WriteLine(rsa.ToXmlString(true));
}

  

三、DES加密

DES加密:使用一个 56 位的密钥以及附加的 8 位奇偶校验位,产生最大 64 位的分组大小。这是一个迭代的分组密码,使用称为 Feistel 的技术,其中将加密的文本块分成两半。使用子密钥对其中一半应用循环功能,然后将输出与另一半进行“异或”运算;接着交换这两半,这一过程会继续下去,但最后一个循环不交换。DES 使用 16 个循环,使用异或,置换,代换,移位操作四种基本运算。额专业术语就看看得了,下面直接给大家演示一个小demo,以帮助大家的理解。

先定义一个全局的字节数组和实例化一个全局的DESCryptoServiceProvider对象

byte[] buffer;

DESCryptoServiceProvider DesCSP = new DESCryptoServiceProvider();

加密:

private void button2_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();//先创建 一个内存流
CryptoStream cryStream = new CryptoStream(ms, DesCSP.CreateEncryptor(), CryptoStreamMode.Write);//将内存流连接到加密转换流
StreamWriter sw = new StreamWriter(cryStream);
sw.WriteLine(txtyuan.Text);//将要加密的字符串写入加密转换流
sw.Close();
cryStream.Close();
buffer = ms.ToArray();//将加密后的流转换为字节数组
txtjiami.Text =Convert.ToBase64String(buffer);//将加密后的字节数组转换为字符串
} 解密: private void button1_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream(buffer);//将加密后的字节数据加入内存流中
CryptoStream cryStream = new CryptoStream(ms, DesCSP.CreateDecryptor(), CryptoStreamMode.Read);//内存流连接到解密流中
StreamReader sr = new StreamReader(cryStream);
txthjiemi.Text = sr.ReadLine();//将解密流读取为字符串
sr.Close();
cryStream.Close();
ms.Close();
}

此外还有AES加密算法,但是AES加密是一个新的可以用于保护电子数据的加密算法。其产生的密码是迭代对称的分组密码,代加密使用一个循环结构,在该循环中重复置换和替换输入数据。因为用的不是很多,在这里就不再做具体的演示了。

 //SHA-1算法
string password =
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text,
"SHA1");
//MD5算法
string password1 =
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text,
"MD5"); 加密后生成不可逆密文保存到数据库中。用户登录时用加密计算后的密文与数据库中的密码密文比较。一致则通过验证,不一致则返回登录错误。
这种加密算法是不可逆的,所以除了用户自己,其他人无法得知用户的真实密码内容。 SHA-1算法和MD5算法的区别:
SHA-1比MD5多32位密文,所以更安全。由于同样的原因,MD5比SHA-1的运算速度更快。 加密算法总汇
方法一: //须添加对System.Web的引用
using System.Web.Security; ... /// <summary>
/// SHA1加密字符串
///
</summary>
/// <param name="source">源字符串</param> /// <returns>加密后的字符串</returns>
public string
SHA1(string source)
{
return
FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1"); } /// <summary>
/// MD5加密字符串
///
</summary>
/// <param name="source">源字符串</param> /// <returns>加密后的字符串</returns>
public string
MD5(string source)
{
return
FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");; } 方法二(可逆加密解密):
using System.Security.Cryptography; ... public string Encode(string data)
{ byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new
DESCryptoServiceProvider();
int i = cryptoProvider.KeySize; MemoryStream ms = new MemoryStream();
CryptoStream cst =
new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV),
CryptoStreamMode.Write); StreamWriter sw = new
StreamWriter(cst);
sw.Write(data);
sw.Flush(); cst.FlushFinalBlock();
sw.Flush();
return
Convert.ToBase64String(ms.GetBuffer(), , (int)ms.Length); } public string Decode(string data)
{
byte[]
byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[]
byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); byte[] byEnc;
try
{
byEnc =
Convert.FromBase64String(data);
}
catch
{ return null;
} DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(byEnc);
CryptoStream
cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV),
CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst); return sr.ReadToEnd();
} 方法三(MD5不可逆):
using
System.Security.Cryptography; ... //MD5不可逆加密 //32位加密 public string GetMD5_32(string s,
string _input_charset)
{
MD5 md5 = new
MD5CryptoServiceProvider();
byte[] t =
md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s)); StringBuilder sb = new StringBuilder();
for (int i = ; i <
t.Length; i++)
{ sb.Append(t[i].ToString("x").PadLeft(, ''));
}
return
sb.ToString();
} //16位加密
public static string
GetMd5_16(string ConvertString)
{
MD5CryptoServiceProvider
md5 = new MD5CryptoServiceProvider();
string t2 =
BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)),
, );
t2 = t2.Replace("-", "");
return t2; } 方法四(对称加密):
using System.IO;
using
System.Security.Cryptography; ... private
SymmetricAlgorithm mobjCryptoService;
private string Key;
///
<summary>
/// 对称加密类的构造函数
/// </summary> public SymmetricMethod()
{
mobjCryptoService = new
RijndaelManaged();
Key =
"Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7"; }
/// <summary>
/// 获得密钥
///
</summary>
/// <returns>密钥</returns> private byte[] GetLegalKey()
{
string sTemp = Key; mobjCryptoService.GenerateKey();
byte[] bytTemp =
mobjCryptoService.Key;
int KeyLength = bytTemp.Length; if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(,
KeyLength);
else if (sTemp.Length < KeyLength) sTemp = sTemp.PadRight(KeyLength, ' ');
return
ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary> /// 获得初始向量IV
/// </summary>
///
<returns>初试向量IV</returns>
private byte[] GetLegalIV() {
string sTemp =
"E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; mobjCryptoService.GenerateIV();
byte[] bytTemp =
mobjCryptoService.IV;
int IVLength = bytTemp.Length;
if
(sTemp.Length > IVLength)
sTemp = sTemp.Substring(,
IVLength);
else if (sTemp.Length < IVLength) sTemp = sTemp.PadRight(IVLength, ' ');
return
ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary> /// 加密方法
/// </summary>
/// <param
name="Source">待加密的串</param>
///
<returns>经过加密的串</returns>
public string Encrypto(string
Source)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); MemoryStream ms = new MemoryStream(); mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV =
GetLegalIV();
ICryptoTransform encrypto =
mobjCryptoService.CreateEncryptor();
CryptoStream cs = new
CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn,
, bytIn.Length);
cs.FlushFinalBlock();
ms.Close(); byte[] bytOut = ms.ToArray();
return
Convert.ToBase64String(bytOut);
}
/// <summary> /// 解密方法
/// </summary>
/// <param
name="Source">待解密的串</param>
///
<returns>经过解密的串</returns>
public string Decrypto(string
Source)
{
byte[] bytIn = Convert.FromBase64String(Source); MemoryStream ms = new MemoryStream(bytIn, , bytIn.Length); mobjCryptoService.Key = GetLegalKey(); mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto =
mobjCryptoService.CreateDecryptor();
CryptoStream cs = new
CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr =
new StreamReader(cs);
return sr.ReadToEnd(); } 方法五:
using System.IO;
using
System.Security.Cryptography;
using System.Text; ... //默认密钥向量
private static byte[] Keys = { 0x12, 0x34,
0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <summary>
///
DES加密字符串
/// </summary>
/// <param
name="encryptString">待加密的字符串</param>
/// <param
name="encryptKey">加密密钥,要求为8位</param>
///
<returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string
EncryptDES(string encryptString, string encryptKey)
{ try
{
byte[] rgbKey =
Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
byte[] rgbIV
= Keys;
byte[] inputByteArray =
Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider
dCSP = new DESCryptoServiceProvider();
MemoryStream mStream =
new MemoryStream();
CryptoStream cStream = new
CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV),
CryptoStreamMode.Write);
cStream.Write(inputByteArray, ,
inputByteArray.Length);
cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray());
} catch
{
return encryptString; }
} /// <summary>
/// DES解密字符串 /// </summary>
/// <param
name="decryptString">待解密的字符串</param>
/// <param
name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
///
<returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string
DecryptDES(string decryptString, string decryptKey)
{ try
{
byte[] rgbKey =
Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey,
rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray,
, inputByteArray.Length);
cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray());
} catch
{
return decryptString; }
} 方法六(文件加密):
using System.IO;
using
System.Security.Cryptography;
using System.Text; ... //加密文件
private static void EncryptData(String inName,
String outName, byte[] desKey, byte[] desIV)
{
//Create the
file streams to handle the input and output files.
FileStream fin =
new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream
fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(); //Create variables to help
with read and write.
byte[] bin = new byte[]; //This is
intermediate storage for the encryption.
long rdlen =
; //This is the total number of bytes written.
long
totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be
written at a time. DES des = new
DESCryptoServiceProvider();
CryptoStream encStream = new
CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the
output file.
while (rdlen < totlen)
{ len = fin.Read(bin, , );
encStream.Write(bin, , len); rdlen = rdlen + len;
} encStream.Close();
fout.Close();
fin.Close();
} //解密文件
private static void DecryptData(String inName,
String outName, byte[] desKey, byte[] desIV)
{
//Create the
file streams to handle the input and output files.
FileStream fin =
new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream
fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(); //Create variables to help
with read and write.
byte[] bin = new byte[]; //This is
intermediate storage for the encryption.
long rdlen =
; //This is the total number of bytes written.
long
totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be
written at a time. DES des = new
DESCryptoServiceProvider();
CryptoStream encStream = new
CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the
output file.
while (rdlen < totlen)
{ len = fin.Read(bin, , );
encStream.Write(bin, , len); rdlen = rdlen + len;
} encStream.Close();
fout.Close();
fin.Close(); } using System;
using
System.Security.Cryptography;//这个是处理文字编码的前提
using System.Text;
using
System.IO;
/// <summary>
/// DES加密方法
/// </summary>
///
<param name="strPlain">明文</param>
/// <param
name="strDESKey">密钥</param>
/// <param
name="strDESIV">向量</param>
///
<returns>密文</returns>
public string DESEncrypt(string
strPlain,string strDESKey,string strDESIV)
{
//把密钥转换成字节数组
byte[]
bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
//把向量转换成字节数组
byte[]
bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
//声明1个新的DES对象
DESCryptoServiceProvider
desEncrypt=new DESCryptoServiceProvider();
//开辟一块内存流
MemoryStream
msEncrypt=new MemoryStream();
//把内存流对象包装成加密流对象
CryptoStream
csEncrypt=new
CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write);
//把加密流对象包装成写入流对象
StreamWriter
swEncrypt=new
StreamWriter(csEncrypt);
//写入流对象写入明文
swEncrypt.WriteLine(strPlain);
//写入流关闭
swEncrypt.Close();
//加密流关闭
csEncrypt.Close();
//把内存流转换成字节数组,内存流现在已经是密文了
byte[]
bytesCipher=msEncrypt.ToArray();
//内存流关闭
msEncrypt.Close();
//把密文字节数组转换为字符串,并返回
return
UnicodeEncoding.Unicode.GetString(bytesCipher);
} ///
<summary>
/// DES解密方法
/// </summary>
/// <param
name="strCipher">密文</param>
/// <param
name="strDESKey">密钥</param>
/// <param
name="strDESIV">向量</param>
///
<returns>明文</returns>
public string DESDecrypt(string
strCipher,string strDESKey,string strDESIV)
{
//把密钥转换成字节数组
byte[]
bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
//把向量转换成字节数组
byte[]
bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
//把密文转换成字节数组
byte[]
bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher);
//声明1个新的DES对象
DESCryptoServiceProvider
desDecrypt=new
DESCryptoServiceProvider();
//开辟一块内存流,并存放密文字节数组
MemoryStream
msDecrypt=new MemoryStream(bytesCipher);
//把内存流对象包装成解密流对象
CryptoStream
csDecrypt=new
CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read);
//把解密流对象包装成读出流对象
StreamReader
srDecrypt=new StreamReader(csDecrypt);
//明文=读出流的读出内容
string
strPlainText=srDecrypt.ReadLine();
//读出流关闭
srDecrypt.Close();
//解密流关闭
csDecrypt.Close();
//内存流关闭
msDecrypt.Close();
//返回明文
return
strPlainText;
}

加密代码汇总