安全架构-加密算法-AES加密.NET C#实现

安全架构-加密算法-AES加密.NET C#实现

方法一:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Csharp
{
   
    class AESHelper
    {
   
        /// 
        /// AES加密
        /// 
        /// 被加密的明文
        /// 密钥
        /// 向量
        /// 密文
        public static String AESEncrypt(String Data, String Key, String Vector)
        {
   
            Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);

            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            Byte[] bVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

            Byte[] Cryptograph = null; // 加密后的密文

            Rijndael Aes = Rijndael.Create();
            try
            {
   
                // 开辟一块内存流
                using (MemoryStream Memory = new MemoryStream())
                {
   
                    // 把内存流对象包装成加密流对象
                    using (CryptoStream Encryptor = new CryptoStream(Memory,
                     Aes.CreateEncryptor(bKey, bVector),
                     CryptoStreamMode.Write))
                    {
   
                        // 明文数据写入加密流
                        Encryptor.Write(plainBytes, 0, plainBytes.Length);
                        Encryptor.FlushFinalBlock();

                        Cryptograph = Memory.ToArray();
                    }
                }
            }
            catch
            {
   
                Cryptograph = null;
            }

            

你可能感兴趣的:(安全架构,.NET,安全架构,架构师,加密算法,AES,C#)