前言:最近项目中需要用到字符串加解密,遂研究了一波,发现密码学真的是博大精深,好多算法的设计都相当巧妙,学到了不少东西,在这里做个小小的总结,方便后续查阅。
文中关键词:
- 明文(P,Plaintext)
- 密文(C,Ciphertext)
- 密钥(K,Key)
- 加密算法(E,Encypted Algorithm)
- 解密算法(D,Decrypted Algorithm)
- 公钥(Public Key)
- 私钥(Private Key)
常见加密算法如下,本文主要介绍红框里边的5种算法以及C#代码实现

1. Base64编码
1.1 原理介绍
(1)Base64是一种基于64个可打印字符来表示二进制数据的表示方法。其索引表如下:

共包含64个可打印字符为:A-Z、a-z、0-9、+、/,另外还会有“=”或者“==”作为填充字符出现在编码中。
(2)编码规则
- 将待编码字符串每三个字节分为一组,每组24bit
- 将上边的24bit分为4组,每组6bit
- 在每组前添加两个0,每组由6bit变为8bit,总共32bit,即4byte
- 根据Base64编码对照表获取对应的编码值

上述图例中:“Man”经过Base64编码之后变为“TWFu”。
(3)字节数不足3个时

- 两个字节:2byte共16bit,按照编码规则,每6bit分为一组,则第三组缺少2bit,用0补齐,得到3个Based64编码,第四组完全没有数据则用“=”补上。因此上图“BC”经过Base64编码之后变为“QkM=”;
- 一个字节:1byte共8bit,按照编码规则,每6bit分为一组,则第二组缺少4bit,用0补齐,得到2个Based64编码,后两组完全没有数据都用“=”补上。因此上图“A”经过Base64编码之后变为“QQ==”。
1.2 C#代码
- // Base64编码
- public sealed class Base64
- {
- // Base64加密
- public static string Base64Encrypt(string plaintext)
- {
- string ciphertext = "";
- byte[] buffer = Encoding.ASCII.GetBytes(plaintext);
- ciphertext = Convert.ToBase64String(buffer);
- return ciphertext;
- }
- // Base64解密
- public static string Base64Decrypt(string ciphertext)
- {
- string plaintext = "";
- byte[] buffer = Convert.FromBase64String(ciphertext);
- plaintext = Encoding.ASCII.GetString(buffer);
- return plaintext;
- }
- }
复制代码 2. 凯撒密码
2.1 原理介绍
凯撒密码是一种很古老的加密体制,主要是通过代换来达到加密的目的。其基本思想是:通过把字母移动一定的位数来实现加密和解密。移动位数就是加密和解密的密钥。
举例说明,假设明文为“ABCD”,密钥设置为7,那么对应的密文就是“HIJK”。具体流程如下表所示:

2.2 C#代码
- // Caesar Cipher(凯撒密码)
- public sealed class Caesar
- {
- // 加密
- public static string CaesarEncrypt(string plaintext, int key)
- {
- // 字符串转换为字节数组
- byte[] origin = Encoding.ASCII.GetBytes(plaintext);
- string rst = null;
- for (int i = 0; i < origin.Length; i++)
- {
- // 获取字符ASCII码
- int asciiCode = (int)origin[i];
- // 偏移
- asciiCode += key;
- byte[] byteArray = new byte[] { (byte)asciiCode };
- // 将偏移后的数据转为字符
- ASCIIEncoding asciiEncoding = new ASCIIEncoding();
- string strCharacter = asciiEncoding.GetString(byteArray);
- // 拼接数据
- rst += strCharacter;
- }
- return rst;
- }
- // 解密
- public static string CaesarDecrypt(string ciphertext, int key)
- {
- // 字符串转换为字节数组
- byte[] origin = Encoding.ASCII.GetBytes(ciphertext);
- string rst = null;
- for (int i = 0; i < origin.Length; i++)
- {
- // 获取字符ASCII码
- int asciiCode = (int)origin[i];
- // 偏移
- asciiCode -= key;
- byte[] byteArray = new byte[] { (byte)asciiCode };
- // 将偏移后的数据转为字符
- ASCIIEncoding asciiEncoding = new ASCIIEncoding();
- string strCharacter = asciiEncoding.GetString(byteArray);
- // 拼接数据
- rst += strCharacter;
- }
- return rst;
- }
- }
复制代码 3. Vigenere密码
3.1 原理介绍
在凯撒密码中,每一个字母通过一定的偏移量(即密钥K)变成另外一个字母,而维吉尼亚密码就是由多个偏移量不同的凯撒密码组成,属于多表密码的一种。在一段时间里它曾被称为“不可破译的密码”。
维吉尼亚密码在加密和解密时,需要一个表格进行对照。表格一般为26*26的矩阵,行和列都是由26个英文字母组成。加密时,明文字母作为列,密钥字母作为行,所对应坐标上的字母即为对应的密文字母。

可以用上述表格直接查找对应的密文,也可通过取模计算的方式。用0-25代替字母A-Z,C表示密文,P表示明文,K表示密钥,维吉尼亚加密算法可表示为:

密文可表示为:

举例说明,假设明文为“I AM A CHINESE”,密钥为“CHINA”,那么密文就是“L HU N CJPVRSG”。具体过程如下表:

3.2 C#代码
- // Vigenere Cipher(维吉尼亚密码)
- public sealed class Vigenere
- {
- // 加密
- public static string VigenereEncrypt(string plaintext, string key)
- {
- string ciphertext = "";
- byte[] origin = Encoding.ASCII.GetBytes(plaintext.ToUpper());
- byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
- int length = origin.Length;
- int d = keys.Length;
- for (int i = 0; i < length; i++)
- {
- int asciiCode = (int)origin[i];
- // 加密(移位)
- asciiCode = asciiCode + (int)keys[i % d] - (int)'A';
- if (asciiCode > (int)'Z')
- {
- asciiCode -= 26;
- }
- byte[] byteArray = new byte[] { (byte)asciiCode };
- // 将偏移后的数据转为字符
- ASCIIEncoding asciiEncoding = new ASCIIEncoding();
- string strCharacter = asciiEncoding.GetString(byteArray);
- ciphertext += strCharacter;
- }
- return ciphertext;
- }
- // 解密
- public static string VigenereDecrypt(string ciphertext, string key)
- {
- string plaintext = "";
- byte[] origin = Encoding.ASCII.GetBytes(ciphertext.ToUpper());
- byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
- int length = origin.Length;
- int d = keys.Length;
- for (int i = 0; i < length; i++)
- {
- int asciiCode = (int)origin[i];
- // 解密(移位)
- asciiCode = asciiCode - (int)keys[i % d] + (int)'A';
- if (asciiCode < (int)'A')
- {
- asciiCode += 26;
- }
- byte[] byteArray = new byte[] { (byte)asciiCode };
- // 将偏移后的数据转为字符
- ASCIIEncoding asciiEncoding = new ASCIIEncoding();
- string strCharacter = asciiEncoding.GetString(byteArray);
- plaintext += strCharacter;
- }
- return plaintext;
- }
- }
复制代码 4. DES
4.1 原理介绍
DES(数据加密标准,Data Encryption Standard),出自IBM的研究,后被美国政府正式采用,密钥长度56位,以现代的计算能力可在24h以内被暴力破解。算法设计原理参考这篇博客。
顺便说一下3DES(Triple DES),它是DES向AES过渡的加密算法,使用3条56位的密钥对数据进行三次加密。是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加密算法。比起最初的DES,3DES更为安全。
4.2 C#代码
C#中提供封装好的DES加解密方法,直接调用即可。- // DES(数据加密标准,Data Encryption Standard)
- public sealed class DES
- {
- /* DES相关
- ecb、ctr模式不需要初始化向量
- cbc、ofc、cfb需要初始化向量
- 初始化向量的长度:DES/3DES为8byte;AES为16byte。加解密使用的IV相同。
- */
- /// <summary>
- /// DES加密
- /// </summary>
- /// <param name="plaintext">明文</param>
- /// <param name="key">密钥,长度8byte</param>
- /// <param name="iv">初始化向量,长度8byte</param>
- /// <returns>返回密文</returns>
- public static string DESEncrypt(string plaintext, string key, string iv)
- {
- try
- {
- byte[] btKey = Encoding.UTF8.GetBytes(key);
- byte[] btIV = Encoding.UTF8.GetBytes(iv);
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- using (MemoryStream ms = new MemoryStream())
- {
- byte[] inData = Encoding.UTF8.GetBytes(plaintext);
- try
- {
- using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
- {
- cs.Write(inData, 0, inData.Length);
- cs.FlushFinalBlock();
- }
- return Convert.ToBase64String(ms.ToArray());
- }
- catch
- {
- return plaintext;
- }
- }
- }
- catch { }
- return "DES加密出错";
- }
- /// <summary>
- /// DES解密
- /// </summary>
- /// <param name="ciphertext">密文</param>
- /// <param name="key">密钥,长度8byte</param>
- /// <param name="iv">初始化向量,长度8byte</param>
- /// <returns>返回明文</returns>
- public static string DESDecrypt(string ciphertext, string key, string iv)
- {
- if (ciphertext == "") return "";
- try
- {
- byte[] btKey = Encoding.UTF8.GetBytes(key);
- byte[] btIV = Encoding.UTF8.GetBytes(iv);
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- using (MemoryStream ms = new MemoryStream())
- {
- byte[] inData = Convert.FromBase64String(ciphertext);
- try
- {
- using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
- {
- cs.Write(inData, 0, inData.Length);
- cs.FlushFinalBlock();
- }
- return Encoding.UTF8.GetString(ms.ToArray());
- }
- catch
- {
- return ciphertext;
- }
- }
- }
- catch { }
- return "DES解密出错";
- }
- }
复制代码 5. AES
5.1 原理简述
AES(高级加密算法,Advanced Encryption Standard),美国政府提出,该加密算法采用对称分组密码体制,提供128位、192位和256位三种密钥长度,算法应易于各种硬件和软件实现。这种加密算法是美国联邦政府采用的区块加密标准。AES本身就是为了取代DES的,AES具有更好的安全性、效率和灵活性。
5.2 C#代码
- // AES(高级加密算法,Advanced Encryption Standard),美政府提出
- public sealed class AES
- {
- /// <summary>
- /// AES加密
- /// </summary>
- /// <param name="plaintext">明文</param>
- /// <param name="key">密钥,长度16byte</param>
- /// <param name="IV">初始化向量,长度16byte</param>
- /// <returns>返回密文</returns>
- public static string AESEncrypt(string plaintext, string key, string iv)
- {
- if (plaintext == "") return "";
- try
- {
- byte[] btKey = Encoding.UTF8.GetBytes(key);
- byte[] btIV = Encoding.UTF8.GetBytes(iv);
- byte[] inputByteArray = Encoding.UTF8.GetBytes(plaintext);
- using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
- {
- using (MemoryStream mStream = new MemoryStream())
- {
- CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write);
- cStream.Write(inputByteArray, 0, inputByteArray.Length);
- cStream.FlushFinalBlock();
- cStream.Close();
- return Convert.ToBase64String(mStream.ToArray());
- }
- }
- }
- catch { }
- return "AES加密出错";
- }
- /// <summary>
- /// AES解密
- /// </summary>
- /// <param name="ciphertext">密文</param>
- /// <param name="key">密钥,长度16byte</param>
- /// <param name="iv">初始化向量,长度16byte</param>
- /// <returns>返回明文</returns>
- public static string AESDecrypt(string ciphertext, string key, string iv)
- {
- if (ciphertext == "") return "";
- try
- {
- byte[] btKey = Encoding.UTF8.GetBytes(key);
- byte[] btIV = Encoding.UTF8.GetBytes(iv);
- byte[] inputByteArray = Convert.FromBase64String(ciphertext);
- using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
- {
- using (MemoryStream mStream = new MemoryStream())
- {
- CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write);
- cStream.Write(inputByteArray, 0, inputByteArray.Length);
- cStream.FlushFinalBlock();
- cStream.Close();
- return Encoding.UTF8.GetString(mStream.ToArray());
- }
- }
- }
- catch { }
- return "AES解密出错";
- }
- }
复制代码 参考资料
1. 一篇文章彻底弄懂Base64编码原理
2. 【C++】STL常用容器总结之十二:string类
3. 加密算法汇总
4. DES算法加密原理
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |