473,883 Members | 1,608 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Encryption Error "Length of the data to decrypt is invalid"

Hello all,
I am having a problem where I get an error message when I call
FlushFinalBlock when decrypting my encrypted text. I am using the
Rijndael algorithm.

The error message is "Length of the data to decrypt is invalid" and
occurs on the csDecrypt.Flush FinalBlock.

Please find below the two routines I use to encrypt my text and decrypt
the text. I have used the two routines in a very simple app that takes
a string from a label and then calls EncryptString and displays it on
another label. I then call DecryptString and pass it the contents of
the encrypted label text property.

The CryptKey is byte[32] and is set on creation of the object
containing these methods.

Could somebody please enlighten me as to what I am doing wrong!
Thanks in advance

Jimski

public string EncryptString(s tring pText)
{
string strResult = "";

try
{
// Create the rijndael encryptor
ICryptoTransfor m encryptor =
_RijndaelEncryp tor.CreateEncry ptor();

// Encrypt the data to the memory stream
MemoryStream msEncrypt = new MemoryStream(pT ext.Length);
CryptoStream csEncrypt = new CryptoStream(ms Encrypt, encryptor,
CryptoStreamMod e.Write);

// Convert the string to a byte array.
byte[] beforeEncrypt = Encoding.UTF8.G etBytes(pText);

// Write all the data to the crypto stream and flush it to the
MemoryStream.
csEncrypt.Write (beforeEncrypt, 0, beforeEncrypt.L ength);
csEncrypt.Flush FinalBlock();

// Read encrypted array of bytes from the MemoryStream
byte[] afterEncrypt = new byte[msEncrypt.Lengt h];
msEncrypt.Posit ion = 0;
msEncrypt.Read( afterEncrypt, 0, afterEncrypt.Le ngth);

csEncrypt.Close ();

// Returns the encrypted text as a string
strResult = Encoding.UTF8.G etString(afterE ncrypt);
}
catch (Exception ex)
{
// An error occurred during encryption
}
return strResult;
}
public string DecryptString(s tring pEncryptedText)
{
string strResult = "";

try
{
// Convert the string to a byte array.
byte[] beforeDecrypt = Encoding.UTF8.G etBytes(pEncryp tedText);

// Create the rijndael decryptor
ICryptoTransfor m decryptor =
_RijndaelEncryp tor.CreateDecry ptor();

// decrypt the data to the memory stream
MemoryStream msDecrypt = new
MemoryStream(be foreDecrypt.Len gth);
CryptoStream csDecrypt = new CryptoStream(ms Decrypt, decryptor,
CryptoStreamMod e.Write);

// Write all the data to the crypto stream and flush it.
csDecrypt.Write (beforeDecrypt, 0, beforeDecrypt.L ength);
// ERROR occurs in this next line.
csDecrypt.Flush FinalBlock();

// Read decrypted array of bytes from the MemoryStream
byte[] afterDecrypt = new byte[msDecrypt.Lengt h];
msDecrypt.Posit ion = 0;
msDecrypt.Read( afterDecrypt, 0, afterDecrypt.Le ngth);

csDecrypt.Close ();

// Returns the decrypted text as a string
strResult = Encoding.UTF8.G etString(afterD ecrypt);
}
catch (Exception ex)
{
// Show error - which in this case is "Length of the data to
decrypt is invalid"
}

return strResult;
}

Nov 16 '05 #1
3 29303
Here's a sample that can should help:

http://www.dalepreston.com/Blog/Arch...0_Archive.html

DalePres
MCAD, MCDBA, MCSE

"Jimski" <ji**********@g mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Hello all,
I am having a problem where I get an error message when I call
FlushFinalBlock when decrypting my encrypted text. I am using the
Rijndael algorithm.

The error message is "Length of the data to decrypt is invalid" and
occurs on the csDecrypt.Flush FinalBlock.

Please find below the two routines I use to encrypt my text and decrypt
the text. I have used the two routines in a very simple app that takes
a string from a label and then calls EncryptString and displays it on
another label. I then call DecryptString and pass it the contents of
the encrypted label text property.

The CryptKey is byte[32] and is set on creation of the object
containing these methods.

Could somebody please enlighten me as to what I am doing wrong!
Thanks in advance

Jimski

public string EncryptString(s tring pText)
{
string strResult = "";

try
{
// Create the rijndael encryptor
ICryptoTransfor m encryptor =
_RijndaelEncryp tor.CreateEncry ptor();

// Encrypt the data to the memory stream
MemoryStream msEncrypt = new MemoryStream(pT ext.Length);
CryptoStream csEncrypt = new CryptoStream(ms Encrypt, encryptor,
CryptoStreamMod e.Write);

// Convert the string to a byte array.
byte[] beforeEncrypt = Encoding.UTF8.G etBytes(pText);

// Write all the data to the crypto stream and flush it to the
MemoryStream.
csEncrypt.Write (beforeEncrypt, 0, beforeEncrypt.L ength);
csEncrypt.Flush FinalBlock();

// Read encrypted array of bytes from the MemoryStream
byte[] afterEncrypt = new byte[msEncrypt.Lengt h];
msEncrypt.Posit ion = 0;
msEncrypt.Read( afterEncrypt, 0, afterEncrypt.Le ngth);

csEncrypt.Close ();

// Returns the encrypted text as a string
strResult = Encoding.UTF8.G etString(afterE ncrypt);
}
catch (Exception ex)
{
// An error occurred during encryption
}
return strResult;
}
public string DecryptString(s tring pEncryptedText)
{
string strResult = "";

try
{
// Convert the string to a byte array.
byte[] beforeDecrypt = Encoding.UTF8.G etBytes(pEncryp tedText);

// Create the rijndael decryptor
ICryptoTransfor m decryptor =
_RijndaelEncryp tor.CreateDecry ptor();

// decrypt the data to the memory stream
MemoryStream msDecrypt = new
MemoryStream(be foreDecrypt.Len gth);
CryptoStream csDecrypt = new CryptoStream(ms Decrypt, decryptor,
CryptoStreamMod e.Write);

// Write all the data to the crypto stream and flush it.
csDecrypt.Write (beforeDecrypt, 0, beforeDecrypt.L ength);
// ERROR occurs in this next line.
csDecrypt.Flush FinalBlock();

// Read decrypted array of bytes from the MemoryStream
byte[] afterDecrypt = new byte[msDecrypt.Lengt h];
msDecrypt.Posit ion = 0;
msDecrypt.Read( afterDecrypt, 0, afterDecrypt.Le ngth);

csDecrypt.Close ();

// Returns the decrypted text as a string
strResult = Encoding.UTF8.G etString(afterD ecrypt);
}
catch (Exception ex)
{
// Show error - which in this case is "Length of the data to
decrypt is invalid"
}

return strResult;
}

Nov 16 '05 #2
Thanks Dale,

Your code identified an area that I was implementing wrong.

In my decryption routine I should have populated the memory stream with
the bytes and then created the CryptoStream. Writing them afterwards
was causing problems.

Cheers for you help.
Jimski

Nov 16 '05 #3
I am glad it helped. That's what makes it worth the time to write it.

DalePres

"Jimski" <ji**********@g mail.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
Thanks Dale,

Your code identified an area that I was implementing wrong.

In my decryption routine I should have populated the memory stream with
the bytes and then created the CryptoStream. Writing them afterwards
was causing problems.

Cheers for you help.
Jimski

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2039
by: vincent wehren | last post by:
Hi, Trying to grasp Py_NewInterpreter()in a simple app embedding Python, I was wondering why the following gives me an error: int main() { PyThreadState *tstate; Py_Initialize();
1
14958
by: arvee | last post by:
Hi - I'm updating an Oracle table with an empty string and getting the error: An unhandled exception of type 'System.Exception' occurred in system.data.dll Additional information: Parameter 'p1': No size set for variable length data type: String. The column is nullable and of type varchar2(50). I'm aware that I can store DBNull.Value instead and Oracle won't complain, but, I was hoping to avoid
3
3020
by: Stephen Poley | last post by:
Could some kind soul explain the errors and warnings that the W3C CSS validator generates for page: http://www.atlis.nl/testsite/nl/ Results at: http://tinyurl.com/5pxqx The error "Invalid number : borderParse Error - " may be due to something I've done, but I'm blowed if I can see what. While the warning "property display doesn't exist for media" has me baffled.
3
4702
by: 21novembre | last post by:
Hi all, I made a question several days before to describe my strange trouble of mysqldump. But I still can't figour it out. Well, I just want to ask another question whether I could just backup my databases by copying the data folder to some place? Then if I meet some disaster, could I just copy the backup folder back to recover my databases? Thank you. Zh.y
7
17883
by: Dica | last post by:
i've used the sample code from msdn to create an encyption/decryption assembly as found here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.asp i'm able to encrypt and then decrypt data okay as in the following code: // encrypt the data // Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes); byte key = Encoding.ASCII.GetBytes("0123456789012345");
0
1828
by: Simon Harris | last post by:
I'm trying to access a password protected web service. My code is as follows: Dim BS7666 As New bs7666.BS7666 'New instance of my web service Dim CredCache As CredentialCache = New CredentialCache Dim WebSvcURL As System.Uri = New System.Uri(BS7666.Url) CredCache.Add(WebSvcURL, "Basic", New NetworkCredential("USERNAME", "PASSWORD", "DOMAIN")) 'This is the line it fails on BS7666.Credentials = CredCache Dim DataSet_bs7666 As New...
6
2152
by: Patrick Dugan | last post by:
Hello, I'm trying to load different images (icons) into a PictureBox1.Image. The first image loads just fine, but the second image always returns the error "Invalid property used." It doesn't matter what icons are loaded. The first always shows up and any icons after that give me the error. Here is the offending code: The "DestinationPath" variable is the full path and filename of the icon
4
6238
by: floppyzedolfin | last post by:
Hello! I'm actually encoding an encryption / decryption program. The encryption programes takes a file path in parameter, and encrypts the contents of the file and stores that into another file. I'm using AES for it is quick, and RSA to encrypt AES, to transmit AES keys (it'll run on two separate computers). Please notice that - this is my first C# code :)
1
2502
by: SM | last post by:
Hi, I need your help, the following code is not working, ret = sr.ReadToEnd() throws the message error : Length of the data to decrypt is invalid. Any idea ? thank you public string Decrypting(string Source, string Key) { string ret = ""; try
0
9943
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11151
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10750
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10858
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7974
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5804
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4619
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3237
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.