欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實現(xiàn)常見加密算法的示例代碼

 更新時間:2022年07月24日 10:36:20   作者:最菜程序員Sxx  
這篇文章主要為大家詳細(xì)介紹一下C#中一些常見加密算法(Base64編碼、凱撒密碼、Vigenere密碼、DES、AES)以及它們的實現(xiàn)代碼,感興趣的可以了解一下

前言

最近項目中需要用到字符串加解密,遂研究了一波,發(fā)現(xiàn)密碼學(xué)真的是博大精深,好多算法的設(shè)計都相當(dāng)巧妙,學(xué)到了不少東西,在這里做個小小的總結(jié),方便后續(xù)查閱。

文中關(guān)鍵詞:

  • 明文(P,Plaintext)
  • 密文(C,Ciphertext)
  • 密鑰(K,Key)
  • 加密算法(E,Encypted Algorithm)
  • 解密算法(D,Decrypted Algorithm)
  • 公鑰(Public Key)
  • 私鑰(Private Key)

常見加密算法如下,本文主要介紹紅框里邊的5種算法以及C#代碼實現(xiàn)

1. Base64編碼

1.1 原理介紹

(1)Base64是一種基于64個可打印字符來表示二進(jìn)制數(shù)據(jù)的表示方法。其索引表如下:

共包含64個可打印字符為:A-Z、a-z、0-9、+、/,另外還會有“=”或者“==”作為填充字符出現(xiàn)在編碼中。

(2)編碼規(guī)則

  • 將待編碼字符串每三個字節(jié)分為一組,每組24bit
  • 將上邊的24bit分為4組,每組6bit
  • 在每組前添加兩個0,每組由6bit變?yōu)?bit,總共32bit,即4byte
  • 根據(jù)Base64編碼對照表獲取對應(yīng)的編碼值

上述圖例中:“Man”經(jīng)過Base64編碼之后變?yōu)?ldquo;TWFu”。

(3)字節(jié)數(shù)不足3個時

兩個字節(jié):2byte共16bit,按照編碼規(guī)則,每6bit分為一組,則第三組缺少2bit,用0補齊,得到3個Based64編碼,第四組完全沒有數(shù)據(jù)則用“=”補上。因此上圖“BC”經(jīng)過Base64編碼之后變?yōu)?ldquo;QkM=”;

一個字節(jié):1byte共8bit,按照編碼規(guī)則,每6bit分為一組,則第二組缺少4bit,用0補齊,得到2個Based64編碼,后兩組完全沒有數(shù)據(jù)都用“=”補上。因此上圖“A”經(jīng)過Base64編碼之后變?yōu)?ldquo;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 原理介紹

凱撒密碼是一種很古老的加密體制,主要是通過代換來達(dá)到加密的目的。其基本思想是:通過把字母移動一定的位數(shù)來實現(xiàn)加密和解密。移動位數(shù)就是加密和解密的密鑰。

舉例說明,假設(shè)明文為“ABCD”,密鑰設(shè)置為7,那么對應(yīng)的密文就是“HIJK”。具體流程如下表所示:

2.2 C#代碼

// Caesar Cipher(凱撒密碼)
public sealed class Caesar
{
    // 加密
    public static string CaesarEncrypt(string plaintext, int key)
    {
        // 字符串轉(zhuǎn)換為字節(jié)數(shù)組
        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 };
 
            // 將偏移后的數(shù)據(jù)轉(zhuǎn)為字符
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(byteArray);
 
            // 拼接數(shù)據(jù)
            rst += strCharacter;
        }
        return rst;
    }
 
    // 解密
    public static string CaesarDecrypt(string ciphertext, int key)
    {
        // 字符串轉(zhuǎn)換為字節(jié)數(shù)組
        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 };
 
            // 將偏移后的數(shù)據(jù)轉(zhuǎn)為字符
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(byteArray);
 
            // 拼接數(shù)據(jù)
            rst += strCharacter;
        }
        return rst;
    }
}

3. Vigenere密碼

3.1 原理介紹

在凱撒密碼中,每一個字母通過一定的偏移量(即密鑰K)變成另外一個字母,而維吉尼亞密碼就是由多個偏移量不同的凱撒密碼組成,屬于多表密碼的一種。在一段時間里它曾被稱為“不可破譯的密碼”。

維吉尼亞密碼在加密和解密時,需要一個表格進(jìn)行對照。表格一般為26*26的矩陣,行和列都是由26個英文字母組成。加密時,明文字母作為列,密鑰字母作為行,所對應(yīng)坐標(biāo)上的字母即為對應(yīng)的密文字母。

可以用上述表格直接查找對應(yīng)的密文,也可通過取模計算的方式。用0-25代替字母A-Z,C表示密文,P表示明文,K表示密鑰,維吉尼亞加密算法可表示為:

密文可表示為:

舉例說明,假設(shè)明文為“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 };
 
            // 將偏移后的數(shù)據(jù)轉(zhuǎn)為字符
            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 };
 
            // 將偏移后的數(shù)據(jù)轉(zhuǎn)為字符
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(byteArray);
 
            plaintext += strCharacter;
        }
        return plaintext;
    }
} 

4. DES

4.1 原理介紹

DES(數(shù)據(jù)加密標(biāo)準(zhǔn),Data Encryption Standard),出自IBM的研究,后被美國政府正式采用,密鑰長度56位,以現(xiàn)代的計算能力可在24h以內(nèi)被暴力破解。算法設(shè)計原理參考這篇博客。

順便說一下3DES(Triple DES),它是DES向AES過渡的加密算法,使用3條56位的密鑰對數(shù)據(jù)進(jìn)行三次加密。是DES的一個更安全的變形。它以DES為基本模塊,通過組合分組方法設(shè)計出分組加密算法。比起最初的DES,3DES更為安全。 

4.2 C#代碼

C#中提供封裝好的DES加解密方法,直接調(diào)用即可。

// DES(數(shù)據(jù)加密標(biāo)準(zhǔn),Data Encryption Standard)
public sealed class DES
{
    /* DES相關(guān)
       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位三種密鑰長度,算法應(yīng)易于各種硬件和軟件實現(xiàn)。這種加密算法是美國聯(lián)邦政府采用的區(qū)塊加密標(biāo)準(zhǔn)。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解密出錯";
    }
} 

到此這篇關(guān)于C#實現(xiàn)常見加密算法的示例代碼的文章就介紹到這了,更多相關(guān)C#加密算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#使用前序遍歷、中序遍歷和后序遍歷打印二叉樹的方法

    C#使用前序遍歷、中序遍歷和后序遍歷打印二叉樹的方法

    這篇文章主要介紹了C#使用前序遍歷、中序遍歷和后序遍歷打印二叉樹的方法,涉及C#遍歷二叉樹的相關(guān)技巧,需要的朋友可以參考下
    2015-04-04
  • HttpHelper類的調(diào)用方法詳解

    HttpHelper類的調(diào)用方法詳解

    這篇文章主要為大家詳細(xì)介紹了HttpHelper類的使用方法,HttpHelper類及調(diào)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • C#集合之列表的用法

    C#集合之列表的用法

    這篇文章介紹了C#集合之列表的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • C#中關(guān)于zip壓縮解壓幫助類的封裝 附源碼下載

    C#中關(guān)于zip壓縮解壓幫助類的封裝 附源碼下載

    之前一個同學(xué)問了這個問題后,看了園子里其它園友的封裝,都很零碎,調(diào)用也不是很方便。所以自己就封裝了一個zip解壓的類。后來想整理下怕自己忘了。就把壓縮的類也一并封裝了
    2013-02-02
  • C# 文字代碼頁 文字編碼的代碼頁名稱速查表

    C# 文字代碼頁 文字編碼的代碼頁名稱速查表

    最近有項目需要用到韓語,日語的編碼轉(zhuǎn)換,最重要的就是需要一個代碼頁的對照,找了一下,最新的代碼頁或者說編碼表如下
    2011-11-11
  • 深入淺出掌握Unity ShaderLab語法基礎(chǔ)

    深入淺出掌握Unity ShaderLab語法基礎(chǔ)

    Unity中所有Shader文件都通過一種陳述性語言進(jìn)行描述,稱為“ShaderLab”, 這篇文章主要介紹了Unity圖形學(xué)之ShaderLab入門基礎(chǔ),需要的朋友可以參考下
    2023-05-05
  • Datagridview使用技巧(9)Datagridview的右鍵菜單

    Datagridview使用技巧(9)Datagridview的右鍵菜單

    這篇文章主要為大家詳細(xì)介紹了Datagridview使用技巧,Datagridview的右鍵菜單,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • 詳解C#中的System.Timers.Timer定時器的使用和定時自動清理內(nèi)存應(yīng)用

    詳解C#中的System.Timers.Timer定時器的使用和定時自動清理內(nèi)存應(yīng)用

    這篇文章主要介紹了詳解C#中的System.Timers.Timer定時器的使用和定時自動清理內(nèi)存應(yīng)用,需要的朋友可以參考下
    2017-06-06
  • WPF實現(xiàn)帶篩選功能的DataGrid

    WPF實現(xiàn)帶篩選功能的DataGrid

    在默認(rèn)情況下,WPF提供的DataGrid僅擁有數(shù)據(jù)展示等簡單功能,如果要實現(xiàn)像Excel一樣復(fù)雜的篩選過濾功能,則相對比較麻煩。本文以一個簡單的小例子,簡述如何通過WPF實現(xiàn)DataGrid的篩選功能,僅供學(xué)習(xí)分享使用,如有不足之處,還請指正
    2023-03-03
  • C#中的枚舉類型(Enum)介紹

    C#中的枚舉類型(Enum)介紹

    這篇文章介紹了C#中的枚舉類型(Enum),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07

最新評論