如何在没有IV的情况下使用AES 128加密和解密?

kdh*_*kdh 5 c# encryption aes rijndael

我目前需要一种方法来加密字符串并使用AES-128对称加密在C#中解密字节数组.我找不到办法怎么做,但也许我错过了什么.

Ari*_*ari 11

导入名称空间

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

     static void Main(string[] args)
        {
            string value = "@arifansari300<3>";

            string encryptedValue= EncryptDecrypt.Encrypt(value);

            string decryptedValue = EncryptDecrypt.Decrypt(encryptedValue);
        }

    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new 
                Rfc2898DeriveBytes(EncryptionKey, new byte[] 
                { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }

    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new 
                Rfc2898DeriveBytes(EncryptionKey, new byte[] 
                { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
Run Code Online (Sandbox Code Playgroud)

  • 当您必须使用最终用户输入的密码而不是生成正确的密钥时,`Rfc2898DeriveBytes`是一个不错的选择.但是在这种情况下你应该使用一个盐(在你的例子中它是一个常数,错过了IV的点)和更多的迭代(至少20k,最好是更多).如果你有一个正确的密钥,普通加密更简单,*更快*. (2认同)
  • 确保更改盐:0x49、0x76、0x61、0x6e,0x20、0x4d,0x65、0x64、0x76、0x65、0x64、0x65、0x76 =伊万·梅德韦杰夫 (2认同)