473,698 Members | 2,411 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a problem with encryption

This is the problem: I do not get the output I need when encoding and
decoding data using rijndael alghoritm.
Look at the code and see what the problem is actually:

Please paste this code into your Visual Studio and compile it + run it; so
you can see what the actual problem is.

Thanks.

code:

using System;
using System.IO;
using System.Text;
using System.Security .Cryptography;
namespace ConsoleApplicat ion1
{
class MyMainClass
{
public static void Main()
{
string original = "Original string";
string roundtrip;
ASCIIEncoding textConverter = new ASCIIEncoding() ;
RijndaelManaged myRijndael = new RijndaelManaged ();
byte[] fromEncrypt;
byte[] encrypted;
byte[] toEncrypt;
byte[] key;
byte[] IV;
//Create a new key and initialization vector.
myRijndael.Gene rateKey();
myRijndael.Gene rateIV();
//Get the key and IV.
key = myRijndael.Key;
IV = myRijndael.IV;
//Get an encryptor.
ICryptoTransfor m encryptor = myRijndael.Crea teEncryptor(key , IV);
//Encrypt the data.
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(ms Encrypt, encryptor,
CryptoStreamMod e.Write);
//Convert the data to a byte array.
toEncrypt = textConverter.G etBytes(origina l);
//Write all data to the crypto stream and flush it.
csEncrypt.Write (toEncrypt, 0, toEncrypt.Lengt h);
csEncrypt.Flush FinalBlock();
//Get encrypted array of bytes.
encrypted = msEncrypt.ToArr ay();

//Here I send data trough network stream
//create byte array to be sent trough tcp network
byte[] finalized = new byte[key.Length+IV.L ength+encrypted .Length];
//merge all values into single byte array
key.CopyTo(fina lized,0);
IV.CopyTo(final ized,32);
encrypted.CopyT o(finalized,48) ;
//here goes tcp code with sending the array trough network. it works fine,
and is no problem.
//For simplicitiy's sake, here i'll just simulate a new application that
uses values it got from the first application.
//SIMULATED NEW APPLICATION
//Create values that will be used in decryption process and that are passed
trough network
byte[] key1 = new byte[32];
byte[] IV1 = new byte[16];
byte[] encrypted1 = new byte[finalized.Lengt h-48];
//read all values from the passed byte array and divid those correctly.
for (int i=0; i<32; i++)
{
key1[i]=finalized[i];
}
for (int i=32; i<48; i++)
{
IV1[i-32]=finalized[i];
}
for (int i=48; i<finalized.Len gth; i++)
{
encrypted1[i-48]=finalized[i];
}
//now use values to get the result:
//Get a decryptor that uses the same key and IV as the encryptor.
ICryptoTransfor m decryptor = myRijndael.Crea teDecryptor(key 1, IV1);
//Now decrypt the previously encrypted message using the decryptor
MemoryStream msDecrypt = new MemoryStream(en crypted1);
CryptoStream csDecrypt = new CryptoStream(ms Decrypt, decryptor,
CryptoStreamMod e.Read);
fromEncrypt = new byte[encrypted1.Leng th];
//Read the data out of the crypto stream.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Len gth);
//Convert the byte array back into a string.
roundtrip = textConverter.G etString(fromEn crypt);
//Display the original data and the decrypted data to see where the actual
problem is:
Console.WriteLi ne("Original string: {0}", original + "_");
Console.WriteLi ne("String I got to another application: {0}", roundtrip +
"_");
//Guess what! The result string has some dummy stuff at the end and it is
//just not the data I encoded. It is actually there, but I really don't want
//that sh*t at the end. I placed "_" sign just to see that there is a
problem with data I got.
}
}
}
Jul 21 '05
10 2347
Tonci Jukic <ny******@email .htnet.hr> wrote:
roundtrip =
textConverter.G etString(fromEn crypt).TrimEnd( Convert.ToChar( 0));

That way I always get the original data I've encrypted.

That's a bad way of doing things. Just use the return value of Read to

find out how much real data you've got, and use the form of GetString
that lets you specify how much to decode.

Well. I really don't know a way to know how long the string I send to
the server app can be. As you could see in the code, I send key, IV and
encrypted data in a byte array trough network stream. I really don't
know how to send the length of the string I encrypted to the server by
which the server would know how much to decrypt.
The only way I could think of was to trim encrypted byte array at the
very start before sending data trough network.


You don't need to trim anything. Just take note of how much decrypted
data you're actually receiving. From your original sample, all you've
got to change is:

csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Len gth);
//Convert the byte array back into a string.
roundtrip = textConverter.G etString(fromEn crypt);

to

int bytesRead = csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Len gth);
//Convert the byte array back into a string.
roundtrip = textConverter.G etString(fromEn crypt, 0, bytesRead);

(It doesn't deal with the situation where there's more data to read
than you expect, or a single call to Read doesn't return all the data.)
Yes. That's much more robust - relying on a single call to Read as you

are at the moment is a very bad idea.

How could I possible use multiple read calls? What would it give to me?


It would mean that if you send more data than the decrypting code wants
to decrypt in one call, your code would still work.
That's not your actual code, is it? Byte arrays don't have a DeCrypt

method. Please always post your *actual* code.

Well. We've got a slight problem here:)

I tried to cut\paste and edit my code here. I've translated variables
into english as I thought it would be easier for you to understand the
code.

Too bad attachments are not possible here, but here is almost the
complete code I've been using.

(I'm totally green in C# and .NET (although I've been using C++ till
now) so please don't laugh at my code. I woul appreciate any comments
and suggestions about it.)

http://www.dg.disorange.com/download/code.zip


Ah. The problem is that you changed variable names half way through -
you wrote (in your previous message) encrypted.DeCry pt() instead of
dekripted.DeCry pt(). It's always worth trying to compile the code
you're about to post. It's also worth posting short and complete code -
see http://www.pobox.com/~skeet/csharp/complete.html

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

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

Similar topics

8
18637
by: Joshua Beall | last post by:
Hi All, Up until now I have been storing passwords in the database as an sha1 hash. I like doing it this way, but a problem arises with people who forget their passwords - I cannot retrieve it for them. The simplest option would be cleartext passwords. Easy enough. But what I would prefer to do is some sort of two-way encryption, so I can encrypt the passwords, store them in the database, and then get them back. Are there any PHP...
34
4099
by: Blake T. Garretson | last post by:
I want to save some sensitive data (passwords, PIN numbers, etc.) to disk in a secure manner in one of my programs. What is the easiest/best way to accomplish strong file encryption in Python? Any modern block cipher will do: AES, Blowfish, etc. I'm not looking for public key stuff; I just want to provide a pass-phrase. I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. ...
1
8986
by: Marshall Dudley | last post by:
I have an application where I need to encrypt a bit of text, and then I need to be able to decrypt it using a customer's key. I want to make sure that the key to decrypt is NOT on the server anywhere, so hackers cannot get the decrypt key, which means I cannot use a symetrical key pair since the encryption key will need to be on the server. What I need is more like a public key cypher. But I want the customer to be able to create his...
1
7141
by: Cliff | last post by:
We are trying to connect to 3 different Oracle databases using MS Access as the front-end and ODBC as the connection. The problem that we are having is that 1 of the databases requires a CRYPTO_SEED. With the sqlnet.ora file configured for the encryption, the other 2 databases won't connect and vise versa. Is there a way to make the connections use encryption when required and not use it when not required. We are using 9i client...
7
2825
by: helmut woess | last post by:
Hi, has anybody knowledge about the safetyness of encrypting stored procs in SQL-Server 2005 using WITH ENCRYPTION? Or can they be hacked with the same old tools which exists for SQL 2000? thanks, Helmut
3
4472
by: Todd Gruben | last post by:
I am trying to send some encrypted data from a php application to be decoded in a .Net application. Both apps encode/decode a given string but generate different encrypted results. Anyone have any idea? Code to follow: php====> <?php // Designate string to be encrypted $string = "This is a test";
3
2783
by: Chuck P | last post by:
I need to deploy and asp.net 2.0 application that has dpapi/machine encrypted connection strings. I tried using the VS Build Publish menu selection and then putting the encryption in the global.asax application_start event. Unfortunately this errors because the asp.net account doesn't have write permissions to web.config. I'd rather not give permissions to the account. I tried writing a batch file to compile and then encrypt the...
11
5039
by: John Williams | last post by:
I've written a simple program to do XOR encryption as my first foray into understanding how encryption works. The code compiles fine, however it segmentation faults on every run. using gdb to debug it let me narrow the problem down to the Cipher function I think it faults at line 84 or 85. The program makes it's first read/cipher/write pass without issue but the second pass kills it. Using gdb to print the variables left showed me the...
8
2742
by: manmit.walia | last post by:
Hello Everyone, Long time ago, I posted a small problem I had about converting a VB6 program to C#. Well with the help with everyone I got it converted. But I overlooked something and don't understand why it is doing this. Below is my code, I would be greatfull if someone can guide me through the right path or even help me solve this issue. Problem: The old tool which was written in VB6 works perfect. But I needed to convert this to C#...
22
7679
by: j1mb0jay | last post by:
I have had to create a simple string encryption program for coursework, I have completed the task and now have to do a write up on how it could be improved at a later date. If you could look through the code and point me in the correct direction one would be very grateful. Example Input : j1mb0jay Example Output 1 : rZHKZbYZWn/4UgL9mAjN2DUz7X/UpcpRxXM9SO1QkvkOe5nOPEKnZldpsB7uHUNZ Example Output 2 :...
0
8685
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
9032
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...
0
8880
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
7743
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
6532
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
5869
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
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
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.