Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does a bad password cause "Padding is invalid and cannot be removed"?
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload