473,324 Members | 2,456 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,324 software developers and data experts.

Is this how Encryption/Decryption Really works ?

Hi,

I have been experimenting with the RijndaelManaged Cryptography class in C#
and have stumbled upon a "peculiarity".

Following code is standalone Console App that demonstrates

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

namespace EncryptTheMAC
{

class Program1
{
static void Main(string[] args)
{
string Password = "password";
string MAC = "00:01:36:09:32:88";

SymmetricAlgorithm myAlg = new RijndaelManaged();

byte[] saltValueBytes = Encoding.ASCII.GetBytes(Password);

PasswordDeriveBytes passwordKey = new
PasswordDeriveBytes(Password, saltValueBytes, "SHA1", 3);

myAlg.Key = passwordKey.GetBytes(myAlg.KeySize / 8);
myAlg.IV = passwordKey.GetBytes(myAlg.BlockSize / 8);

byte[] Data = Encoding.ASCII.GetBytes(MAC);

ICryptoTransform myEncrypter = myAlg.CreateEncryptor();

MemoryStream mStream = new MemoryStream();

CryptoStream csEncrypt = new CryptoStream(mStream, myEncrypter,
CryptoStreamMode.Write);

csEncrypt.Write(Data, 0, Data.Length);

csEncrypt.FlushFinalBlock();
csEncrypt.Close();
mStream.Close();

byte[] EncryptedData = mStream.ToArray();

//
// De-Encrypt the Data
//

string Password1 = "password1";

SymmetricAlgorithm myAlg1 = new RijndaelManaged();

byte[] saltValueBytes1 = Encoding.ASCII.GetBytes(Password1);

PasswordDeriveBytes passwordKey1 = new
PasswordDeriveBytes(Password1, saltValueBytes1, "SHA1", 3);

myAlg1.Key = passwordKey1.GetBytes(myAlg1.KeySize / 8);
myAlg1.IV = passwordKey1.GetBytes(myAlg1.BlockSize / 8);
ICryptoTransform myDecryptor = myAlg1.CreateDecryptor();

MemoryStream msOutput = new MemoryStream(EncryptedData);

CryptoStream DecryptStream = new CryptoStream(msOutput,
myDecryptor, CryptoStreamMode.Read);

StreamReader sr = new StreamReader(DecryptStream);

string ab = sr.ReadLine();
Console.WriteLine(ab);
Console.ReadLine();
}
}
}


If I change the definition of variable "Password1" to be something different
from the original value at the start of the program, the third line from the
end
string ab = sr.ReadLine();

causes an Exception

"Padding is invalid and cannot be removed"

The only way it appears that I can get around this is to put a
try...catch... around the sr.ReadLine().

I would have expected the sr.ReadLine() line to have returned random data,
not raise an exception. I have searched on MSDN and various other sources
and cannot find any thing of value. Is it possible that I am using the
cryptography API's incorrectly. Code above is duplicated in places to show
the error.

Thanks in advance

Dec 16 '05 #1
3 2287
Mike, it makes sense to me that you'd get an exception when trying to
decrypt with a different key because Rijndael is a symmetric algorithm.
That means that you must decrypt it with the same key you used for
encryption. With symmetric encryption, you encrypt using the key and
when you decrypt, you just reverse the original process, essentially.
If you don't have the same key, you can't reverse that original
transformation.

If you were encrypting/decrypting with an asymmetric algorithm (like
RSA) and you changed the key when trying to decrypt, I think you would
get the random data that you're expecting. Not with a symmetric
algorithm, though, because you're breaking the symmetry between the
encryption key and the decryption key, and the transformation would
thus fail.

I'm no encryption expert, but that's my $.02. Simon Singh's "Code
Book" is a really good resource for learning about symmetric vs.
asymmetric encryption.

Cody Powell

Dec 16 '05 #2
Thanks for response Cody.

when you word it like that, I suppose it makes sense. What I did not
understand really was why the exception, I cannot find it documented
anywhere. It also makes following code snippet fail.

StreamReader sr = new StreamReader(DecryptStream);
string ab;
try
{
ab = sr.ReadLine();
}
catch
{
ab = "BAD DATA";
}
finally
{
sr.Close();
}
return ab;
It causes another exception in the finally clause when trying to close the
StreamReader sr. It all works fine if I dont attempt any operations on the
StreamReader when the password is incorrect.

It is a shame that a status could not be returned somehow instead of the
exception every time you look at the StreamReader.

Mike

"Cody Powell" wrote:
Mike, it makes sense to me that you'd get an exception when trying to
decrypt with a different key because Rijndael is a symmetric algorithm.
That means that you must decrypt it with the same key you used for
encryption. With symmetric encryption, you encrypt using the key and
when you decrypt, you just reverse the original process, essentially.
If you don't have the same key, you can't reverse that original
transformation.

If you were encrypting/decrypting with an asymmetric algorithm (like
RSA) and you changed the key when trying to decrypt, I think you would
get the random data that you're expecting. Not with a symmetric
algorithm, though, because you're breaking the symmetry between the
encryption key and the decryption key, and the transformation would
thus fail.

I'm no encryption expert, but that's my $.02. Simon Singh's "Code
Book" is a really good resource for learning about symmetric vs.
asymmetric encryption.

Cody Powell

Dec 17 '05 #3
Mike <Mi**@discussions.microsoft.com> wrote:

<snip>
I would have expected the sr.ReadLine() line to have returned random data,
not raise an exception. I have searched on MSDN and various other sources
and cannot find any thing of value. Is it possible that I am using the
cryptography API's incorrectly. Code above is duplicated in places to show
the error.


Some cryptography algorithms always give data regardless of whether the
key is correct. Others "spot" incorrect keys, either early on or (as in
this case) spot when the stream ends in an unexpected way. If you'd
written more data, you'd be able to read garbage out for a while before
running into the exception.

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

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

Similar topics

3
by: Ralph Freshour | last post by:
I'm having trouble decrypting a file I encrypted and wrote to the server - the following code displays the $decrypted_string variable but the data is still encrypted - any help would be...
1
by: Jase H | last post by:
Hello, I have a ASP.NET web application problem involving the data encryption and decryption assembly(DLL) used on the connection string value that is set in the webconfig file. The problem...
2
by: Dave Bailey | last post by:
I have developed a web app using DPAPI to encrypt a connection string in the web.config file. The application works perfectly on the development machine but when deployed to the server when...
25
by: eggie5 | last post by:
I have a form where a user can change his password, but I'm confused on how to prevent this from being transmitted in plain text. Well, I know how not to transmit it in plain text - use any type...
8
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...
4
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 =...
0
by: Dipanwita | last post by:
I have written a RSA encryption/decryption function in c using the formula a = b^c %n. For solving the equation I have used Squaring and multiplying method for modulo exponentiation . These...
5
by: Netwatcher | last post by:
well, i started messing around with dictionaries, yet, most of the pages i found about them always talk about getting only one word out of it and turning it vice versa, i've been playing with that...
9
by: Betikci Boris | last post by:
I get bored last night and wrote a script that uses xor for encrypt- decrypt, however it woks fine under linux 2.6.25, text and documents are ok, but fails on compressed files *.jpg, *.pdf , etc ....
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.