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


     


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

    文中关键词:

    • 明文(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)编码规则

    1. 将待编码字符串每三个字节分为一组,每组24bit
    2. 将上边的24bit分为4组,每组6bit
    3. 在每组前添加两个0,每组由6bit变为8bit,总共32bit,即4byte
    4. 根据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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // 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#代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    // 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#代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    // 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加解密方法,直接调用即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    // DES(数据加密标准,Data Encryption Standard)
    public sealed class DES
    {
        /* DES相关
           ecb、ctr模式不需要初始化向量
           cbc、ofc、cfb需要初始化向量
           初始化向量的长度:DES/3DES为8byte;AES为16byte。加解密使用的IV相同。
        */
     
        ///
        /// DES加密
        ///
        /// 明文
        /// 密钥,长度8byte
        /// 初始化向量,长度8byte
        /// 返回密文
        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加密出错";
        }
     
        ///
        /// DES解密
        ///
        /// 密文
        /// 密钥,长度8byte
        /// 初始化向量,长度8byte
        /// 返回明文
        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#代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    // AES(高级加密算法,Advanced Encryption Standard),美政府提出
    public sealed class AES
    {
        ///
        /// AES加密
        ///
        /// 明文
        /// 密钥,长度16byte
        /// 初始化向量,长度16byte
        /// 返回密文
        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加密出错";
        }
     
        ///
        /// AES解密
        ///
        /// 密文
        /// 密钥,长度16byte
        /// 初始化向量,长度16byte
        /// 返回明文
        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算法加密原理

  • 相关阅读:
    监听Helm release资源
    计算机毕设(附源码)JAVA-SSM基于框架的毕业生就业管理系统
    windows10自动设置时间灰色怎么办
    基于SSM+Vue的鲜花销售系统设计与实现
    TikTok美国市场爆品:美牙仪一周售出3.36万单,GMV近百万刀
    轻量级简约仪表板Dasherr
    Nginx简单使用
    MySQL知识点归纳总结(一)
    Python4(文件操作、os、异常处理)
    学习Opencv(蝴蝶书/C++)相关——2.用clang++或g++命令行编译程序
  • 原文地址:https://www.cnblogs.com/shaoxx333/p/16435336.html