zhang_jiafeng
zhang_jiafeng
采纳率0%
2016-03-28 02:52 阅读 5.7k

C#AES加密时,怎么产生密钥和密钥向量?

各位大神好,最近在做一个一个项目,牵扯到加密,网上搜到了加密算法,但是不知道AES的机密密钥和密钥向量怎么产生?烦请各位为小弟指点一下~

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • lx624909677 lx624909677 2016-03-28 06:15
     /// AES加密
            /// </summary>
            /// <param name="inputdata">输入的数据</param>
            /// <param name="iv">向量128位</param>
            /// <param name="strKey">加密密钥</param>
            /// <returns></returns>
            public static byte[] AESEncrypt(byte[] inputdata, byte[] iv, string strKey)
            {
                //分组加密算法   
                SymmetricAlgorithm des = Rijndael.Create();
                byte[] inputByteArray = inputdata;//得到需要加密的字节数组       
                //设置密钥及密钥向量
                des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
                des.IV = iv;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                        cs.FlushFinalBlock();
                        byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组   
                        cs.Close();
                        ms.Close();                   
                        return cipherBytes;
                    }
                }
            }
    
    
            /// <summary>
            /// AES解密
            /// </summary>
            /// <param name="inputdata">输入的数据</param>
            /// <param name="iv">向量128</param>
            /// <param name="strKey">key</param>
            /// <returns></returns>
            public static byte[] AESDecrypt(byte[] inputdata, byte[] iv, string strKey)
            {
                SymmetricAlgorithm des = Rijndael.Create();
                des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
                des.IV = iv;
                byte[] decryptBytes = new byte[inputdata.Length];
                using (MemoryStream ms = new MemoryStream(inputdata))
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        cs.Read(decryptBytes, 0, decryptBytes.Length);
                        cs.Close();
                        ms.Close();
                    }
                }
                return decryptBytes;
            }
    
    点赞 评论 复制链接分享

相关推荐