473,778 Members | 1,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

TripleDES String Encrypt/Decrypt Problem

I'm having trouble encrypting/decrypting a simple string using the
System.Security .Cryptography.T ripleDESCryptoS erviceProvider, etc...

The encryption works, but the decryption does not properly decrypt
several of the first few characters.

Here's the code:

class TMyCipher
{
public string Encipher(string s, string key)
{
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(k ey);
TripleDESCrypto ServiceProvider TripleDesProv = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m ict = TripleDesProv.C reateEncryptor( bKey,null);
byte[] bInput = ASCIIEncoding.A SCII.GetBytes(s );
byte[] bOutput = ict.TransformFi nalBlock(bInput ,0,bInput.Lengt h);
System.Console. WriteLine(Syste m.Text.Encoding .ASCII.GetStrin g(bOutput,0,bOu tput.Length));
return Convert.ToBase6 4String(bOutput ,0,bOutput.Leng th);
}

public string Decipher(string ciphertext, string key)
{
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(k ey);
TripleDESCrypto ServiceProvider TripleDesDec = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m Decryptor =
TripleDesDec.Cr eateDecryptor(b Key,null);
System.Console. WriteLine(ciphe rtext);
byte[] eInput = Convert.FromBas e64String(ciphe rtext);
System.Console. WriteLine(Syste m.Text.Encoding .ASCII.GetStrin g(eInput,0,eInp ut.Length));
byte[] eOutput =
Decryptor.Trans formFinalBlock( eInput,0,eInput .Length);
return System.Text.Enc oding.ASCII.Get String(eOutput, 0,eOutput.Lengt h);
}
}

string ClearText = "test-text-this-is-text";

string sKey = "mykey";
sKey = sKey.PadRight(1 6,' ');
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(s Key);
TMyCipher ciph = new TMyCipher();
string ciphertext = ciph.Encipher(C learText,sKey);
System.Console. WriteLine(ciphe rtext);
string sFinal = ciph.Decipher(c iphertext,sKey) ;
System.Console. WriteLine("Fina l: " + sFinal);

The result:

G)♠SK|YS
M♀H)←b ↨\
r2xpLw1HKQbTy/zZh9MKTYzIqZtiC Rfc
r2xpLw1HKQbTy/zZh9MKTYzIqZtiC Rfc
G)♠SK|YS
M♀H)←b ↨\
Final: I'|htT<#t-this-is-text
Nov 15 '05 #1
8 13540
<wk****@yahoo.c om> wrote:
I'm having trouble encrypting/decrypting a simple string using the
System.Security .Cryptography.T ripleDESCryptoS erviceProvider, etc...

The encryption works, but the decryption does not properly decrypt
several of the first few characters.


<snip>

The problem is that you're giving it more in one block than you should.
Rather than using the transform directly, I suggest you use the
CryptoStream API. That way you don't need to worry about block sizes
etc.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in message news:<MP******* *************** **@msnews.micro soft.com>...

The problem is that you're giving it more in one block than you should.
Rather than using the transform directly, I suggest you use the
CryptoStream API. That way you don't need to worry about block sizes
etc.


Thank you. I've tried to implement a simple solution using a
CryptoStream, but the results are almost identical:

My ClearText String
d!U#CP↕?¶XgN☼q% ♀U∟o→
ZCHVo3eIQ1AShz+ UWOdOj3GlDNUcbx oN <-- After Base64 Encoding.

d!U#CP↕?¶XgN☼q% ♀U∟o→
My CleSRText String <-- After Decryption.
^^^^

Here's my code. Thanks again.

static void Main(string[] args)
{
string sKey = "MyKey";
sKey = sKey.PadRight(1 6,' ');
string sInit = "123456";
byte[] bInit = ASCIIEncoding.A SCII.GetBytes(s Init);
string ClearText = "My ClearText String";
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(s Key);
byte[] buffer = ASCIIEncoding.A SCII.GetBytes(C learText);
byte[] rbuffer;

System.Console. WriteLine(Clear Text);
TripleDESCrypto ServiceProvider tdc = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m icp = tdc.CreateEncry ptor(bKey,bInit );
System.IO.Memor yStream ms = new System.IO.Memor yStream();
CryptoStream cs = new CryptoStream(ms ,icp,CryptoStre amMode.Write);
cs.Write(buffer ,0,buffer.Lengt h);
cs.Close();
rbuffer = ms.ToArray();
System.Console. WriteLine(ASCII Encoding.ASCII. GetString(rbuff er,0,rbuffer.Le ngth));
string CipherText =
Convert.ToBase6 4String(rbuffer ,0,rbuffer.Leng th);
System.Console. WriteLine(Ciphe rText);
System.Console. ReadLine();
ms.Close();

System.IO.Memor yStream dms = new System.IO.Memor yStream();
byte[] eBuffer = Convert.FromBas e64String(Ciphe rText);
System.Console. WriteLine(ASCII Encoding.ASCII. GetString(eBuff er,0,eBuffer.Le ngth));
dms.Write(eBuff er,0,eBuffer.Le ngth);
dms.Seek(0,Syst em.IO.SeekOrigi n.Begin);

TripleDESCrypto ServiceProvider ddc = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m dcp = ddc.CreateDecry ptor(bKey,bInit );
CryptoStream dcs = new CryptoStream(dm s,dcp,CryptoStr eamMode.Read);
byte[] cBuffer = new byte[eBuffer.Length];
dcs.Read(cBuffe r,0,eBuffer.Len gth);
dcs.Close();
System.Console. WriteLine(ASCII Encoding.ASCII. GetString(cBuff er,0,cBuffer.Le ngth));
dms.Close();
string cText = ASCIIEncoding.A SCII.GetString( cBuffer,0,cBuff er.Length);
System.Console. WriteLine(cText );
System.Console. ReadLine();
}
Nov 15 '05 #3
You need to use CryptoStream.Fl ushFinalBlock before closing the crypto
stream after writing.

<wk****@yahoo.c om> wrote in message
news:2e******** *************** ***@posting.goo gle.com...
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in message news:<MP******* *************** **@msnews.micro soft.com>...

The problem is that you're giving it more in one block than you should.
Rather than using the transform directly, I suggest you use the
CryptoStream API. That way you don't need to worry about block sizes
etc.


Thank you. I've tried to implement a simple solution using a
CryptoStream, but the results are almost identical:

My ClearText String
d!U#CP↕?¶XgN☼q% ♀U∟o→
ZCHVo3eIQ1AShz+ UWOdOj3GlDNUcbx oN <-- After Base64 Encoding.

d!U#CP↕?¶XgN☼q% ♀U∟o→
My CleSRText String <-- After Decryption.
^^^^

Here's my code. Thanks again.

static void Main(string[] args)
{
string sKey = "MyKey";
sKey = sKey.PadRight(1 6,' ');
string sInit = "123456";
byte[] bInit = ASCIIEncoding.A SCII.GetBytes(s Init);
string ClearText = "My ClearText String";
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(s Key);
byte[] buffer = ASCIIEncoding.A SCII.GetBytes(C learText);
byte[] rbuffer;

System.Console. WriteLine(Clear Text);
TripleDESCrypto ServiceProvider tdc = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m icp = tdc.CreateEncry ptor(bKey,bInit );
System.IO.Memor yStream ms = new System.IO.Memor yStream();
CryptoStream cs = new CryptoStream(ms ,icp,CryptoStre amMode.Write);
cs.Write(buffer ,0,buffer.Lengt h);
cs.Close();
rbuffer = ms.ToArray();

System.Console. WriteLine(ASCII Encoding.ASCII. GetString(rbuff er,0,rbuffer.Le n
gth)); string CipherText =
Convert.ToBase6 4String(rbuffer ,0,rbuffer.Leng th);
System.Console. WriteLine(Ciphe rText);
System.Console. ReadLine();
ms.Close();

System.IO.Memor yStream dms = new System.IO.Memor yStream();
byte[] eBuffer = Convert.FromBas e64String(Ciphe rText);
System.Console. WriteLine(ASCII Encoding.ASCII. GetString(eBuff er,0,eBuffer.Le n
gth)); dms.Write(eBuff er,0,eBuffer.Le ngth);
dms.Seek(0,Syst em.IO.SeekOrigi n.Begin);

TripleDESCrypto ServiceProvider ddc = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m dcp = ddc.CreateDecry ptor(bKey,bInit );
CryptoStream dcs = new CryptoStream(dm s,dcp,CryptoStr eamMode.Read);
byte[] cBuffer = new byte[eBuffer.Length];
dcs.Read(cBuffe r,0,eBuffer.Len gth);
dcs.Close();
System.Console. WriteLine(ASCII Encoding.ASCII. GetString(cBuff er,0,cBuffer.Le n
gth)); dms.Close();
string cText = ASCIIEncoding.A SCII.GetString( cBuffer,0,cBuff er.Length);
System.Console. WriteLine(cText );
System.Console. ReadLine();
}

Nov 15 '05 #4
<wk****@yahoo.c om> wrote:
Thank you. I've tried to implement a simple solution using a
CryptoStream, but the results are almost identical:


Well, one of the problems which may well be everything in fact is that
you're using Stream.Read and assuming that it will completely fill the
buffer you've specified. You're also assuming that the encrypted length
is the same as the unencrypted length.

Rather than using CryptoStreamMod e.Read, I find it easier to use
CryptoStreamMod e.Write again, and write into a memory stream.

Here's some working code I wrote for someone else the other day - it
uses a straight DESCryptoServic eProvider, but I'm sure you can change
that part.

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

public class Working
{
DESCryptoServic eProvider provider;

Working()
{
provider = new DESCryptoServic eProvider();
provider.Genera teKey();
provider.Genera teIV();
}

byte[] Encrypt (string text)
{
byte[] encodedText = Encoding.UTF8.G etBytes (text);
ICryptoTransfor m transform = provider.Create Encryptor();

using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream
(ms, transform, CryptoStreamMod e.Write))
{
cs.Write (encodedText, 0, encodedText.Len gth);
cs.FlushFinalBl ock();
}

return ms.ToArray();
}
}

string Decrypt (byte[] data)
{
ICryptoTransfor m transform = provider.Create Decryptor();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream (ms,
transform, CryptoStreamMod e.Write))
{
cs.Write (data, 0, data.Length);
cs.FlushFinalBl ock();
}
return Encoding.UTF8.G etString (ms.ToArray());
}
}

static void Main()
{
Working w = new Working();

Console.WriteLi ne (w.Decrypt(w.En crypt
("Some text to be encrypted and then decrypted")));
}
}
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
Bret Mulvey <br***@online.m icrosoft.com> wrote:
You need to use CryptoStream.Fl ushFinalBlock before closing the crypto
stream after writing.


Actually, if you close a CryptoStream without flushing the final block,
it'll flush it for you. Not a bad idea to make it clear though.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Bret Mulvey <br***@online.m icrosoft.com> wrote:
You need to use CryptoStream.Fl ushFinalBlock before closing the crypto
stream after writing.


Actually, if you close a CryptoStream without flushing the final block,
it'll flush it for you. Not a bad idea to make it clear though.


That's what I thought, but I tried his example and reproduced problem. Using
Close without FlushFinalBlock corrupted the data, and with FlushFinalBlock
before Close it resolved the problem. I was able to see this in his code as
well as a separate example I created.

In a decompilation of CryptoStream.Cl ose I can clearly see where it calls
FlushFinalBlock , but only conditionally. Perhaps the TripleDES encryptor
doesn't correctly set this flag.
Nov 15 '05 #7

"Bret Mulvey" <br***@online.m icrosoft.com> wrote in message
news:3f******** @news.microsoft .com...

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Bret Mulvey <br***@online.m icrosoft.com> wrote:
You need to use CryptoStream.Fl ushFinalBlock before closing the crypto
stream after writing.
Actually, if you close a CryptoStream without flushing the final block,
it'll flush it for you. Not a bad idea to make it clear though.


That's what I thought, but I tried his example and reproduced problem.

Using Close without FlushFinalBlock corrupted the data, and with FlushFinalBlock
before Close it resolved the problem. I was able to see this in his code as well as a separate example I created.

In a decompilation of CryptoStream.Cl ose I can clearly see where it calls
FlushFinalBlock , but only conditionally. Perhaps the TripleDES encryptor
doesn't correctly set this flag.


Never mind, I can't back this up. I just re-ran my test that illustrated
this and it's not behaving the same so I must have made some other change.
It does look like the problem is on the reading side.
Nov 15 '05 #8
your problem is that you do not provide "good" IV in

TripleDesProv.C reateEncryptor( bKey, null);

if you put the same array for encr and decr, it works fine:
private byte[] bIV;
...
bIV = str2bytes("tXes terX");

// and use

ict = tProvider.Creat eEncryptor(bKey , bIV);

// and

ict = tProvider.Creat eDecryptor(bKey , bIV);

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

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

Similar topics

0
3089
by: Jonas | last post by:
I have the following perl program witch i use to encrypt a password file with. In perl 5.6 this program works like a charm but when trying it on the RED HAT EL 3 platform (taroon) is doesnt decrypt the encrypted string right. Program use Crypt::TripleDES; sub generate() {
7
5494
by: c duden | last post by:
I am attempting to encrypt some text and be able to decrypt it at a later time. I have two methods to do this: public static Byte EncryptText(string textToEncrypt, string encryptionHash) { Byte bytearrayinput = StringAndByteManipulation.ConvertStringToByteArray(textToEncrypt); //DES instance System.Security.Cryptography.TripleDESCryptoServiceProvider des = new
7
17879
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");
5
1589
by: jdn | last post by:
I'm new to using this part of the framework, so I'm hoping I've done something obviously stupid, which someone will be able to point out in an obvious manner. Most of the samples I've seen involved encrypting and decrypting to and from a file, but that's not what I want. I want to be able to insert a string into an encryption function which outputs that encrypted string, which could then be sent into a decryption function and spit out...
2
30546
by: GRB | last post by:
A client wants me to decrypt a cookie. They encrypted the data in java using TripleDES. The key provided is a 168 bit 44 character key, DESede alogorithm. Ive tried to decrypt in vb.net and get the above error. Below is the class I use and the code I use to call it. Not sure wher I'm going wrong here. The TripleDES service provider only uses a 192 bit 24 character length key. Any help would be greatly appreciated.
1
1310
by: d4v3y0rk | last post by:
i have a class i found/wrote (meaning i found it originally and tinkered with it to make it mine) and i would like some suggestions on how to make it better. i am looking for things i need to add, weaknesses, whatnot. Thanks in advance. ----------------------------------------------------------------------------------------------------------------- Imports System.Security.Cryptography Imports System.Security Imports System.Text
0
3298
by: intersoln | last post by:
Hi, I tried encrypting and decrypting a string using the following Java code and key. And was successful. Then, I used the following C# to encrypt and decrypt a string using the following C# code and key. And was successful. But when i tried to encrypted using java and decrypted using C#, but it was not successful. Can someone please help? THanks in advanced.
0
9629
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
10127
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
10068
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,...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8954
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7474
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
6723
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
5370
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...
3
2863
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.