code_junkie

C# - CryptographicException: Padding is invalid and cannot be removed

Nov 10th, 2011
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. // create and initialize a crypto algorithm
  2. private static SymmetricAlgorithm getAlgorithm(string password) {
  3. SymmetricAlgorithm algorithm = Rijndael.Create();
  4. Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
  5. password, new byte[] {
  6. 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
  7. 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
  8. }
  9. );
  10. algorithm.Padding = PaddingMode.ISO10126;
  11. algorithm.Key = rdb.GetBytes(32);
  12. algorithm.IV = rdb.GetBytes(16);
  13. return algorithm;
  14. }
  15.  
  16. /*
  17. * encryptString
  18. * provides simple encryption of a string, with a given password
  19. */
  20. public static string encryptString(string clearText, string password) {
  21. SymmetricAlgorithm algorithm = getAlgorithm(password);
  22. byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
  23. MemoryStream ms = new MemoryStream();
  24. CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
  25. cs.Write(clearBytes, 0, clearBytes.Length);
  26. cs.Close();
  27. return Convert.ToBase64String(ms.ToArray());
  28. }
  29.  
  30. /*
  31. * decryptString
  32. * provides simple decryption of a string, with a given password
  33. */
  34. public static string decryptString(string cipherText, string password) {
  35. SymmetricAlgorithm algorithm = getAlgorithm(password);
  36. byte[] cipherBytes = Convert.FromBase64String(cipherText);
  37. MemoryStream ms = new MemoryStream();
  38. CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
  39. cs.Write(cipherBytes, 0, cipherBytes.Length);
  40. cs.Close();
  41. return System.Text.Encoding.Unicode.GetString(ms.ToArray());
  42. }
  43.  
  44. string password1 = "password";
  45. string password2 = "letmein";
  46. string startClearText = "The quick brown fox jumps over the lazy dog";
  47. string cipherText = encryptString(startClearText, password1);
  48. string endClearText = decryptString(cipherText, password2); // exception thrown
Add Comment
Please, Sign In to add comment