zoukankan      html  css  js  c++  java
  • C# AES 加解密处理

    引言

      这是一个有关AES加解密的方法类

    一、设置AES加解密密钥:下面列出自己分配的三类密钥

            private const string UserKey = "roshan-2015-user"; //加密用户名和密码
            private static readonly byte[] UserIv = { 5, 4, 0xF, 7, 9, 0xC, 1, 0xB, 3, 0x5B, 0xD, 0x17, 1, 0xA, 6, 8 };
    
            private const string ServerAuthTokenKey = "roshan2015server"; //加密服务端AuthToken
            private static readonly byte[] ServerAuthTokenIv = { 0xC, 1, 0xB, 3, 0x5B, 0xD, 5, 4, 0xF, 7, 9, 0x17, 1, 0xA, 6, 8 };
    
            private const string ClientAuthTokenKey = "roshan2015client";//加密客户端AuthToken
            private static readonly byte[] ClientAuthTokenIv = { 0x38, 0x31, 0x37, 0x34, 0x36, 0x33, 0x35, 0x33, 0x32, 0x31, 0x34, 0x38, 0x37, 0x36, 0x35, 0x32 };   
    密钥设置

    二、填充方法:这里个人采用默认的填充方法

    Mode:CBC

    Padding:PKCS7

    三、配置加解密方法

            /// <summary>
            /// 加密
            /// </summary>
            /// <param name="toEncrypt">明文</param>
            /// <param name="key">秘钥</param>
            /// <param name="ivBytes">向量</param>
            /// <returns>密文</returns>
            public static string AESEncrypt(string toEncrypt, string key, byte[] ivBytes)
            {
                byte[] toEncryptBytes = System.Text.Encoding.UTF8.GetBytes(toEncrypt);
                var rijndael = new RijndaelManaged();
                rijndael.Key = System.Text.Encoding.UTF8.GetBytes(key);
                rijndael.IV = ivBytes;
                ICryptoTransform cryptoTransform = rijndael.CreateDecryptor();
                byte[] resultBytes = cryptoTransform.TransformFinalBlock(toEncryptBytes, 0, toEncryptBytes.Length);
                return Convert.ToBase64String(resultBytes);
            }
    加密方法
            /// <summary>
            /// 解密
            /// </summary>
            /// <param name="toDecrypt">密文</param>
            /// <param name="key">秘钥</param>
            /// <param name="ivBytes">向量</param>
            /// <returns>明文</returns>
            private static string AESDecrypt(string toDecrypt, string key, byte[] ivBytes)
            {
                byte[] toDecryptBytes = Convert.FromBase64String(toDecrypt);
                var rijndael = new RijndaelManaged();
                rijndael.Key = System.Text.Encoding.UTF8.GetBytes(key);
                rijndael.IV = ivBytes;
                ICryptoTransform cryptoTransform = rijndael.CreateDecryptor();
                byte[] resultArray = cryptoTransform.TransformFinalBlock(toDecryptBytes, 0, toDecryptBytes.Length);
                return System.Text.Encoding.UTF8.GetString(resultArray);
            }
    解密方法
    真正的谦卑是对真理持续不断的追求。
  • 相关阅读:
    设计模式
    刷新所有视图存储过程
    js杨辉三角控制台输出
    2018申请淘宝客AppKey
    w3c标准 dom对象 事件冒泡和事件捕获
    promise原理
    vue virtual Dom
    css学习
    seo优化
    新概念学习
  • 原文地址:https://www.cnblogs.com/huanghzm/p/5381531.html
Copyright © 2011-2022 走看看