Problem with encryption/decryption

  • Thread starter Thread starter Jon Poploskie
  • Start date Start date
J

Jon Poploskie

Hello,

I am trying to encrypt/decrypt some text that is being stored in an XML
file. The encryption/decryption works fine when I don't save it to the
file, but I get the following error when I try to decrypt the text that I
stored in the XML file:

PKCS7 padding is invalid and cannot be removed.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.Security.Cryptography.CryptographicException:
PKCS7 padding is invalid and cannot be removed.

Source Error:

Line 64: CryptoStream crypto = new CryptoStream(ms,
sa.CreateDecryptor(key, iv), CryptoStreamMode.Write);
Line 65: crypto.Write(bytes, 0, bytes.Length);
Line 66: crypto.FlushFinalBlock();
Line 67: crypto.Close();
Line 68: return Encoding.Unicode.GetString(ms.ToArray());


I have tried pretty much every available encoding to write the XML file
(using an XmlTextWriter), but nothing seems to be working. I've included
the cryptography functions I'm using, I'd appreciate any thoughts anyone
has. By the way, key is a hardcoded 32 byte key and iv is a hardcoded 16
byte IV.

Thank you!
Jon

public static string EncryptText(string textToEncrypt)
{
if(textToEncrypt == null)
return null;

byte[] bytes = Encoding.Unicode.GetBytes(textToEncrypt);
MemoryStream ms = new MemoryStream();

SymmetricAlgorithm sa = new RijndaelManaged();
CryptoStream crypto = new CryptoStream(ms, sa.CreateEncryptor(key, iv),
CryptoStreamMode.Write);
crypto.Write(bytes, 0, bytes.Length);
crypto.FlushFinalBlock();
crypto.Close();
return Convert.ToBase64String(ms.ToArray());
}

public static string DecodeText(string txtToDecode)
{
if(txtToDecode == null)
return null;

byte[] bytes = Convert.FromBase64String(txtToDecode);
MemoryStream ms = new MemoryStream();
SymmetricAlgorithm sa = new RijndaelManaged();
CryptoStream crypto = new CryptoStream(ms, sa.CreateDecryptor(key, iv),
CryptoStreamMode.Write);
crypto.Write(bytes, 0, bytes.Length);
crypto.FlushFinalBlock();
crypto.Close();
return Encoding.Unicode.GetString(ms.ToArray());
}
 
I think your problem may be related to key size...
Here's my VB code, that works...
Private mobjCryptoService As System.Security.Cryptography.SymmetricAlgorithm

Private Const strKey As String = "don't exceed the key size"

Dim key() As Byte = GetLegalKey(strKey)

Private Function GetLegalKey(ByVal Key As String) As Byte()

' Depending on the legal key size limitations of a specific CryptoService
provider

' and length of the private key provided, padding the secret key with space
character

' to meet the legal size of the algorithm.

Dim sTemp As String

If (mobjCryptoService.LegalKeySizes.Length > 0) Then

Dim lessSize As Integer = 0

Dim moreSize As Integer = mobjCryptoService.LegalKeySizes(0).MinSize

'' key sizes are in bits

Do While (Key.Length * 8 > moreSize)

lessSize = moreSize

moreSize += mobjCryptoService.LegalKeySizes(0).SkipSize

Loop

sTemp = Key.PadRight(moreSize / 8, " ")

Else

sTemp = Key

End If

'' convert the secret key to byte array

Return ASCIIEncoding.ASCII.GetBytes(sTemp)

End Function



Hello,

I am trying to encrypt/decrypt some text that is being stored in an XML
file. The encryption/decryption works fine when I don't save it to the
file, but I get the following error when I try to decrypt the text that I
stored in the XML file:

PKCS7 padding is invalid and cannot be removed.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.Security.Cryptography.CryptographicException:
PKCS7 padding is invalid and cannot be removed.

Source Error:

Line 64: CryptoStream crypto = new CryptoStream(ms,
sa.CreateDecryptor(key, iv), CryptoStreamMode.Write);
Line 65: crypto.Write(bytes, 0, bytes.Length);
Line 66: crypto.FlushFinalBlock();
Line 67: crypto.Close();
Line 68: return Encoding.Unicode.GetString(ms.ToArray());


I have tried pretty much every available encoding to write the XML file
(using an XmlTextWriter), but nothing seems to be working. I've included
the cryptography functions I'm using, I'd appreciate any thoughts anyone
has. By the way, key is a hardcoded 32 byte key and iv is a hardcoded 16
byte IV.

Thank you!
Jon

public static string EncryptText(string textToEncrypt)
{
if(textToEncrypt == null)
return null;

byte[] bytes = Encoding.Unicode.GetBytes(textToEncrypt);
MemoryStream ms = new MemoryStream();

SymmetricAlgorithm sa = new RijndaelManaged();
CryptoStream crypto = new CryptoStream(ms, sa.CreateEncryptor(key, iv),
CryptoStreamMode.Write);
crypto.Write(bytes, 0, bytes.Length);
crypto.FlushFinalBlock();
crypto.Close();
return Convert.ToBase64String(ms.ToArray());
}

public static string DecodeText(string txtToDecode)
{
if(txtToDecode == null)
return null;

byte[] bytes = Convert.FromBase64String(txtToDecode);
MemoryStream ms = new MemoryStream();
SymmetricAlgorithm sa = new RijndaelManaged();
CryptoStream crypto = new CryptoStream(ms, sa.CreateDecryptor(key, iv),
CryptoStreamMode.Write);
crypto.Write(bytes, 0, bytes.Length);
crypto.FlushFinalBlock();
crypto.Close();
return Encoding.Unicode.GetString(ms.ToArray());
}
 
Not sure what you are doing wrong, but here is some code that works for you to play with. It is also commented so that you have a clue what it is doing, and why.

Good luck!

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Xml;

namespace Lilypepper.Cryptography
{
/// <summary>
/// Implements a simple symmetric encryption object for use with Unicode strings.
/// </summary>
/// <remarks>
/// <p>
/// This is a wrapper for the Rijndael algorithm using maximum key and
/// block sizes. It is for use with string data.
/// </p>
/// <p>
/// The visible part of the output of <see cref="SymmetricEncryption.Encrypt"/>
/// is an XML document containing an "initialization vector" (IV) and some encrypted
/// data. It is okay for the IV to be public - in fact, that is exactly how it
/// is supposed to be used. The IV and the private key are all that are required
/// to decrypt the cipher-text.
/// </p>
/// <p>
/// The encrypted portion of the output also contains an XML document. This
/// document contains the plain-text in a CDATA section along with a hash code.
/// The hash code is used to verify that the data has not been corrupted. In
/// Rijndael, a small change in the cipher text will normally only corrupt
/// a portion of the plain text. It is therefore important to verify the integrity of
/// the data after decryption. This is accomplished by keeping a hash (message digest)
/// of the original data to compare against.
/// </p>
/// </remarks>
public sealed class SymmetricEncryption
{
RijndaelManaged _crypt = null;
UTF8Encoding _encoding = new UTF8Encoding();
SHA1Managed _sha = new SHA1Managed();

/// <SUMMARY>
/// Returns the key size in bytes.
/// </SUMMARY>
/// <REMARKS>
/// The value is fixed at 32 (256 bits) for the sake of simplicity. This is the
/// maximum key size allowed by the Rijndael algorithm.
/// </REMARKS>
public const int KeySize = 32;

/// <SUMMARY>
/// Returns the block size in bytes.
/// </SUMMARY>
/// <REMARKS>
/// The value is fixed at 32 (256 bits) for the sake of simplicity. This is the
/// maximum block size allowed by the Rijndael algorithm.
/// </REMARKS>
private const int BlockSize = 32;

public SymmetricEncryption()
{
_crypt = new RijndaelManaged();
_crypt.KeySize = KeySize * 8;
_crypt.BlockSize = BlockSize * 8;
_crypt.Padding = PaddingMode.Zeros;
_crypt.Mode = CipherMode.CBC;
_crypt.GenerateKey();
}

/// <SUMMARY>
/// Initializes the <C>SymmetricEncryption</C> instance with a key.
/// </SUMMARY>
/// <PARAM name="key">The symmetric key for encryption and decryption.</PARAM>
public SymmetricEncryption(byte[] key):this()
{
if(key.Length != KeySize)
throw new ArgumentException("Key must be exactly " + KeySize + " bytes (" + (KeySize * 8) + " bits).");
_crypt.Key = key;
}

/// <SUMMARY>
/// Initializes the <C>SymmetricEncryption</C> instance with a key based on a password.
/// </SUMMARY>
/// <REMARKS>
/// This constructor runs very slowly (a few thousand times slower than is possible) by design. Passwords
/// almost always are the weakest link in any cryptographic system. Typical passwords
/// may only provide 20 to 40 bits of encryption strength. The slower password generation scheme
/// used here may effectively add 10 bits or so to the strength of the password. If you are
/// concerned about the speed of the password key generation, use one of the other constructors
/// that takes a key directly.
/// </REMARKS>
/// <PARAM name="password">The password used to generate the strong key.</PARAM>
public SymmetricEncryption(string password):this(GetPassKey(password))
{
}

public byte[] Key
{
get{return _crypt.Key;}
}

/// <SUMMARY>
/// Derives a key from a password. Given the same password and number of bytes for
/// the key size, this will return the same key.
/// </SUMMARY>
/// <REMARKS>
/// Wraps the functionality of <SEE cref="System.Security.Cryptography.PasswordDeriveBytes" />
/// using a fixed seed value and the default hash algorithm. The hash algorithm is SHA256, which
/// guarantees the key will be secure to 256 bits. Additionally, the number of iterations has
/// been purposely chosen to make generating the key from the password a relatively expensive
/// operation. Since the password is the weakest link in the encryption chain, we want to make
/// sure that it is relatively expensive to guess the password. The number
/// of iterations has been chosen to make each password guess take more than 10 msec (depending on
/// the speed of the CPU). Even a very good password guessing heuristic is going to get bogged
/// down if it can't do more than 100 guesses per second, even if the password is relatively
/// unsecure!
/// </REMARKS>
/// <PARAM name="password">The password to derive the key from.</PARAM>
/// <RETURNS>A byte array containing the key.</RETURNS>
private static byte[] GetPassKey(string password)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(
password,
new byte[] {0xDE, 0xAD, 0xBE, 0xEF, 0x11, 0x22, 0x44, 0x88},
"SHA256",
2048);
return pdb.GetBytes(KeySize);
}

/// <SUMMARY>
/// Encrypts string data that can be decrypted later with <SEE cref="Decrypt" />.
/// </SUMMARY>
///
/// <PARAM name="plainText">The text to encrypt.</PARAM>
/// <RETURNS>An XML document containing the encrypted data and associated information.</RETURNS>
public XmlDocument Encrypt(string plainText)
{
byte[] hash = ComputeHashValue(plainText);
XmlDocument cryptDoc = new XmlDocument();
XmlElement documentElt = (XmlElement)cryptDoc.AppendChild(cryptDoc.CreateElement("document"));
documentElt.AppendChild(cryptDoc.CreateCDataSection(plainText));
documentElt.SetAttribute("hash", Convert.ToBase64String(hash));

_crypt.GenerateIV();
byte[] iv = _crypt.IV;

ICryptoTransform encryptor = _crypt.CreateEncryptor();
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
StreamWriter swEncrypt = new StreamWriter(csEncrypt, Encoding.UTF8);
swEncrypt.Write(cryptDoc.OuterXml);
swEncrypt.Flush();
csEncrypt.FlushFinalBlock();

byte[] data = msEncrypt.ToArray();

swEncrypt.Close();

XmlDocument containerDoc = new XmlDocument();
XmlElement containerElt = (XmlElement)containerDoc.AppendChild(containerDoc.CreateElement("encryptedData"));

containerElt.SetAttribute("iv", Convert.ToBase64String(iv));
containerElt.InnerText = Convert.ToBase64String(data);

return containerDoc;
}

/// <SUMMARY>
/// Decrypts data that was encrypted with <SEE cref="Encrypt" />.
/// </SUMMARY>
///
/// <PARAM name="cipherXml">The XML document or element containing the cipher-text.</PARAM>
/// <RETURNS>The original, decrypted text.</RETURNS>
///
/// <EXCEPTION cref="System.ArgumentException">
/// <C>cipherXml</C> must be either a <C>XmlDocument</C> or a <C>XmlElement</C>.
/// </EXCEPTION>
///
/// <EXCEPTION cref="System.ApplicationException">
/// The XML element does not conform to the standard structure for encrypted data.
/// </EXCEPTION>
///
/// <EXCEPTION cref="System.Security.Cryptography.CryptographicException">
/// Message failed to decrypt. This may be due to either an invalid key or corrupted data
/// (verified by a hash comparison).
/// </EXCEPTION>
public string Decrypt(XmlNode cipherXml)
{
XmlElement cipherElt = null;
if(cipherXml is XmlDocument)
cipherElt = ((XmlDocument)cipherXml).DocumentElement;
else if(cipherXml is XmlElement)
cipherElt = (XmlElement)cipherXml;
else
throw new ArgumentException("Object to decrypt must be either an XmlElement or an XmlDocument.", "cipherXml");

if(cipherElt.GetAttribute("iv") == "")
throw new ApplicationException("XML structure is not correct.");

byte[] iv = Convert.FromBase64String(cipherElt.GetAttribute("iv"));

byte[] data = Convert.FromBase64String(cipherElt.InnerText);

try
{
_crypt.IV = iv;

ICryptoTransform decryptor = _crypt.CreateDecryptor();
MemoryStream msDecrypt = new MemoryStream(data);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.UTF8);

string result = srDecrypt.ReadToEnd();
int length = result.Length;
while((int)result[length-1] == 0)
length--;
result = result.Substring(0, length);

XmlDocument cryptDoc = new XmlDocument();
cryptDoc.LoadXml(result);
XmlElement cryptElt = cryptDoc.DocumentElement;

string plainText = cryptElt.InnerText;
string hash = cryptElt.GetAttribute("hash");

string computedHash = Convert.ToBase64String(ComputeHashValue(plainText));
if(hash != computedHash)
throw new ApplicationException("Encrypted data was corrupt.");

return plainText;
}
catch(Exception e)
{
throw new CryptographicException("Decryption operation failed.", e);
}
}

/// <SUMMARY>
/// Computes an SHA1 hash value for the UTF-8 byte representation of the given string.
/// </SUMMARY>
/// <PARAM name="text">The text string that the hash will be computed against.</PARAM>
/// <RETURNS>A hash value.</RETURNS>
private byte[] ComputeHashValue(string text)
{
byte[] textBytes = _encoding.GetBytes(text);
SHA1Managed sha = new SHA1Managed();
return sha.ComputeHash(textBytes, 0, textBytes.Length);
}
}
}
 
Hello Jon,

Thanks for posting in the group.

Dan and Jason has provided you a lot useful information. Here is my thought
on the problem.

Since the problem doesn't exist when you encrypt/decrypt text in memory. It
only happens when invloving IO operations. The problem may be existing in
the save XML part. So I suggest you pay more attention to it and compare
the data to see if you could find difference there.

Hope that helps.

Best regards,
Yanhong Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
!From: "Jon Poploskie" <[email protected]>
!Subject: Problem with encryption/decryption
!Date: Fri, 19 Sep 2003 12:56:50 -0400
!Lines: 68
!X-Priority: 3
!X-MSMail-Priority: Normal
!X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
!X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
!Message-ID: <[email protected]>
!Newsgroups: microsoft.public.dotnet.framework
!NNTP-Posting-Host: 207.148.215.34
!Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP11.phx.gbl
!Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.framework:54223
!X-Tomcat-NG: microsoft.public.dotnet.framework
!
!Hello,
!
!I am trying to encrypt/decrypt some text that is being stored in an XML
!file. The encryption/decryption works fine when I don't save it to the
!file, but I get the following error when I try to decrypt the text that I
!stored in the XML file:
!
!PKCS7 padding is invalid and cannot be removed.
!Description: An unhandled exception occurred during the execution of the
!current web request. Please review the stack trace for more information
!about the error and where it originated in the code.
!
!Exception Details: System.Security.Cryptography.CryptographicException:
!PKCS7 padding is invalid and cannot be removed.
!
!Source Error:
!
!Line 64: CryptoStream crypto = new CryptoStream(ms,
!sa.CreateDecryptor(key, iv), CryptoStreamMode.Write);
!Line 65: crypto.Write(bytes, 0, bytes.Length);
!Line 66: crypto.FlushFinalBlock();
!Line 67: crypto.Close();
!Line 68: return Encoding.Unicode.GetString(ms.ToArray());
!
!
!I have tried pretty much every available encoding to write the XML file
!(using an XmlTextWriter), but nothing seems to be working. I've included
!the cryptography functions I'm using, I'd appreciate any thoughts anyone
!has. By the way, key is a hardcoded 32 byte key and iv is a hardcoded 16
!byte IV.
!
!Thank you!
!Jon
!
!public static string EncryptText(string textToEncrypt)
!{
! if(textToEncrypt == null)
! return null;
!
! byte[] bytes = Encoding.Unicode.GetBytes(textToEncrypt);
! MemoryStream ms = new MemoryStream();
!
! SymmetricAlgorithm sa = new RijndaelManaged();
! CryptoStream crypto = new CryptoStream(ms, sa.CreateEncryptor(key, iv),
!CryptoStreamMode.Write);
! crypto.Write(bytes, 0, bytes.Length);
! crypto.FlushFinalBlock();
! crypto.Close();
! return Convert.ToBase64String(ms.ToArray());
!}
!
!public static string DecodeText(string txtToDecode)
!{
! if(txtToDecode == null)
! return null;
!
! byte[] bytes = Convert.FromBase64String(txtToDecode);
! MemoryStream ms = new MemoryStream();
! SymmetricAlgorithm sa = new RijndaelManaged();
! CryptoStream crypto = new CryptoStream(ms, sa.CreateDecryptor(key, iv),
!CryptoStreamMode.Write);
! crypto.Write(bytes, 0, bytes.Length);
! crypto.FlushFinalBlock();
! crypto.Close();
! return Encoding.Unicode.GetString(ms.ToArray());
!}
!
!
!
 
Thank you all for the help. It turns out that I have found the problem, and
it was indeed a problem in reading the xml out of the file to pass it into
the decryption algorithm.

Thanks again,
Jon

Yan-Hong Huang said:
Hello Jon,

Thanks for posting in the group.

Dan and Jason has provided you a lot useful information. Here is my thought
on the problem.

Since the problem doesn't exist when you encrypt/decrypt text in memory. It
only happens when invloving IO operations. The problem may be existing in
the save XML part. So I suggest you pay more attention to it and compare
the data to see if you could find difference there.

Hope that helps.

Best regards,
Yanhong Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
!From: "Jon Poploskie" <[email protected]>
!Subject: Problem with encryption/decryption
!Date: Fri, 19 Sep 2003 12:56:50 -0400
!Lines: 68
!X-Priority: 3
!X-MSMail-Priority: Normal
!X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
!X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
!Message-ID: <[email protected]>
!Newsgroups: microsoft.public.dotnet.framework
!NNTP-Posting-Host: 207.148.215.34
!Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP11.phx.gbl
!Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.framework:54223
!X-Tomcat-NG: microsoft.public.dotnet.framework
!
!Hello,
!
!I am trying to encrypt/decrypt some text that is being stored in an XML
!file. The encryption/decryption works fine when I don't save it to the
!file, but I get the following error when I try to decrypt the text that I
!stored in the XML file:
!
!PKCS7 padding is invalid and cannot be removed.
!Description: An unhandled exception occurred during the execution of the
!current web request. Please review the stack trace for more information
!about the error and where it originated in the code.
!
!Exception Details: System.Security.Cryptography.CryptographicException:
!PKCS7 padding is invalid and cannot be removed.
!
!Source Error:
!
!Line 64: CryptoStream crypto = new CryptoStream(ms,
!sa.CreateDecryptor(key, iv), CryptoStreamMode.Write);
!Line 65: crypto.Write(bytes, 0, bytes.Length);
!Line 66: crypto.FlushFinalBlock();
!Line 67: crypto.Close();
!Line 68: return Encoding.Unicode.GetString(ms.ToArray());
!
!
!I have tried pretty much every available encoding to write the XML file
!(using an XmlTextWriter), but nothing seems to be working. I've included
!the cryptography functions I'm using, I'd appreciate any thoughts anyone
!has. By the way, key is a hardcoded 32 byte key and iv is a hardcoded 16
!byte IV.
!
!Thank you!
!Jon
!
!public static string EncryptText(string textToEncrypt)
!{
! if(textToEncrypt == null)
! return null;
!
! byte[] bytes = Encoding.Unicode.GetBytes(textToEncrypt);
! MemoryStream ms = new MemoryStream();
!
! SymmetricAlgorithm sa = new RijndaelManaged();
! CryptoStream crypto = new CryptoStream(ms, sa.CreateEncryptor(key, iv),
!CryptoStreamMode.Write);
! crypto.Write(bytes, 0, bytes.Length);
! crypto.FlushFinalBlock();
! crypto.Close();
! return Convert.ToBase64String(ms.ToArray());
!}
!
!public static string DecodeText(string txtToDecode)
!{
! if(txtToDecode == null)
! return null;
!
! byte[] bytes = Convert.FromBase64String(txtToDecode);
! MemoryStream ms = new MemoryStream();
! SymmetricAlgorithm sa = new RijndaelManaged();
! CryptoStream crypto = new CryptoStream(ms, sa.CreateDecryptor(key, iv),
!CryptoStreamMode.Write);
! crypto.Write(bytes, 0, bytes.Length);
! crypto.FlushFinalBlock();
! crypto.Close();
! return Encoding.Unicode.GetString(ms.ToArray());
!}
!
!
!
 
Hi,

SO you got the answer ....did you want to tell the rest of the world??




tal mcmahon
 
Hi Jon,

I am glad to hear it.

Thanks for participating the community.

Best regards,
Yanhong Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
!From: "Jon Poploskie" <[email protected]>
!References: <[email protected]>
<kqoXb#[email protected]>
!Subject: Re: Problem with encryption/decryption
!Date: Mon, 22 Sep 2003 09:35:39 -0400
!Lines: 121
!X-Priority: 3
!X-MSMail-Priority: Normal
!X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
!X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
!Message-ID: <#[email protected]>
!Newsgroups: microsoft.public.dotnet.framework
!NNTP-Posting-Host: 207.148.215.34
!Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!tk2msftngp13.phx.gbl
!Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.framework:54381
!X-Tomcat-NG: microsoft.public.dotnet.framework
!
!Thank you all for the help. It turns out that I have found the problem,
and
!it was indeed a problem in reading the xml out of the file to pass it into
!the decryption algorithm.
!
!Thanks again,
!Jon
!
!!> Hello Jon,
!>
!> Thanks for posting in the group.
!>
!> Dan and Jason has provided you a lot useful information. Here is my
!thought
!> on the problem.
!>
!> Since the problem doesn't exist when you encrypt/decrypt text in memory.
!It
!> only happens when invloving IO operations. The problem may be existing in
!> the save XML part. So I suggest you pay more attention to it and compare
!> the data to see if you could find difference there.
!>
!> Hope that helps.
!>
!> Best regards,
!> Yanhong Huang
!> Microsoft Online Partner Support
!>
!> Get Secure! - www.microsoft.com/security
!> This posting is provided "AS IS" with no warranties, and confers no
!rights.
!>
!> --------------------
!> !From: "Jon Poploskie" <[email protected]>
!> !Subject: Problem with encryption/decryption
!> !Date: Fri, 19 Sep 2003 12:56:50 -0400
!> !Lines: 68
!> !X-Priority: 3
!> !X-MSMail-Priority: Normal
!> !X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
!> !X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
!> !Message-ID: <[email protected]>
!> !Newsgroups: microsoft.public.dotnet.framework
!> !NNTP-Posting-Host: 207.148.215.34
!> !Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP11.phx.gbl
!> !Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.framework:54223
!> !X-Tomcat-NG: microsoft.public.dotnet.framework
!> !
!> !Hello,
!> !
!> !I am trying to encrypt/decrypt some text that is being stored in an XML
!> !file. The encryption/decryption works fine when I don't save it to the
!> !file, but I get the following error when I try to decrypt the text that
I
!> !stored in the XML file:
!> !
!> !PKCS7 padding is invalid and cannot be removed.
!> !Description: An unhandled exception occurred during the execution of the
!> !current web request. Please review the stack trace for more information
!> !about the error and where it originated in the code.
!> !
!> !Exception Details: System.Security.Cryptography.CryptographicException:
!> !PKCS7 padding is invalid and cannot be removed.
!> !
!> !Source Error:
!> !
!> !Line 64: CryptoStream crypto = new CryptoStream(ms,
!> !sa.CreateDecryptor(key, iv), CryptoStreamMode.Write);
!> !Line 65: crypto.Write(bytes, 0, bytes.Length);
!> !Line 66: crypto.FlushFinalBlock();
!> !Line 67: crypto.Close();
!> !Line 68: return Encoding.Unicode.GetString(ms.ToArray());
!> !
!> !
!> !I have tried pretty much every available encoding to write the XML file
!> !(using an XmlTextWriter), but nothing seems to be working. I've
included
!> !the cryptography functions I'm using, I'd appreciate any thoughts anyone
!> !has. By the way, key is a hardcoded 32 byte key and iv is a hardcoded
16
!> !byte IV.
!> !
!> !Thank you!
!> !Jon
!> !
!> !public static string EncryptText(string textToEncrypt)
!> !{
!> ! if(textToEncrypt == null)
!> ! return null;
!> !
!> ! byte[] bytes = Encoding.Unicode.GetBytes(textToEncrypt);
!> ! MemoryStream ms = new MemoryStream();
!> !
!> ! SymmetricAlgorithm sa = new RijndaelManaged();
!> ! CryptoStream crypto = new CryptoStream(ms, sa.CreateEncryptor(key, iv),
!> !CryptoStreamMode.Write);
!> ! crypto.Write(bytes, 0, bytes.Length);
!> ! crypto.FlushFinalBlock();
!> ! crypto.Close();
!> ! return Convert.ToBase64String(ms.ToArray());
!> !}
!> !
!> !public static string DecodeText(string txtToDecode)
!> !{
!> ! if(txtToDecode == null)
!> ! return null;
!> !
!> ! byte[] bytes = Convert.FromBase64String(txtToDecode);
!> ! MemoryStream ms = new MemoryStream();
!> ! SymmetricAlgorithm sa = new RijndaelManaged();
!> ! CryptoStream crypto = new CryptoStream(ms, sa.CreateDecryptor(key, iv),
!> !CryptoStreamMode.Write);
!> ! crypto.Write(bytes, 0, bytes.Length);
!> ! crypto.FlushFinalBlock();
!> ! crypto.Close();
!> ! return Encoding.Unicode.GetString(ms.ToArray());
!> !}
!> !
!> !
!> !
!>
!
!
!
 
I was doing a ToLower on the encrypted string after I read it from the Xml,
but before I passed it to the decryption method. This was an inadvertent
carry-over from the code before it was encrypted.

Jon
 
Back
Top