c# - AES 解密仅产生部分答案 C#

标签 c# security encryption aes

我正在尝试学习网络安全,这是我在这方面所做的第一件事。我正在使用这个 MSDN 文档( https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?redirectedfrom=MSDN&view=netcore-3.1 )并且它部分有效。我认为它加密得很好,因为在解密时,一些原始数据存在,但有些丢失了。正在加密的数据是一个已格式化为 JSON 字符串的类(我认为这不相关,因为它仍然是一个正在加密的字符串)。 original data

但是一旦它被加密和解密,它就会变成这样: Encrypted then decrypted data

我已经运行了这段代码并比较了结果 5 次以上,但总是:开头错误,用户名部分正确,密码始终正确,登录 key 部分正确。因此错误会重复出现,并且总是出现在同一个位置。

您应该了解的信息,数据已加密并保存到 .txt 文件中。该程序将再次运行,并尝试解密。 Salt 和密码保存在另一个文件中,并在解密中读取和使用它们。

stackoverflow上有一个类似的问题,但答案只是说使用Rijndael(所以不是真正的答案),这段代码是为了我学习并想要一个不长4行的答案。

如果好奇的话可以写代码(但基本上和MSDN文档一样):

加密:

    static void EncryptFile()
    {
        string pwd1 = SteamID;//steamID is referring to account ID on Valve Steam           
        using (RNGCryptoServiceProvider rngCsp = new
        RNGCryptoServiceProvider())
        {
            rngCsp.GetBytes(salt1); //salt1 is a programme variable and will get saved to a file
        }
        SecureData File = new SecureData(_UserName,_PassWord,_LoginKey);
        string JsonFile = JsonConvert.SerializeObject(File); //puts the class into Json format
        int myIterations = 1000; //not needed
        try
        {
            Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
            myIterations);
            Aes encAlg = Aes.Create(); // This might be the issue as AES will be different when you decrypt 
            encAlg.Key = k1.GetBytes(16);
            MemoryStream encryptionStream = new MemoryStream();
            CryptoStream encrypt = new CryptoStream(encryptionStream,
            encAlg.CreateEncryptor(), CryptoStreamMode.Write);
            byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
            JsonFile); //encrypt Data 

            encrypt.Write(utfD1, 0, utfD1.Length);
            encrypt.FlushFinalBlock();
            encrypt.Close();
            byte[] edata1 = encryptionStream.ToArray();
            k1.Reset();

            System.IO.File.WriteAllBytes(SecureFile, edata1); //writes encrypted data to file
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: ", e);
        }
    }

解密:

    static void DecryptFile()
    {
        string pwd1 = SteamID;
        byte[] edata1;
        try
        {
            edata1 = System.IO.File.ReadAllBytes(SecureFile); //reads the file with encrypted data on it
            Aes encAlg = Aes.Create(); //I think this is the problem as the keyvalue changes when you create a new programme
            Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1); //inputs from last time carry over
            Aes decAlg = Aes.Create();
            decAlg.Key = k2.GetBytes(16);
            decAlg.IV = encAlg.IV;
            MemoryStream decryptionStreamBacking = new MemoryStream();
            CryptoStream decrypt = new CryptoStream(
            decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
            decrypt.Write(edata1, 0, edata1.Length);
            decrypt.Flush();
            decrypt.Close();
            k2.Reset();
            string data2 = new UTF8Encoding(false).GetString(
            decryptionStreamBacking.ToArray());//decrypted data  
            SecureData items = JsonConvert.DeserializeObject<SecureData>(data2); //reformat it out of JSon(Crashes as format isn't accepted)
            _UserName = items.S_UserName;
            _PassWord = items.S_Password;
            _LoginKey = items.S_LoginKey;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: ", e);
            NewLogin();
        }
    }

类结构:

    class SecureData
    {
        public string S_UserName { get; set; } //These are variables that are apart of Valve steam Login process 
        public string S_Password { get; set; }
        public string S_LoginKey { get; set; }

        public SecureData(string z, string x, string y)
        {
            S_UserName = z;
            S_Password = x;
            S_LoginKey = y;
        }
    }

最佳答案

该问题是由加密和解密的IV不同引起的。为了成功解密,必须使用加密中的 IV。

为什么应用不同的 IV?创建 AES 实例时,会隐式生成随机 IV。因此,两个不同的 AES 实例意味着两个不同的 IV。在发布的代码中,使用不同的AES实例进行加密和解密。虽然解密中使用的引用 encAlg 与加密的名称相同,但引用的实例是不同的(即解密过程中新创建的实例)。这在 Microsoft 示例中有所不同。此处,加密的 IV 用于解密:decAlg.IV = encAlg.IV,其中 encAlg 是使用其的 AES 实例已执行加密。

解决方案是将加密后的 IV 存储在文件中,以便在解密时使用。 IV 不是 secret 的,通常放在密文之前:

EncryptFile 中的必要更改:

...
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(JsonFile); 

encryptionStream.Write(encAlg.IV, 0, encAlg.IV.Length);           // Write the IV
encryptionStream.Flush();
            
encrypt.Write(utfD1, 0, utfD1.Length);
...
            

DecryptFile 中的必要更改:

...
edata1 = System.IO.File.ReadAllBytes(SecureFile); 
            
byte[] iv = new byte[16];                                         // Separate IV and ciphertext
byte[] ciphertext = new byte[edata1.Length - iv.Length];
Array.Copy(edata1, 0, iv, 0, iv.Length);
Array.Copy(edata1, iv.Length, ciphertext, 0, ciphertext.Length);
...     
Aes encAlg = Aes.Create();                                        // Remove this line
...
decAlg.IV = iv;                                                   // Use the separated IV
...
decrypt.Write(ciphertext, 0, ciphertext.Length);                  // Use the separated ciphertext

几点说明:

  • 对于每次加密,都应生成一个新的随机盐,并将其与类似于 IV 的密文连接起来。在解密过程中,可以类似于 IV 来确定盐。另外考虑RFC8018, sec 4.1 .
  • 迭代计数会减慢 key 的推导速度,这将使重复尝试的攻击变得更加困难。因此该值应尽可能大。另外考虑RFC8018, sec 4.2 .
  • 身份验证数据(即密码)未加密,而是经过哈希处理,here .

关于c# - AES 解密仅产生部分答案 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63182894/

相关文章:

c# - 网站安全测试显示 Response.Redirect 容易受到攻击

c# - 静态类 C# 中的惰性属性初始化

php - 加密用于票务系统的条形码上显示的 ID 的值

java - Pdfbox 签名和保护,无需保存在文件系统中

c# - 我可以创建一个返回 Task<T> 的方法来同步运行吗?

c# - 如何以编程方式响应 Windows 8 Metro 中的 Snap

javascript - 无需登录即可跨 iframe 进行跨域身份验证

java - 如何使用字符数组密码进行jtds连接

objective-c - 使用 CommonCrypto 生成加盐 key

php - 加密 - 它是这样工作的还是我想错了?