472,952 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,952 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 2267
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
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.