本文是利用一个简单的小例子,简述C#中和加密术有关的内容,仅供学习参考用。
概述
随着信息技术的发展,计算机网络为信息的获取、传输、处理、利用与共享提供了一个高效、快捷、安全的通信环境和传输通道,网络信息安全也变得越来越重要。信息安全主要包括两个方面的内容:信息存储安全和信息传输安全。保证网络中信息安全的主要技术是数据的加密与解密。如下图示,说明了加密与解密的过程。
公式算法表示如下:
加密公式:c=Eke(m) (11.1) 解密公式:m=Dkd(c) (11.2)其中m代表明文,c代表密文,E是加密算法,D是解密算法,参数ke称为加密密钥,参数kd称为解密密钥
涉及知识点
- HASH算法 :散列函数是现代密码系统的基础。这些函数将任意长度的二进制字符串映射为固定长度的二进制字符串(称为散列值)
- 对称加密算法:指对信息的加密和解密都使用相同的密钥。
- 非对称加密算法:非对称加密算法对信息的加密与解密使用不同的密钥,用来加密的密钥是可以公开的,用来解密的密钥需要保密
- 数字签名术:数字签名技术结合散列算法和非对称加密技术来进行篡改检测和解决相关的身份验证问题。这就像在现实生活中用亲笔签名来保证文件或资料的真实性一样。
散列算法
散列算法主要有MD5【Message Digest Algorithm】,RIPEMD160【RACE Integrity Primitives Evaluation Message Digest】和SHA【Secure Hash Algorithm】,SHA又分为SHA1,SHA256,SHA384,SHA512,【散列算法不可逆,是单向操作】如下如所示:
关于散列算法,效果图如下:
HASH算法核心代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace DemoCrtpto
{
/// <summary>
/// 信息摘要帮助类
/// </summary>
public class HashHelper
{
#region 信息摘要 /// <summary>
/// MD5信息摘要
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string GetInfoByMd5(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.MD5);
return Encrypto(hash, source);
} public static string GetInfoBySHA1(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.SHA1);
return Encrypto(hash, source);
} public static string GetInfoBySHA256(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.SHA256);
return Encrypto(hash, source);
} public static string GetInfoBySHA384(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.SHA384);
return Encrypto(hash, source);
} public static string GetInfoBySHA512(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.SHA512);
return Encrypto(hash, source);
} public static string GetInfoByRipeMD(string source)
{
HashAlgorithm hash = getHashAlgorithm(HashType.RIPEMD);
return Encrypto(hash, source);
} #endregion /// <summary>
/// 根据类型获取摘要算法名称
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private static HashAlgorithm getHashAlgorithm(HashType t) {
HashAlgorithm hash;
switch (t) {
case HashType.MD5:
hash = new MD5CryptoServiceProvider();
break;
case HashType.SHA1:
hash = new SHA1Managed();
break;
case HashType.SHA256:
hash = new SHA256Managed();
break;
case HashType.SHA384:
hash = new SHA384Managed();
break;
case HashType.SHA512:
hash = new SHA512Managed();
break;
case HashType.RIPEMD:
hash = new RIPEMD160Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
return hash;
} /// <summary>
/// 加密
/// </summary>
/// <param name="hash"></param>
/// <param name="source"></param>
/// <returns></returns>
private static string Encrypto(HashAlgorithm hash, string source) {
string dest = string.Empty;
try
{
byte[] btSource = Encoding.Default.GetBytes(source);
byte[] btDest = hash.ComputeHash(btSource);
dest = Convert.ToBase64String(btDest, , btDest.Length);
}
catch (Exception ex)
{
throw ex;
}
return dest;
}
} /// <summary>
/// 信息摘要类型
/// </summary>
public enum HashType {
MD5=,
SHA1=,
SHA256=,
SHA384=,
SHA512=,
RIPEMD=
}
}
对称加密算法
关于对称加密算法,主要有DES【Data Encryption Standard / 数据加密标准】 , 3DES【三重数据加密算法】,RC2【Rivest Cipher】,Rijndael【又称AES:Advanced Encryption Standard】。如下图所示:
关于对称加密算法,效果图如下:
对称加密算法的核心代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace DemoCrtpto
{
/// <summary>
/// 对称加密算法帮助类
/// </summary>
public class SymHelper
{
#region DES加密 /// <summary>
/// DES加密
/// </summary>
/// <param name="source"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetEnCryptoInfoByDES(string source, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.DES);
return Encrypto(sym, source, key, iv); } /// <summary>
/// DES解密
/// </summary>
/// <param name="dest"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetDeCryptoInfoByDES(string dest, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.DES);
return Decrypto(sym, dest, key, iv); } #endregion #region RC2加密与解密 /// <summary>
/// RC2加密
/// </summary>
/// <param name="source"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetEnCryptoInfoByRC2(string source, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.RC2);
return Encrypto(sym, source, key, iv); } /// <summary>
/// RC2解密
/// </summary>
/// <param name="dest"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetDeCryptoInfoByRC2(string dest, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.RC2);
return Decrypto(sym, dest, key, iv); } #endregion #region 3DES加密与解密 /// <summary>
/// 3DES加密
/// </summary>
/// <param name="source"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetEnCryptoInfoBy3DES(string source, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.TripleDES);
return Encrypto(sym, source, key, iv); } /// <summary>
/// 3DES解密
/// </summary>
/// <param name="dest"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetDeCryptoInfoBy3DES(string dest, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.TripleDES);
return Decrypto(sym, dest, key, iv); } #endregion #region Rijndael加密与解密 /// <summary>
/// Rijndael加密
/// </summary>
/// <param name="source"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetEnCryptoInfoByRijndael(string source, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.Rijndael);
return Encrypto(sym, source, key, iv); } /// <summary>
/// Rijndael解密
/// </summary>
/// <param name="dest"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string GetDeCryptoInfoByRijndael(string dest, string key, string iv)
{
SymmetricAlgorithm sym = getSymmetricAlgorithm(SymType.Rijndael);
return Decrypto(sym, dest, key, iv);
} #endregion public static SymmetricAlgorithm getSymmetricAlgorithm(SymType t)
{
SymmetricAlgorithm sym;
switch (t)
{
case SymType.DES:
sym = new DESCryptoServiceProvider();
break;
case SymType.RC2:
sym = new RC2CryptoServiceProvider();
break;
case SymType.TripleDES:
sym = new TripleDESCryptoServiceProvider();
break;
case SymType.Rijndael:
sym = new RijndaelManaged();
break;
default:
sym = new DESCryptoServiceProvider();
break;
}
return sym;
} /// <summary>
/// 加密
/// </summary>
/// <param name="sym"></param>
/// <param name="source"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
private static string Encrypto(SymmetricAlgorithm sym, string source, string key, string iv)
{
string dest = string.Empty;
try
{
byte[] btnSource = Encoding.Default.GetBytes(source);
//1.创建对称加密算法实例创建对称加密算法实例
sym.Mode = CipherMode.CBC;
int keyLen = sym.LegalKeySizes[].MaxSize / ;
int ivLen = sym.BlockSize / ;
if (key.Length < keyLen)
{
key = key.PadRight(keyLen, '');
}
if (iv.Length < ivLen)
{
iv = iv.PadRight(ivLen, '');
}
//使用 PBKDF1 算法的扩展从密码派生密钥
PasswordDeriveBytes pkey = new PasswordDeriveBytes(key,
ASCIIEncoding.ASCII.GetBytes("")); //2.设置初始化参数,包括密钥和初始化向量等
sym.Key = pkey.GetBytes(key.Length); //Encoding.Default.GetBytes(key);
sym.IV = Encoding.Default.GetBytes(iv);
//3.使用CreateEncryptor方法创建加密实例
ICryptoTransform trans = sym.CreateEncryptor();
//4.创建加密流
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Write);
//5.利用加密流进行数据加密
cs.Write(btnSource, , btnSource.Length);
cs.FlushFinalBlock();
//6.返回密文
byte[] cryptoByte = ms.ToArray();
dest = Convert.ToBase64String(cryptoByte, , cryptoByte.GetLength());
}
catch (Exception ex)
{
throw ex;
}
return dest;
} /// <summary>
/// 解密
/// </summary>
/// <param name="sym"></param>
/// <param name="dest"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
private static string Decrypto(SymmetricAlgorithm sym, string dest, string key, string iv)
{
string source = string.Empty;
try
{
byte[] btnDest = Convert.FromBase64String(dest);
//1.创建对称加密算法实例创建对称加密算法实例
sym.Mode = CipherMode.CBC;
int keyLen = sym.LegalKeySizes[].MaxSize / ;
int ivLen = sym.BlockSize / ;
if (key.Length < keyLen)
{
key = key.PadRight(keyLen, '');
}
if (iv.Length < ivLen)
{
iv = iv.PadRight(ivLen, '');
}
//使用 PBKDF1 算法的扩展从密码派生密钥
PasswordDeriveBytes pkey = new PasswordDeriveBytes(key,
ASCIIEncoding.ASCII.GetBytes(""));
//2.设置初始化参数,包括密钥和初始化向量等
sym.Key = pkey.GetBytes(key.Length); //Encoding.Default.GetBytes(key);
sym.IV = Encoding.Default.GetBytes(iv);
//3.使用CreateDecryptor方法创建解密实例
ICryptoTransform trans = sym.CreateDecryptor();
//4.创建解密流
MemoryStream ms = new MemoryStream(btnDest, , btnDest.Length);
CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Read); //5.返回明文
StreamReader sr = new StreamReader(cs);
source = sr.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
return source;
}
} /// <summary>
/// 加密类型
/// </summary>
public enum SymType {
DES=,
RC2=,
TripleDES=,
Rijndael=
}
}
非对称加密算法和数字签名
非对称加密算法,主要要RSA【RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。1987年7月首次在美国公布,当时他们三人都在麻省理工学院工作实习。RSA就是他们三人姓氏开头字母拼在一起组成的。】【非对称加密算法对长度有一定的限制,适用于少量数据】
关于非对称加密算法,效果图如下:
关于数字签名,效果图如下:
关于非对称加密术和数字签名,核心代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace DemoCrtpto
{
/// <summary>
/// 非对称加密算法帮助类
/// </summary>
public class AsymHelper
{ } public class DSAHelper { private static string keyContainerName = "star"; private static string m_PriKey = string.Empty; private static string m_PubKey = string.Empty; public static string PriKey
{
get
{
return m_PriKey;
} set
{
m_PriKey = value;
}
} public static string PubKey
{
get
{
return m_PubKey;
} set
{
m_PubKey = value;
}
} public static void generateKey()
{
CspParameters m_CspParameters;
m_CspParameters = new CspParameters();
m_CspParameters.KeyContainerName = keyContainerName;
DSACryptoServiceProvider asym = new DSACryptoServiceProvider();
m_PriKey = asym.ToXmlString(true);
m_PubKey = asym.ToXmlString(false);
asym.PersistKeyInCsp = false;
asym.Clear();
} public static string Encrypto(string source) {
if (string.IsNullOrEmpty(m_PubKey) && string.IsNullOrEmpty(m_PriKey))
{
generateKey();
}
return getEncryptoInfoByDSA(source);
} /// <summary>
/// 创建数字签名
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string getEncryptoInfoByDSA(string source)
{
string dest = string.Empty;
string ss = HashHelper.GetInfoBySHA1(source);
byte[] btSource = Convert.FromBase64String(ss);
DSACryptoServiceProvider asym = new DSACryptoServiceProvider();
asym.FromXmlString(m_PriKey);
DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(asym);
dsaFormatter.SetHashAlgorithm("SHA1");
byte[] btDest = dsaFormatter.CreateSignature(btSource);
dest = Convert.ToBase64String(btDest);
return dest;
} /// <summary>
/// 验证数字签名
/// </summary>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <returns></returns>
public static bool verifyInfo(string source, string dest)
{
string ss = HashHelper.GetInfoBySHA1(source);
byte[] btnSource = Convert.FromBase64String(ss);
byte[] btnDest = Convert.FromBase64String(dest);
DSACryptoServiceProvider asym = new DSACryptoServiceProvider();
asym.FromXmlString(m_PubKey);
DSASignatureDeformatter dsaFormatter = new DSASignatureDeformatter(asym);
dsaFormatter.SetHashAlgorithm("SHA1");
return dsaFormatter.VerifySignature(btnSource, btnDest);
}
} public class RSAHelper { private static string keyContainerName = "star"; private static string m_PriKey = string.Empty; private static string m_PubKey = string.Empty; public static string PriKey
{
get
{
return m_PriKey;
} set
{
m_PriKey = value;
}
} public static string PubKey
{
get
{
return m_PubKey;
} set
{
m_PubKey = value;
}
} public static string Encrypto(string source) {
if (string.IsNullOrEmpty(m_PubKey) && string.IsNullOrEmpty(m_PriKey)) {
generateKey();
}
return getEncryptoInfoByRSA(source);
} public static string Decrypto(string dest) {
if (string.IsNullOrEmpty(m_PubKey) && string.IsNullOrEmpty(m_PriKey))
{
generateKey();
}
return getDecryptoInfoByRSA(dest);
} public static void generateKey()
{
CspParameters m_CspParameters;
m_CspParameters = new CspParameters();
m_CspParameters.KeyContainerName = keyContainerName;
RSACryptoServiceProvider asym = new RSACryptoServiceProvider(m_CspParameters); m_PriKey = asym.ToXmlString(true);
m_PubKey = asym.ToXmlString(false);
asym.PersistKeyInCsp = false;
asym.Clear();
} public static string getEncryptoInfoByRSA(string source)
{
byte[] plainByte = Encoding.ASCII.GetBytes(source);
//初始化参数
RSACryptoServiceProvider asym = new RSACryptoServiceProvider();
asym.FromXmlString(m_PubKey);
int keySize = asym.KeySize / ;//非对称加密,每次的长度不能太长,否则会报异常
int bufferSize = keySize - ;
if (plainByte.Length > bufferSize) {
throw new Exception("非对称加密最多支持【"+bufferSize+"】字节,实际长度【"+plainByte.Length+"】字节。");
}
byte[] cryptoByte = asym.Encrypt(plainByte, false);
return Convert.ToBase64String(cryptoByte);
} public static string getDecryptoInfoByRSA(string dest)
{
byte[] btDest = Convert.FromBase64String(dest);
//初始化参数
RSACryptoServiceProvider asym = new RSACryptoServiceProvider();
asym.FromXmlString(m_PriKey);
int keySize = asym.KeySize / ;//非对称加密,每次的长度不能太长,否则会报异常
//int bufferSize = keySize - 11;
if (btDest.Length > keySize)
{
throw new Exception("非对称解密最多支持【" + keySize + "】字节,实际长度【" + btDest.Length + "】字节。");
}
byte[] cryptoByte = asym.Decrypt(btDest, false);
return Encoding.ASCII.GetString(cryptoByte);
}
} public enum AsymType{
DSA=,
RSA=
}
}
本文旨在抛砖引玉,希望大家可以共同探讨,如有不足之处,还请指正。