473,406 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

TripleDESCryptoServiceProvider bad data error

JC
Hi all,

I have seem few messages posted regaring this but as yet have been
able to get this code to work. The plan was to encrypt some string
then pass the result to another function that woudl decrypt it -
please see below. Anyway i keep getting a 'bad data' exception. I'm
totally at a loss, so any help woudl be greatly appreciated.

public Byte[] myEncrypt()
{
UTF8Encoding utf8encoder = new UTF8Encoding();
Byte[] inputBytes = utf8encoder.GetBytes(txtToDb.Text);
//Console.WriteLine(inputBytes.ToString());

TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform =
tdesProvider.CreateEncryptor(tripleDes.Key,tripleD es.IV);

MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(encryptedStream,cryptoTransform,Crypt oStreamMode.Write);

cryptStream.Write(inputBytes,0,inputBytes.Length);
cryptStream.FlushFinalBlock();
encryptedStream.Position = 0;

Byte[] bResult = new Byte[encryptedStream.Length-1];
encryptedStream.Read(bResult,0,int.Parse(encrypted Stream.Length.ToString())-1);
cryptStream.Close();
myDecrypt(bResult);
return bResult;
}
static string myDecrypt(Byte[] inputInBytes)
{
//UTF8Encoding utf8encoder = new UTF8Encoding();
TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();

ICryptoTransform cryptoTranform =
tdesProvider.CreateDecryptor(tripleDes.Key,tripleD es.IV);

MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(decryptedStream,cryptoTranform,Crypto StreamMode.Write);
cryptStream.Write(inputInBytes,0,inputInBytes.Leng th);
cryptStream.FlushFinalBlock();
decryptedStream.Position=0;

Byte[] result = new Byte[decryptedStream.Length-1];
decryptedStream.Read(result,0,int.Parse(decryptedS tream.Length.ToString()));
cryptStream.Close();

UTF8Encoding myutf = new UTF8Encoding();
return myutf.GetString(result).ToString();
}
Nov 15 '05 #1
4 10089
JC <ja*********@btinternet.com> wrote:
I have seem few messages posted regaring this but as yet have been
able to get this code to work. The plan was to encrypt some string
then pass the result to another function that woudl decrypt it -
please see below. Anyway i keep getting a 'bad data' exception. I'm
totally at a loss, so any help woudl be greatly appreciated.


Firstly, you're converting a MemoryStream to a byte array in a
roundabout way: the best way is to use MemoryStream.ToArray, which you
can even call after it's closed.

Secondly, there's no need to instantiate the UTF8Encoding - just use
Encoding.UTF8 which returns a singleton instance reference.

Having said that, I can't immediately see why it's likely to be
failing. Could you post a short but complete program which demonstrates
the problem?

See http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that.

I've looked at a few problems like this recently - I think it may be
time to write a page about it...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Hi John,

Thanks for your reply. I have recreated a bare bones version to run and
show the error in a console app.

here's the code.

using System;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;

namespace demoEncrtptionForNewsGroup
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
myEncrypt();
}
public class tripleDes
{
public static byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
public static byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

}
static void myEncrypt()
{
UTF8Encoding utf8encoder = new UTF8Encoding();
Byte[] inputBytes = utf8encoder.GetBytes("please encrypt me!");

TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform =
tdesProvider.CreateEncryptor(tripleDes.Key,tripleD es.IV);

MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(encryptedStream,cryptoTransform,Crypt oStreamMode.Write);

cryptStream.Write(inputBytes,0,inputBytes.Length);
cryptStream.FlushFinalBlock();
encryptedStream.Position = 0;

Byte[] bResult = new Byte[encryptedStream.Length-1];
encryptedStream.Read(bResult,0,int.Parse(encrypted Stream.Length.ToStr
ing())-1);
cryptStream.Close();
myDecrypt(bResult);
}
static void myDecrypt(Byte[] inputInBytes)
{
TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();

ICryptoTransform cryptoTranform =
tdesProvider.CreateDecryptor(tripleDes.Key,tripleD es.IV);

MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(decryptedStream,cryptoTranform,Crypto StreamMode.Write);
cryptStream.Write(inputInBytes,0,inputInBytes.Leng th);
cryptStream.FlushFinalBlock();
decryptedStream.Position=0;

Byte[] result = new Byte[decryptedStream.Length-1];
decryptedStream.Read(result,0,int.Parse(decryptedS tream.Length.ToStri
ng()));
cryptStream.Close();

UTF8Encoding myutf = new UTF8Encoding();
Console.WriteLine(myutf.GetString(result).ToString ());
}
}
}

I hope this is what you were after, and thanks for you help.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #3
James Crane <ja*********@btinternet.com> wrote:
Thanks for your reply. I have recreated a bare bones version to run and
show the error in a console app.
Right. The problem is really simple - sorry I didn't spot it before.

For some reason, you've decided to miss off the last byte of each of
the encrypted and decrypted data:
Byte[] bResult = new Byte[encryptedStream.Length-1];
encryptedStream.Read(bResult,0,int.Parse
(encryptedStream.Length.ToString())-1);


If you just use MemoryStream.ToArray instead, all is well.

I have to ask though - why were you converting the length into a string
and then parsing it? Why not just cast the long to an int?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4


Hi Jon,

I have taken your advice and and now using MemoryStream.ToArray instead
and have removed the -1 and it works fine.

To be totally honest, the reason why I didnt cast the orinigal values is
because I'm still quite new to c# and wasnt thinking - I'll know for
next time.

Thanks for you help.

I've including the full working listing below for anyone else who needs
a reference.
using System;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;

namespace demoEncrtptionForNewsGroup
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
myEncrypt();
}
public class tripleDes
{
public static byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
public static byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

}
static void myEncrypt()
{
UTF8Encoding utf8encoder = new UTF8Encoding();
Byte[] inputBytes = utf8encoder.GetBytes("please encrypt me!");

TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform =
tdesProvider.CreateEncryptor(tripleDes.Key,tripleD es.IV);

MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(encryptedStream,cryptoTransform,Crypt oStreamMode.Write);

cryptStream.Write(inputBytes,0,inputBytes.Length);
cryptStream.FlushFinalBlock();
encryptedStream.Position = 0;

Byte[] bResult = new Byte[encryptedStream.Length];
encryptedStream.Read(bResult,0,encryptedStream.ToA rray().Length);
cryptStream.Close();
myDecrypt(bResult);
}
static void myDecrypt(Byte[] inputInBytes)
{
TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();

ICryptoTransform cryptoTranform =
tdesProvider.CreateDecryptor(tripleDes.Key,tripleD es.IV);

MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(decryptedStream,cryptoTranform,Crypto StreamMode.Write);
cryptStream.Write(inputInBytes,0,inputInBytes.Leng th);
cryptStream.FlushFinalBlock();
decryptedStream.Position=0;

Byte[] result = new Byte[decryptedStream.Length];
decryptedStream.Read(result,0,decryptedStream.ToAr ray().Length);
cryptStream.Close();

UTF8Encoding myutf = new UTF8Encoding();
Console.WriteLine(myutf.GetString(result).ToString ());
while(Console.Read()!='q');

}
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #5

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

Similar topics

3
by: dave | last post by:
Hello there, I am at my wit's end ! I have used the following script succesfully to upload an image to my web space. But what I really want to be able to do is to update an existing record in a...
10
by: Gregory A Greenman | last post by:
I'm trying to write a program in vb.net to automate filling out a series of forms on a website. There are three forms I need to fill out in sequence. The first one is urlencoded. My program is...
4
by: Ced | last post by:
Hi, i'm not an expert in C but i try to compile BTNG software under linux kernel 2.4.2-2. I get these errors at the very first stage. Does someone could have a rapid look on this and tell me...
5
by: petro | last post by:
Hello all, My asp.net web application works on my machine but I get the following error on our test web server, There is only one oracle home on the test server. Does anyone know how to resolve...
6
by: Alex | last post by:
Hi, I am using TripleDESCryptoServiceProvider to encrypt a value in the querystring and my only concern is whether will the ampersand character appear in an encrypted string. Using POST is...
18
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning...
18
by: robert | last post by:
Is there a ready made function in numpy/scipy to compute the correlation y=mx+o of an X and Y fast: m, m-err, o, o-err, r-coef,r-coef-err ? Or a formula to to compute the 3 error ranges? ...
4
by: Rick | last post by:
I've moved code from a stage machine to the production machine, exact same code works fine on the stage machine, they are both windows 2003 servers, I'm getting a "Cannot generate SSPI context"...
0
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.