473,566 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this how Encryption/Decryption Really works ?

Hi,

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

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";

SymmetricAlgori thm myAlg = new RijndaelManaged ();

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

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

myAlg.Key = passwordKey.Get Bytes(myAlg.Key Size / 8);
myAlg.IV = passwordKey.Get Bytes(myAlg.Blo ckSize / 8);

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

ICryptoTransfor m myEncrypter = myAlg.CreateEnc ryptor();

MemoryStream mStream = new MemoryStream();

CryptoStream csEncrypt = new CryptoStream(mS tream, myEncrypter,
CryptoStreamMod e.Write);

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

csEncrypt.Flush FinalBlock();
csEncrypt.Close ();
mStream.Close() ;

byte[] EncryptedData = mStream.ToArray ();

//
// De-Encrypt the Data
//

string Password1 = "password1" ;

SymmetricAlgori thm myAlg1 = new RijndaelManaged ();

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

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

myAlg1.Key = passwordKey1.Ge tBytes(myAlg1.K eySize / 8);
myAlg1.IV = passwordKey1.Ge tBytes(myAlg1.B lockSize / 8);
ICryptoTransfor m myDecryptor = myAlg1.CreateDe cryptor();

MemoryStream msOutput = new MemoryStream(En cryptedData);

CryptoStream DecryptStream = new CryptoStream(ms Output,
myDecryptor, CryptoStreamMod e.Read);

StreamReader sr = new StreamReader(De cryptStream);

string ab = sr.ReadLine();
Console.WriteLi ne(ab);
Console.ReadLin e();
}
}
}


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 2299
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(De cryptStream);
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**@discussio ns.microsoft.co m> 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.co m>
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
4265
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 appreciated: $handle = fopen("/home/public_html/testfolder/test.txt","r"); $buffer = fgets($handle, 4096); fclose($handle); // Encryption/decryption key...
1
2457
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 occurs in the application when you instantiate a new instance of the class as shown below: ---Dim dp As DPAPIComp.DataProtectorComp = New...
2
4186
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 opening the app the following wrror is generated: Exception decrypting. Decryption failed. Key not valid for use in specified state. Description: An...
25
2373
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 of encryption, but then the problem is, how do I decrypt it on the server to store it? If I use some type of key based encryption, the how do I...
8
2723
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. ...
4
5676
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 = new RijndaelManaged(); cipher.KeySize = 256; cipher.BlockSize = 256;
0
2362
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 functions work fine when Two random prime numbers (required to generate public n private key) are within certain range but fails afterwords.All the...
5
9491
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 code for a few hours: #dics Encryption={',':'hy{;',' ':'h4x0r2','':'zomg','?':'bko','a':'ika','b':'d0v','c':'ino', 'd':'maw', 'e':'aon', 'f':'que',...
9
4810
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 . I didn't test script on windows. Here is the code, please send me your views. <?php /* Mother Eye Chipper with PHP :), Licence:GPL,
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8108
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...
1
7644
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...
0
7951
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...
0
6260
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...
1
5484
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2083
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1201
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.