C#使用System.Security.Cryptography.Aes的AES256加密示例

C#使用System.Security.Cryptography.Aes的AES256加密示例,c#,encryption,aes,C#,Encryption,Aes,我需要实现AES 256加密/解密,但我还没有找到一个正确工作的示例 建议我使用AES类 Rijndael类是Aes算法的前身。您应该使用Aes算法而不是Rijndael。有关更多信息,请参阅.NET安全博客中的条目 有人能给我指出一个使用AES256的AES类的好例子吗 更清晰一点: 我有一个密码文件,其中包含共享密钥和一个加密文本字符串。我需要解密文本,然后验证它 我看到的所有示例都期望至少有2个参数来执行加密/解密 我应该能够从密码文件中的文本推断出初始化向量和密钥吗 这是保存在我的密码文

我需要实现AES 256加密/解密,但我还没有找到一个正确工作的示例

建议我使用AES类

Rijndael类是Aes算法的前身。您应该使用Aes算法而不是Rijndael。有关更多信息,请参阅.NET安全博客中的条目

有人能给我指出一个使用AES256的AES类的好例子吗

更清晰一点:

我有一个密码文件,其中包含共享密钥和一个加密文本字符串。我需要解密文本,然后验证它

我看到的所有示例都期望至少有2个参数来执行加密/解密

我应该能够从密码文件中的文本推断出初始化向量和密钥吗

这是保存在我的密码文件中的文本示例:

ÚÚ¸Ìrƒ@†²;Ä;öDWnó)

也许这个例子可以帮助你。作者的陈述

大约24行代码需要加密,23行代码需要解密

由于原始帖子中的链接已失效,这里是所需的代码部分(c&p未对原始源代码进行任何更改)

/*
版权所有(c)2010
特此向任何获得副本的人免费授予许可
本软件和相关文档文件(“软件”)的
在软件中不受限制,包括但不限于权利
使用、复制、修改、合并、发布、分发、再许可和/或销售
软件的副本,并允许向其提供软件的人员
按照以下条件提供:
上述版权声明和本许可声明应包含在
软件的所有副本或主要部分。
本软件按“原样”提供,无任何形式的明示或明示担保
默示,包括但不限于适销性保证,
适用于特定目的和非侵权。在任何情况下
作者或版权持有人应承担任何索赔、损害或其他责任
无论是在合同诉讼、侵权诉讼或其他诉讼中,由以下原因引起的责任:,
与本软件有关或与本软件的使用或其他交易有关
软件*/
#区域使用
使用制度;
使用System.IO;
使用System.Security.Cryptography;
使用系统文本;
#端区
名称空间实用程序.加密
{
/// 
///处理加密的实用程序类
/// 
公共静态类加密
{
#区域静态函数
/// 
///加密字符串
/// 
///要加密的文本
///要加密的密码
///用盐加密
///可以是SHA1或MD5
///要执行的迭代次数
///需要16个ASCII字符长
///可以是128、192或256
///加密字符串
公共静态字符串加密(字符串明文、字符串密码、,
string Salt=“犹太”,string HashAlgorithm=“SHA1”,
int PasswordIterations=2,字符串InitialVector=“OFRna73m*aze01xY”,
int KeySize=256)
{
if(string.IsNullOrEmpty(纯文本))
返回“”;
byte[]InitialVectorBytes=Encoding.ASCII.GetBytes(InitialVector);
byte[]SaltValueBytes=Encoding.ASCII.GetBytes(Salt);
字节[]明文字节=Encoding.UTF8.GetBytes(明文);
PasswordDeriveBytes DerivedPassword=新的PasswordDeriveBytes(密码、SaltValueBytes、哈希算法、密码迭代);
byte[]KeyBytes=DerivedPassword.GetBytes(KeySize/8);
RijndaelManaged SymmetricKey=新的RijndaelManaged();
SymmetricKey.Mode=CipherMode.CBC;
byte[]CipherTextBytes=null;
使用(ICryptoTransform Encryptor=SymmetricKey.CreateEncryptor(KeyBytes,InitialVectorBytes))
{
使用(MemoryStream MemStream=new MemoryStream())
{
使用(CryptoStream CryptoStream=new CryptoStream(MemStream、Encryptor、CryptoStreamMode.Write))
{
CryptoStream.Write(明文字节,0,明文字节.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes=MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
返回Convert.tobase64字符串(CipherTextBytes);
}
/// 
///解密字符串
/// 
///要解密的文本
///使用密码进行解密
///用盐解密
///可以是SHA1或MD5
///要执行的迭代次数
///需要16个ASCII字符长
///可以是128、192或256
///解密字符串
公共静态字符串解密(字符串密文、字符串密码、,
string Salt=“犹太”,string HashAlgorithm=“SHA1”,
int PasswordIterations=2,字符串InitialVector=“OFRna73m*aze01xY”,
int KeySize=256)
{
if(string.IsNullOrEmpty(密文))
返回“”;
byte[]InitialVectorBytes=Encoding.ASCII.GetBytes(InitialVector);
byte[]SaltValueBytes=Encoding.ASCII.GetBytes(Salt);
byte[]CipherTextBytes=Convert.FromBase64String(密文);
PasswordDeriveBytes DerivedPassword=新的PasswordDeriveBytes(密码、SaltValueBytes、HashAlgorithm、PasswordIteratio
  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }
    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }
public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}