亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#實現(xiàn)對AES加密和解密的方法

 更新時間:2013年04月24日 16:09:48   作者:  
C#實現(xiàn)對AES加密和解密的方法,需要的朋友可以參考一下

AES簡介

AES(The Advanced Encryption Standard)是美國國家標(biāo)準(zhǔn)與技術(shù)研究所用于加密電子數(shù)據(jù)的規(guī)范。它被預(yù)期能成為人們公認(rèn)的加密包括金融、電信和政府?dāng)?shù)字信息的方法。

AES 是一個新的可以用于保護電子數(shù)據(jù)的加密算法。明確地說,AES 是一個迭代的、對稱密鑰分組的密碼,它可以使用128、192 和 256 位密鑰,并且用 128 位(16字節(jié))分組加密和解密數(shù)據(jù)。與公共密鑰密碼使用密鑰對不同,對稱密鑰密碼使用相同的密鑰加密和解密數(shù)據(jù)。通過分組密碼返回的加密數(shù)據(jù) 的位數(shù)與輸入數(shù)據(jù)相同。以下是我經(jīng)過整理的代碼,希望對大家有所幫助:

復(fù)制代碼 代碼如下:

/// <summary>
/// ASE加解密
/// </summary>
public class AESHelper
{
    /// <summary>
    /// 獲取密鑰
    /// </summary>
    private static string Key
    {
        get
        {
            return "abcdef1234567890";    ////必須是16位
        }
    }

    //默認(rèn)密鑰向量
    private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

    /// <summary>
    /// AES加密算法
    /// </summary>
    /// <param name="plainText">明文字符串</param>
    /// <returns>將加密后的密文轉(zhuǎn)換為Base64編碼,以便顯示</returns>
    public static string AESEncrypt(string plainText)
    {
        //分組加密算法
        SymmetricAlgorithm des = Rijndael.Create();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字節(jié)數(shù)組
        //設(shè)置密鑰及密鑰向量
        des.Key = Encoding.UTF8.GetBytes(Key);
        des.IV = _key1;
        byte[] cipherBytes = null;
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                cipherBytes = ms.ToArray();//得到加密后的字節(jié)數(shù)組
                cs.Close();
                ms.Close();
            }
        }
        return Convert.ToBase64String(cipherBytes);
    }

    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="cipherText">密文字符串</param>
    /// <returns>返回解密后的明文字符串</returns>
    public static string AESDecrypt(string showText)
    {
        byte[] cipherText = Convert.FromBase64String(showText);

        SymmetricAlgorithm des = Rijndael.Create();
        des.Key = Encoding.UTF8.GetBytes(Key);
        des.IV = _key1;
        byte[] decryptBytes = new byte[cipherText.Length];
        using (MemoryStream ms = new MemoryStream(cipherText))
        {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
            {
                cs.Read(decryptBytes, 0, decryptBytes.Length);
                cs.Close();
                ms.Close();
            }
        }
        return Encoding.UTF8.GetString(decryptBytes).Replace("\0", "");   ///將字符串后尾的'\0'去掉
    }
}


Key的值可以放在config文件中,也可放入數(shù)據(jù)庫中。

相關(guān)文章

最新評論