How to decrypt an AES-256-CBC encrypted string

后端 未结 1 2041
遇见更好的自我
遇见更好的自我 2020-12-03 11:41

I\'m new to C# and I really need help. I need to encrypt/decrypt a string with AES-256-CBC in C#, I found this to encrypt a string:

    public static string          


        
相关标签:
1条回答
  • 2020-12-03 11:59

    Looking at your encryption, something like this should do it, passing the resulting string from your encryption in should give the original string back;

    // Decrypt a string into a string using a key and an IV 
    public static string Decrypt(string cipherData, string keyString, string ivString)
    {
        byte[] key = Encoding.UTF8.GetBytes(keyString);
        byte[] iv  = Encoding.UTF8.GetBytes(ivString);
    
        try
        {
            using (var rijndaelManaged =
                   new RijndaelManaged {Key = key, IV = iv, Mode = CipherMode.CBC})
            using (var memoryStream = 
                   new MemoryStream(Convert.FromBase64String(cipherData)))
            using (var cryptoStream =
                   new CryptoStream(memoryStream,
                       rijndaelManaged.CreateDecryptor(key, iv),
                       CryptoStreamMode.Read))
            {
                return new StreamReader(cryptoStream).ReadToEnd();
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        // You may want to catch more exceptions here...
    }
    

    A small note; you're getting the key using UTF8 encoding from the key string, UTF8 encoding may give you multiple bytes back for international characters, which may give a key or IV of the wrong length for encryption/decryption. Also, using the small range of passwords/keys with 8 characters and printable characters will not give you very secure encryption, you may want to run the string though SHA1 or similar before using it as a key (which will sadly make it incompatible with the current encryption)

    0 讨论(0)
提交回复
热议问题