<p>I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from <a href="http://www.codeproject.com/KB/security/DotNetCrypto.aspx" rel="noreferrer">here</a>):</p>

<pre><code>    // create and initialize a crypto algorithm
    private static SymmetricAlgorithm getAlgorithm(string password) {
        SymmetricAlgorithm algorithm = Rijndael.Create();
        Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
            password, new byte[] {
            0x53,0x6f,0x64,0x69,0x75,0x6d,0x20,             // salty goodness
            0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
        }
        );
        algorithm.Padding = PaddingMode.ISO10126;
        algorithm.Key = rdb.GetBytes(32);
        algorithm.IV = rdb.GetBytes(16);
        return algorithm;
    }

    /* 
     * encryptString
     * provides simple encryption of a string, with a given password
     */
    public static string encryptString(string clearText, string password) {
        SymmetricAlgorithm algorithm = getAlgorithm(password);
        byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(clearBytes, 0, clearBytes.Length);
        cs.Close();
        return Convert.ToBase64String(ms.ToArray());
    }

    /*
     * decryptString
     * provides simple decryption of a string, with a given password
     */
    public static string decryptString(string cipherText, string password) {
        SymmetricAlgorithm algorithm = getAlgorithm(password);
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(cipherBytes, 0, cipherBytes.Length);
        cs.Close();            
        return System.Text.Encoding.Unicode.GetString(ms.ToArray());
    }
</code></pre>

<p>The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. </p>

<p>example code:</p>

<pre><code>    string password1 = "password";
    string password2 = "letmein";
    string startClearText = "The quick brown fox jumps over the lazy dog";
    string cipherText = encryptString(startClearText, password1);
    string endClearText = decryptString(cipherText, password2);     // exception thrown
</code></pre>

<p>My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.</p>

[{'answer_id': 11776, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 2, 'selected': False, 'text': '<p>Yes, this is to be expected, or at least, its exactly what happens when our crypto routines get non-decryptable data</p>\n'}, {'answer_id': 26283, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 6, 'selected': True, 'text': '<p>Although this have been already answered I think it would be a good idea to explain <strong>why</strong> it is to be expected.</p>\n\n<p>A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the <a href="http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding" rel="noreferrer">OAEP</a> padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or <a href="http://en.wikipedia.org/wiki/Blinding_(cryptography)" rel="noreferrer">blinding</a>).</p>\n\n<p>A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation):</p>\n\n<ol>\n<li>Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number.</li>\n<li>Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent.</li>\n</ol>\n\n<p>That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can\'t say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you\'re doing something wrong (i.e someone has tampered with the message or you\'re using the wrong key)</p>\n'}, {'answer_id': 3404132, 'author': 'R D', 'author_id': 410571, 'author_profile': 'https://Stackoverflow.com/users/410571', 'pm_score': 1, 'selected': False, 'text': '<p>There may be some unread bytes in the CryptoStream. Closing before reading the stream completely was causing the error in my program.</p>\n'}, {'answer_id': 14971080, 'author': 'jbtule', 'author_id': 637783, 'author_profile': 'https://Stackoverflow.com/users/637783', 'pm_score': 3, 'selected': False, 'text': '<p>If you want your usage to be correct, you should add <a href="http://en.wikipedia.org/wiki/Authenticated_encryption" rel="nofollow noreferrer">authentication</a> to your ciphertext so that you can verify that it is the correct pasword or that the ciphertext hasn\'t been modified.  The padding you are using <a href="http://en.wikipedia.org/wiki/Padding_%28cryptography%29#ISO_10126" rel="nofollow noreferrer">ISO10126</a> will only throw an exception if the last byte doesn\'t decrypt as one of 16 valid values for padding (0x01-0x10). So you have a 1/16 chance of it NOT throwing the exception with the wrong password, where if you authenticate it you have a deterministic way to tell if your decryption is valid.</p>\n\n<p>Using crypto api\'s while seemingly easy, actually is rather is easy to make mistakes. For example you use a fixed salt for for you key and iv derivation, that means every ciphertext encrypted with the same password will reuse it\'s IV with that key, that breaks semantic security with CBC mode, the IV needs to be both unpredictable and unique for a given key.</p>\n\n<p>For that reason of easy to make mistakes, I have a code snippet, that I try to keep reviewed and up to date (comments, issues welcome):</p>\n\n<p><a href="https://stackoverflow.com/a/10366194/637783">Modern Examples of Symmetric Authenticated Encryption of a string C#.</a></p>\n\n<p>If you use it\'s <code>AESThenHMAC.AesSimpleDecryptWithPassword(ciphertext, password)</code> when the wrong password is used, <code>null</code> is returned, if the ciphertext or iv has been modified post encryption <code>null</code> is returned, you will never get junk data back, or a padding exception.</p>\n'}, {'answer_id': 19835066, 'author': 'Yaniv', 'author_id': 2964625, 'author_profile': 'https://Stackoverflow.com/users/2964625', 'pm_score': 4, 'selected': False, 'text': '<p>I experienced a similar "Padding is invalid and cannot be removed." exception, but in my case the key IV and padding were correct.</p>\n\n<p>It turned out that flushing the crypto stream is all that was missing.</p>\n\n<p>Like this:</p>\n\n<pre><code>            MemoryStream msr3 = new MemoryStream();\n            CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);\n            encStream.Write(bar2, 0, bar2.Length);\n            // unless we flush the stream we would get "Padding is invalid and cannot be removed." exception when decoding\n            encStream.FlushFinalBlock();\n            byte[] bar3 = msr3.ToArray();\n</code></pre>\n'}, {'answer_id': 28277552, 'author': 'Mina Wissa', 'author_id': 235123, 'author_profile': 'https://Stackoverflow.com/users/235123', 'pm_score': 0, 'selected': False, 'text': '<p>I had a similar problem, the issue in decrypt method was initializing an empty memory stream. when it worked when I initialized it with the cipher text byte array like this:</p>\n\n<pre><code>MemoryStream ms = new MemoryStream(cipherText)\n</code></pre>\n'}, {'answer_id': 29659976, 'author': 'RoopzD', 'author_id': 2537096, 'author_profile': 'https://Stackoverflow.com/users/2537096', 'pm_score': -1, 'selected': False, 'text': '<p>The answer updated by the user "atconway" worked for me.</p>\n\n<p>The problem was not with the padding but the key which was different during encryption and decryption.\nThe key and iv should be same during encypting and decrypting the same value.</p>\n'}, {'answer_id': 39956449, 'author': 'Denis Tikhomirov', 'author_id': 752435, 'author_profile': 'https://Stackoverflow.com/users/752435', 'pm_score': 2, 'selected': False, 'text': '<p>Another reason of the exception might be a race condition between several threads using decryption logic - native implementations of ICryptoTransform are <em>not thread-safe</em> (e.g. SymmetricAlgorithm), so it should be put to exclusive section, e.g. using <em>lock</em>.\nPlease refer here for more details: <a href="http://www.make-awesome.com/2011/07/system-security-cryptography-and-thread-safety/" rel="nofollow">http://www.make-awesome.com/2011/07/system-security-cryptography-and-thread-safety/</a></p>\n'}, {'answer_id': 40018716, 'author': 'Marc L.', 'author_id': 85269, 'author_profile': 'https://Stackoverflow.com/users/85269', 'pm_score': 2, 'selected': False, 'text': "<p>If you've ruled out key-mismatch, then besides <code>FlushFinalBlock()</code> (see Yaniv's answer), calling <code>Close()</code> on the <code>CryptoStream</code> will also suffice.  </p>\n\n<p>If you are cleaning up resources strictly with <code>using</code> blocks, be sure to nest the block for the <code>CryptoStream</code> itself:</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\n{\n  using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n  {\n    encStream.Write(bar2, 0, bar2.Length);\n  } // implicit close\n  byte[] encArray = ms.ToArray();\n}\n</code></pre>\n\n<p>I've been bitten by this (or similar):</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\nusing (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n{\n  encStream.Write(bar2, 0, bar2.Length);\n  byte[] encArray = ms.ToArray();\n} // implicit close -- too late!\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/11762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369/']