常见加密算法C#实现(一)

打印 上一主题 下一主题

主题 1791|帖子 1791|积分 5373

前言:最近项目中需要用到字符串加解密,遂研究了一波,发现密码学真的是博大精深,好多算法的设计都相当巧妙,学到了不少东西,在这里做个小小的总结,方便后续查阅。
文中关键词:

  • 明文(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#代码
  1. // Base64编码
  2. public sealed class Base64
  3. {
  4.     // Base64加密
  5.     public static string Base64Encrypt(string plaintext)
  6.     {
  7.         string ciphertext = "";
  8.         byte[] buffer = Encoding.ASCII.GetBytes(plaintext);
  9.         ciphertext = Convert.ToBase64String(buffer);
  10.         return ciphertext;
  11.     }
  12.     // Base64解密
  13.     public static string Base64Decrypt(string ciphertext)
  14.     {
  15.         string plaintext = "";
  16.         byte[] buffer = Convert.FromBase64String(ciphertext);
  17.         plaintext = Encoding.ASCII.GetString(buffer);
  18.         return plaintext;
  19.     }
  20. } 
复制代码
2. 凯撒密码

2.1 原理介绍

  凯撒密码是一种很古老的加密体制,主要是通过代换来达到加密的目的。其基本思想是:通过把字母移动一定的位数来实现加密和解密。移动位数就是加密和解密的密钥。
  举例说明,假设明文为“ABCD”,密钥设置为7,那么对应的密文就是“HIJK”。具体流程如下表所示:

2.2 C#代码
  1. // Caesar Cipher(凯撒密码)
  2. public sealed class Caesar
  3. {
  4.     // 加密
  5.     public static string CaesarEncrypt(string plaintext, int key)
  6.     {
  7.         // 字符串转换为字节数组
  8.         byte[] origin = Encoding.ASCII.GetBytes(plaintext);
  9.         string rst = null;
  10.         for (int i = 0; i < origin.Length; i++)
  11.         {
  12.             // 获取字符ASCII码
  13.             int asciiCode = (int)origin[i];
  14.             // 偏移
  15.             asciiCode += key;
  16.             byte[] byteArray = new byte[] { (byte)asciiCode };
  17.             // 将偏移后的数据转为字符
  18.             ASCIIEncoding asciiEncoding = new ASCIIEncoding();
  19.             string strCharacter = asciiEncoding.GetString(byteArray);
  20.             // 拼接数据
  21.             rst += strCharacter;
  22.         }
  23.         return rst;
  24.     }
  25.     // 解密
  26.     public static string CaesarDecrypt(string ciphertext, int key)
  27.     {
  28.         // 字符串转换为字节数组
  29.         byte[] origin = Encoding.ASCII.GetBytes(ciphertext);
  30.         string rst = null;
  31.         for (int i = 0; i < origin.Length; i++)
  32.         {
  33.             // 获取字符ASCII码
  34.             int asciiCode = (int)origin[i];
  35.             // 偏移
  36.             asciiCode -= key;
  37.             byte[] byteArray = new byte[] { (byte)asciiCode };
  38.             // 将偏移后的数据转为字符
  39.             ASCIIEncoding asciiEncoding = new ASCIIEncoding();
  40.             string strCharacter = asciiEncoding.GetString(byteArray);
  41.             // 拼接数据
  42.             rst += strCharacter;
  43.         }
  44.         return rst;
  45.     }
  46. }
复制代码
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#代码
  1. // Vigenere Cipher(维吉尼亚密码)
  2. public sealed class Vigenere
  3. {
  4.     // 加密
  5.     public static string VigenereEncrypt(string plaintext, string key)
  6.     {
  7.         string ciphertext = "";
  8.         byte[] origin = Encoding.ASCII.GetBytes(plaintext.ToUpper());
  9.         byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
  10.         int length = origin.Length;
  11.         int d = keys.Length;
  12.         for (int i = 0; i < length; i++)
  13.         {
  14.             int asciiCode = (int)origin[i];
  15.             // 加密(移位)
  16.             asciiCode = asciiCode + (int)keys[i % d] - (int)'A';
  17.             if (asciiCode > (int)'Z')
  18.             {
  19.                 asciiCode -= 26;
  20.             }
  21.             byte[] byteArray = new byte[] { (byte)asciiCode };
  22.             // 将偏移后的数据转为字符
  23.             ASCIIEncoding asciiEncoding = new ASCIIEncoding();
  24.             string strCharacter = asciiEncoding.GetString(byteArray);
  25.             ciphertext += strCharacter;
  26.         }
  27.         return ciphertext;
  28.     }
  29.     // 解密
  30.     public static string VigenereDecrypt(string ciphertext, string key)
  31.     {
  32.         string plaintext = "";
  33.         byte[] origin = Encoding.ASCII.GetBytes(ciphertext.ToUpper());
  34.         byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
  35.         int length = origin.Length;
  36.         int d = keys.Length;
  37.         for (int i = 0; i < length; i++)
  38.         {
  39.             int asciiCode = (int)origin[i];
  40.             // 解密(移位)
  41.             asciiCode = asciiCode - (int)keys[i % d] + (int)'A';
  42.             if (asciiCode < (int)'A')
  43.             {
  44.                 asciiCode += 26;
  45.             }
  46.             byte[] byteArray = new byte[] { (byte)asciiCode };
  47.             // 将偏移后的数据转为字符
  48.             ASCIIEncoding asciiEncoding = new ASCIIEncoding();
  49.             string strCharacter = asciiEncoding.GetString(byteArray);
  50.             plaintext += strCharacter;
  51.         }
  52.         return plaintext;
  53.     }
复制代码
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加解密方法,直接调用即可。
  1. // DES(数据加密标准,Data Encryption Standard)
  2. public sealed class DES
  3. {
  4.     /* DES相关
  5.        ecb、ctr模式不需要初始化向量
  6.        cbc、ofc、cfb需要初始化向量
  7.        初始化向量的长度:DES/3DES为8byte;AES为16byte。加解密使用的IV相同。
  8.     */
  9.     /// <summary>
  10.     /// DES加密
  11.     /// </summary>
  12.     /// <param name="plaintext">明文</param>
  13.     /// <param name="key">密钥,长度8byte</param>
  14.     /// <param name="iv">初始化向量,长度8byte</param>
  15.     /// <returns>返回密文</returns>
  16.     public static string DESEncrypt(string plaintext, string key, string iv)
  17.     {
  18.         try
  19.         {
  20.             byte[] btKey = Encoding.UTF8.GetBytes(key);
  21.             byte[] btIV = Encoding.UTF8.GetBytes(iv);
  22.             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  23.             using (MemoryStream ms = new MemoryStream())
  24.             {
  25.                 byte[] inData = Encoding.UTF8.GetBytes(plaintext);
  26.                 try
  27.                 {
  28.                     using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
  29.                     {
  30.                         cs.Write(inData, 0, inData.Length);
  31.                         cs.FlushFinalBlock();
  32.                     }
  33.                     return Convert.ToBase64String(ms.ToArray());
  34.                 }
  35.                 catch
  36.                 {
  37.                     return plaintext;
  38.                 }
  39.             }
  40.         }
  41.         catch { }
  42.         return "DES加密出错";
  43.     }
  44.     /// <summary>
  45.     /// DES解密
  46.     /// </summary>
  47.     /// <param name="ciphertext">密文</param>
  48.     /// <param name="key">密钥,长度8byte</param>
  49.     /// <param name="iv">初始化向量,长度8byte</param>
  50.     /// <returns>返回明文</returns>
  51.     public static string DESDecrypt(string ciphertext, string key, string iv)
  52.     {
  53.         if (ciphertext == "") return "";
  54.         try
  55.         {
  56.             byte[] btKey = Encoding.UTF8.GetBytes(key);
  57.             byte[] btIV = Encoding.UTF8.GetBytes(iv);
  58.             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  59.             using (MemoryStream ms = new MemoryStream())
  60.             {
  61.                 byte[] inData = Convert.FromBase64String(ciphertext);
  62.                 try
  63.                 {
  64.                     using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
  65.                     {
  66.                         cs.Write(inData, 0, inData.Length);
  67.                         cs.FlushFinalBlock();
  68.                     }
  69.                     return Encoding.UTF8.GetString(ms.ToArray());
  70.                 }
  71.                 catch
  72.                 {
  73.                     return ciphertext;
  74.                 }
  75.             }
  76.         }
  77.         catch { }
  78.         return "DES解密出错";
  79.     }
  80. }
复制代码
5. AES

5.1 原理简述

  AES(高级加密算法,Advanced Encryption Standard),美国政府提出,该加密算法采用对称分组密码体制,提供128位、192位和256位三种密钥长度,算法应易于各种硬件和软件实现。这种加密算法是美国联邦政府采用的区块加密标准。AES本身就是为了取代DES的,AES具有更好的安全性、效率和灵活性。
5.2 C#代码
  1. // AES(高级加密算法,Advanced Encryption Standard),美政府提出
  2. public sealed class AES
  3. {
  4.     /// <summary>
  5.     /// AES加密
  6.     /// </summary>
  7.     /// <param name="plaintext">明文</param>
  8.     /// <param name="key">密钥,长度16byte</param>
  9.     /// <param name="IV">初始化向量,长度16byte</param>
  10.     /// <returns>返回密文</returns>
  11.     public static string AESEncrypt(string plaintext, string key, string iv)
  12.     {
  13.         if (plaintext == "") return "";
  14.         try
  15.         {
  16.             byte[] btKey = Encoding.UTF8.GetBytes(key);
  17.             byte[] btIV = Encoding.UTF8.GetBytes(iv);
  18.             byte[] inputByteArray = Encoding.UTF8.GetBytes(plaintext);
  19.             using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
  20.             {
  21.                 using (MemoryStream mStream = new MemoryStream())
  22.                 {
  23.                     CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write);
  24.                     cStream.Write(inputByteArray, 0, inputByteArray.Length);
  25.                     cStream.FlushFinalBlock();
  26.                     cStream.Close();
  27.                     return Convert.ToBase64String(mStream.ToArray());
  28.                 }
  29.             }
  30.         }
  31.         catch { }
  32.         return "AES加密出错";
  33.     }
  34.     /// <summary>
  35.     /// AES解密
  36.     /// </summary>
  37.     /// <param name="ciphertext">密文</param>
  38.     /// <param name="key">密钥,长度16byte</param>
  39.     /// <param name="iv">初始化向量,长度16byte</param>
  40.     /// <returns>返回明文</returns>
  41.     public static string AESDecrypt(string ciphertext, string key, string iv)
  42.     {
  43.         if (ciphertext == "") return "";
  44.         try
  45.         {
  46.             byte[] btKey = Encoding.UTF8.GetBytes(key);
  47.             byte[] btIV = Encoding.UTF8.GetBytes(iv);
  48.             byte[] inputByteArray = Convert.FromBase64String(ciphertext);
  49.             using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
  50.             {
  51.                 using (MemoryStream mStream = new MemoryStream())
  52.                 {
  53.                     CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write);
  54.                     cStream.Write(inputByteArray, 0, inputByteArray.Length);
  55.                     cStream.FlushFinalBlock();
  56.                     cStream.Close();
  57.                     return Encoding.UTF8.GetString(mStream.ToArray());
  58.                 }
  59.             }
  60.         }
  61.         catch { }
  62.         return "AES解密出错";
  63.     }
  64. } 
复制代码
参考资料

1. 一篇文章彻底弄懂Base64编码原理
2. 【C++】STL常用容器总结之十二:string类
3. 加密算法汇总
4. DES算法加密原理

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曹旭辉

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表