473,897 Members | 3,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Length of the data to decrypt is invalid

I found this code on a site for doing string encryption/decryption.
The string will encrypt fine, but I get this error when I try to
decrypt. Any idea why? I posted the code below.

The error actually points to this line of code in byte[] decrypt
function:

cs.FlushFinalBl ock();

public static byte[] encrypt(byte[] clearData, byte[] Key, byte[] IV)
{
// Create a MemoryStream to accept the encrypted bytes
MemoryStream ms = new MemoryStream();

// Create a symmetric algorithm.
// We are going to use Rijndael because it is strong and
// available on all platforms.
// You can use other algorithms, to do so substitute the
// next line with something like
// TripleDES alg = TripleDES.Creat e();
Rijndael alg = Rijndael.Create ();

// Now set the key and the IV.
// We need the IV (Initialization Vector) because
// the algorithm is operating in its default
// mode called CBC (Cipher Block Chaining).
// The IV is XORed with the first block (8 byte)
// of the data before it is encrypted, and then each
// encrypted block is XORed with the
// following block of plaintext.
// This is done to make encryption more secure.

// There is also a mode called ECB which does not need an IV,
// but it is much less secure.
alg.Key = Key;
alg.IV = IV;

// Create a CryptoStream through which we are going to be
// pumping our data.
// CryptoStreamMod e.Write means that we are going to be
// writing data to the stream and the output will be written
// in the MemoryStream we have provided.
CryptoStream cs = new CryptoStream(ms ,
alg.CreateEncry ptor(), CryptoStreamMod e.Write);

// Write the data and make it do the encryption
cs.Write(clearD ata, 0, clearData.Lengt h);

// Close the crypto stream (or do FlushFinalBlock ).
// This will tell it that we have done our encryption and
// there is no more data coming in,
// and it is now a good time to apply the padding and
// finalize the encryption process.
cs.Close();

// Now get the encrypted data from the MemoryStream.
// Some people make a mistake of using GetBuffer() here,
// which is not the right way.
byte[] encryptedData = ms.ToArray();

return encryptedData;
}

/// <summary>
/// Encrypt a string into a string using a password
/// </summary>
/// <param name="clearText "></param>
/// <param name="Password" ></param>
/// <returns></returns>
public static string encrypt(string clearText, string Password)
{
// First we need to turn the input string into a byte array.
byte[] clearBytes =
System.Text.Enc oding.Unicode.G etBytes(clearTe xt);

// Then, we need to turn the password into Key and IV
// We are using salt to make it harder to guess our key
// using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveB ytes pdb = new PasswordDeriveB ytes(Password,
new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

// Now get the key/IV and do the encryption using the
// function that accepts byte arrays.
// Using PasswordDeriveB ytes object we are first getting
// 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes)
// and then 16 bytes for the IV.
// IV should always be the block size, which is by default
// 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is
// 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off
// the algorithm to find out the sizes.
byte[] encryptedData = encrypt(clearBy tes,
pdb.GetBytes(32 ), pdb.GetBytes(16 ));

// Now we need to turn the resulting byte array into a string.
// A common mistake would be to use an Encoding class for that.
//It does not work because not all byte values can be
// represented by characters.
// We are going to be using Base64 encoding that is designed
//exactly for what we are trying to do.
return Convert.ToBase6 4String(encrypt edData);
}

/// <summary>
/// // Decrypt a byte array into a byte array using a key and an IV
/// </summary>
/// <param name="cipherDat a"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns></returns>
public static byte[] decrypt(byte[] cipherData,
byte[] Key, byte[] IV)
{
// Create a MemoryStream that is going to accept the
// decrypted bytes
MemoryStream ms = new MemoryStream();

// Create a symmetric algorithm.
// We are going to use Rijndael because it is strong and
// available on all platforms.
// You can use other algorithms, to do so substitute the next
// line with something like
// TripleDES alg = TripleDES.Creat e();
Rijndael alg = Rijndael.Create ();

// Now set the key and the IV.
// We need the IV (Initialization Vector) because the algorithm
// is operating in its default
// mode called CBC (Cipher Block Chaining). The IV is XORed with
// the first block (8 byte)
// of the data after it is decrypted, and then each decrypted
// block is XORed with the previous
// cipher block. This is done to make encryption more secure.
// There is also a mode called ECB which does not need an IV,
// but it is much less secure.
alg.Key = Key;
alg.IV = IV;

// Create a CryptoStream through which we are going to be
// pumping our data.
// CryptoStreamMod e.Write means that we are going to be
// writing data to the stream
// and the output will be written in the MemoryStream
// we have provided.
CryptoStream cs = new CryptoStream(ms ,
alg.CreateDecry ptor(), CryptoStreamMod e.Write);

// Write the data and make it do the decryption
cs.Write(cipher Data, 0, cipherData.Leng th);

// Close the crypto stream (or do FlushFinalBlock ).
// This will tell it that we have done our decryption
// and there is no more data coming in,
// and it is now a good time to remove the padding
// and finalize the decryption process.
//cs.Close();
cs.FlushFinalBl ock();

// Now get the decrypted data from the MemoryStream.
// Some people make a mistake of using GetBuffer() here,
// which is not the right way.
byte[] decryptedData = ms.ToArray();

return decryptedData;
}

/// <summary>
/// Decrypt a string into a string using a password
/// </summary>
/// <param name="cipherTex t"></param>
/// <param name="Password" ></param>
/// <returns></returns>
public static string decrypt(string cipherText, string Password)
{
// First we need to turn the input string into a byte array.
// We presume that Base64 encoding was used
byte[] cipherBytes = Convert.FromBas e64String(ciphe rText);

// Then, we need to turn the password into Key and IV
// We are using salt to make it harder to guess our key
// using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveB ytes pdb = new PasswordDeriveB ytes(Password,
new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

// Now get the key/IV and do the decryption using
// the function that accepts byte arrays.
// Using PasswordDeriveB ytes object we are first
// getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes)
// and then 16 bytes for the IV.
// IV should always be the block size, which is by
// default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is
// 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off
// the algorithm to find out the sizes.
byte[] decryptedData = decrypt(cipherB ytes,
pdb.GetBytes(32 ), pdb.GetBytes(16 ));

// Now we need to turn the resulting byte array into a string.
// A common mistake would be to use an Encoding class for that.
// It does not work
// because not all byte values can be represented by characters.
// We are going to be using Base64 encoding that is
// designed exactly for what we are trying to do.
return System.Text.Enc oding.Unicode.G etString(decryp tedData);
}

Jun 27 '06 #1
0 3383

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

Similar topics

3
29305
by: Jimski | last post by:
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.FlushFinalBlock.
1
5366
by: gane kol | last post by:
Hi I am using DES algorithm. I am getting an error message in a few cases of the querystring Error Message : Length of the data to decrypt is invalid. Error Method : System.String Decrypting(System.String) Error Line: strDecrpt = sr.ReadToEnd(); QueryString Data:
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
3078
by: dba123 | last post by:
am getting the following error when a sub domain is receiving a shared cookie: I have this in both web.config of each application. The 1.1 application does not have the decryption= value because you cannot have that for 1.1 or asp.net will error out. The source application is coded in .NET 2.0 but the target application that's sharing the source app's cookie is a .NET 1.1 app. <machineKey...
1
8053
by: Sathyaish | last post by:
I have the following scenario: Algorithm: 3DES Cipher Mode: CBC Key Size: 128-bit Block Size: 64 bit IV: 0x0000000000000000 (an eight byte array of zeros) The results I get using .NET with the following routine are:
4
6240
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 :)
4
5715
by: Fritjolf | last post by:
Hi. I've got a strange problem... I've made a simple program to test encryption/decryption. I use Rijndael encryption and here are the most important properties. RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = 256; cipher.BlockSize = 256;
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
13
3609
by: Tom Andrecht | last post by:
I'm trying to get some encryption/decryption routines going to take care of my data, and while the encryption is working great, I keep running into the message "Padding is invalid and cannot be removed" on the decryption piece. From everything I can see, I am doing things correctly here My code is as follows: private const string PassStr = "MyPrivateKey"; private static readonly byte PassSalt = new byte { Byte Byte Byte Byte Byte};...
0
9990
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
9837
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10850
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
10941
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
8032
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
7185
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6074
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4698
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
3
3300
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.