C#实现aes加密和解密工具类
2016-08-16 13:12:51  By: shinyuu

AES(The Advanced Encryption Standard)是美国国家标准与技术研究所用于加密电子数据的规范、它被预期能成为人们公认的加密包括金融、电信和政府数字信息的方法、AES是一个新的可以用于保护电子数据的加密算法

明确地说、AES是一个迭代的、对称密钥分组的密码、它可以使用128、192 和 256 位密钥、并且用 128 位(16字节)分组加密和解密数据、与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据、通过分组密码返回的加密数据的位数与输入数据相同、以下是我经过整理的代码、希望对大家有所帮助


完整的Class代码

/// <summary>
/// ASE加解密
/// </summary>
public class AESHelper
{
    /// <summary>
    /// 获取密钥
    /// </summary>
    private static string Key
    {
        get
        {
            return "abcdef1234567890";    ////必须是16位
        }
    }
    //默认密钥向量 
    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>将加密后的密文转换为Base64编码,以便显示</returns>
    public static string AESEncrypt(string plainText)
    {
        //分组加密算法
        SymmetricAlgorithm des = Rijndael.Create();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 
        //设置密钥及密钥向量
        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();//得到加密后的字节数组
                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("", "");   ///将字符串后尾的´´去掉
    }
}


上面的代码可以直接复制到项目中使用、但是一定要修改私钥和向量的值、改为自己项目独有的就可以了

若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力

想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)

或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)

如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教

为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)

感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛


快速评论


技术评论

  • 该技术还没有评论、赶快抢沙发吧...
DD记账
top
+