【问题标题】:Encryption method for using AES-256 symmetric algorithm (AES/ECB/PKCS7Padding) in c#c#中使用AES-256对称算法(AES/ECB/PKCS7Padding)的加密方法
【发布时间】:2015-07-22 05:52:58
【问题描述】:

我想使用带有 ECB 和 PKCS7Padding 的 AES 256 位加密算法来加密字符串。我浏览了很多网站,但没有一个是合适的。 请提出解决方案

【问题讨论】:

  • 你去过那里吗:bouncycastle.org/csharp
  • 为什么要使用ECB模式?这是不安全的。至少使用带有随机 IV 的 CBC。 IV 不需要保密,因此您只需将其添加到密文中并在解密之前将其切掉。

标签: c# encryption aes


【解决方案1】:
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);
           }

source

注意:你可以通过更改SymmetricKey.Mode = CipherMode.CBC;来改变模式

您可以添加SymmetricKey.Padding = PaddingMode.PKCS7; 进行填充

【讨论】:

    【解决方案2】:

    使用bounty castle,您应该能够做到这一点:

    cipher = CipherUtilities.GetCipher("AES/ECB/PKCS7"); 
    cipher.Init(false, new KeyParameter(key));
    

    【讨论】:

    • 赏金城堡究竟是什么以及如何使用,代码应该是c#中的独立代码
    猜你喜欢
    • 2020-06-24
    • 2018-07-08
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多