473,408 Members | 1,955 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,408 software developers and data experts.

Beginning Crypto question

I have some code that converts a string into base64 for some
encryption.
It was written on the 1.1 framework but I am trying to get it to work
on 2.0. It throws exceptions on the cryptStream.FlushFinalBlock() and
cryptStream.Clear(). Can anyone tell me what is up with this?
Thanks ahead of time for any help you can offer.

public static string EncryptAndBase64( string val )
{
byte[] buf = UnicodeEncoding.Unicode.GetBytes(val);

MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream, enc3des,
CryptoStreamMode.Write);

cryptStream.Write(buf, 0, buf.Length);
cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);

buf = memStream.GetBuffer();
val = Convert.ToBase64String(buf, 0, (int)memStream.Length);
Array.Clear(buf, 0, (int)memStream.Length);
return val;
}

public static object DecryptFromBase64( object val )
{
if( val.Equals( DBNull.Value ) )
return DBNull.Value;

return DecryptFromBase64( (string)val );
}

public static string DecryptFromBase64( string base64str )
{
byte[] buf = Convert.FromBase64String(base64str);
MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream, dec3des,
CryptoStreamMode.Write );

cryptStream.Write(buf, 0, buf.Length);
cryptStream.FlushFinalBlock();
cryptStream.Clear();

Array.Clear(buf, 0, buf.Length);
buf = memStream.GetBuffer();

string ret = UnicodeEncoding.Unicode.GetString(buf, 0,
(int)memStream.Length);
Array.Clear(buf, 0, (int)memStream.Length);
memStream.Close();

return ret;
}

Mar 15 '07 #1
6 1798
SenseiHitokiri <se************@gmail.comwrote:
I have some code that converts a string into base64 for some
encryption.
It was written on the 1.1 framework but I am trying to get it to work
on 2.0. It throws exceptions on the cryptStream.FlushFinalBlock() and
cryptStream.Clear(). Can anyone tell me what is up with this?
Thanks ahead of time for any help you can offer.
Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
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
Mar 15 '07 #2
hmm I swore I posted the code up in here but I don't see it. Well here
it is again. C#

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

namespace DebugCrypto
{
class DebugCrypto
{
static void Main(string[] args)
{
DebugCrypto x = new DebugCrypto();
Console.Read();
}
void Program()
{
string base64str = "FmcT1N0kYX/IId4m6GuYpg=="; //string to
decrypt
ICryptoTransform dec3des = SetupCrypto();
byte[] buf = Convert.FromBase64String(base64str);

System.IO.MemoryStream memStream = new
System.IO.MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream,
dec3des, CryptoStreamMode.Write);

cryptStream.Write(buf, 0, buf.Length);
try
{
cryptStream.FlushFinalBlock(); //This is what
errors out
cryptStream.Clear(); // and this
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Array.Clear(buf, 0, buf.Length);
buf = memStream.GetBuffer();

Console.WriteLine(UnicodeEncoding.Unicode.GetStrin g(buf,
0, (int)memStream.Length));

Array.Clear(buf, 0, (int)memStream.Length);
memStream.Close();
}

ICryptoTransform SetupCrypto()
{
TripleDESCryptoServiceProvider des3 = new
TripleDESCryptoServiceProvider();

byte[] salt =
System.Text.UTF8Encoding.UTF8.GetBytes("testKey"); //Encryption key
SHA1 hash = new SHA1Managed();
for (int i = 0; i < 200; ++i)
{
salt = hash.ComputeHash(salt, 0, salt.Length);
hash.Initialize();
}
PasswordDeriveBytes pdb = new
PasswordDeriveBytes("testKey", salt, "SHA512", 1000);
Array.Clear(salt, 0, salt.Length);
hash.Clear();

byte[] key3des = pdb.GetBytes(24);
byte[] iv3des = pdb.GetBytes(8);

return( des3.CreateDecryptor(key3des, iv3des) );
}
}
}

Mar 19 '07 #3
SenseiHitokiri <se************@gmail.comwrote:
hmm I swore I posted the code up in here but I don't see it. Well here
it is again. C#
<snip>

Well, the exception (after putting in a call to x.Program() - your
program as posted does nothing :) suggests that the data is invalid.
We'll need to see a short but complete program that produces that data
to start with, too.

--
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
Mar 20 '07 #4
On Mar 20, 3:05 am, Jon Skeet [C# MVP] <s...@pobox.comwrote:
SenseiHitokiri <senseihitok...@gmail.comwrote:
hmm I swore I posted the code up in here but I don't see it. Well here
it is again. C#

<snip>

Well, the exception (after putting in a call to x.Program() - your
program as posted does nothing :) suggests that the data is invalid.
We'll need to see a short but complete program that produces that data
to start with, too.

--
Jon Skeet - <s...@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
Hmm... that may be a little harder. I'm taking over this code from
someone else and at the moment that is in a seperate app that I do not
have access to. I can try to rip out the encrypt code from this
program and throw it up here but that may take me a bit to discern
it. Damn I wish he gave me some documentation lol.

Mar 20 '07 #5
Ok give this a whirl. It generates the encrypted string and prints it
to the screen but then gives me a bad data error when trying to
decrypt.

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

namespace DebugCrypto
{
class DebugCrypto
{
ICryptoTransform enc3des, dec3des;
byte[] key3des = null;
byte[] iv3des = null;

static void Main(string[] args)
{
DebugCrypto x = new DebugCrypto();
string read = Console.ReadLine();
while ( read != "exit" )
{
string encrypted = x.EncryptAndBase64(read);

Console.WriteLine("Encrypting: ");
Console.WriteLine(encrypted);
Console.WriteLine("Decrypting: ");
Console.WriteLine(x.DecryptFromBase64(encrypted));
Console.WriteLine("\n");
}
}

public DebugCrypto()
{
string sKey = "testKey";

TripleDESCryptoServiceProvider des3 = new
TripleDESCryptoServiceProvider();

byte[] salt =
System.Text.UTF8Encoding.UTF8.GetBytes(sKey);
SHA1 hash = new SHA1Managed();
for (int i = 0; i < 200; ++i)
{
salt = hash.ComputeHash(salt, 0, salt.Length);
hash.Initialize();
}
PasswordDeriveBytes pdb = new PasswordDeriveBytes(sKey,
salt, "SHA512", 1000);
Array.Clear(salt, 0, salt.Length);
hash.Clear();

key3des = pdb.GetBytes(24);
iv3des = pdb.GetBytes(8);

enc3des = des3.CreateEncryptor(key3des, iv3des);
dec3des = des3.CreateDecryptor(key3des, iv3des);
des3.Clear();
}

public string EncryptAndBase64(string val)
{
byte[] buf = UnicodeEncoding.Unicode.GetBytes(val);

MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream,
enc3des, CryptoStreamMode.Write);

cryptStream.Write(buf, 0, buf.Length);
int memLength = (int)memStream.Length;

cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);

buf = memStream.GetBuffer();
val = Convert.ToBase64String(buf, 0, memLength );
Array.Clear(buf, 0, memLength );
return val;
}

public string DecryptFromBase64(string base64str)
{
byte[] buf = Convert.FromBase64String(base64str);
MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream,
dec3des, CryptoStreamMode.Write);

cryptStream.Write(buf, 0, buf.Length);
int memLength = (int)memStream.Length;

cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);
buf = memStream.GetBuffer();

string ret = UnicodeEncoding.Unicode.GetString(buf, 0,
memLength);
Array.Clear(buf, 0, memLength );
memStream.Close();
return ret;
}
}
}

Mar 21 '07 #6
SenseiHitokiri <se************@gmail.comwrote:
Ok give this a whirl. It generates the encrypted string and prints it
to the screen but then gives me a bad data error when trying to
decrypt.
The encryption is broken:
public string EncryptAndBase64(string val)
{
byte[] buf = UnicodeEncoding.Unicode.GetBytes(val);

MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream,
enc3des, CryptoStreamMode.Write);

cryptStream.Write(buf, 0, buf.Length);
int memLength = (int)memStream.Length;

cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);

buf = memStream.GetBuffer();
val = Convert.ToBase64String(buf, 0, memLength );
Array.Clear(buf, 0, memLength );
return val;
}
Note how it works out the length of memStream *before* it flushes the
final block. Just move that line to *after* cryptStream.FlushFinalBlock
(and do the same in the decryption) and it works. However, it's not the
nicest way of doing it. It's simpler to use MemoryStream.ToArray to get
the buffer, rather than asking for the length at all. I would
personally write the decryption code as (the encryption side mirrors
it, of course):

public string DecryptFromBase64(string base64str)
{
byte[] buf = Convert.FromBase64String(base64str);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cryptStream = new CryptoStream
(memStream, dec3des, CryptoStreamMode.Write))
{
cryptStream.Write(buf, 0, buf.Length);
// I don't think this is necessary in .NET 2.0
// but it is in 1.1 due to a bug in CryptoStream,
// IIRC
cryptStream.FlushFinalBlock();
}

byte[] decrypted = memStream.ToArray();

return Encoding.Unicode.GetString(decrypted);
}
}

--
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
Mar 21 '07 #7

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

Similar topics

0
by: Simon Roses Femerling | last post by:
Hey all :) I'm looking for a good crypto toolkit (that should be multiplatform, work on python 2.3, etc..) What I have found looks old and too complex (installing 3 party libs, etc.) I just want...
1
by: Stu | last post by:
Hi, Im reading a file in from disk as a byte array then passing it to a memory stream for decryption using crypto api functions. What I have found is that you need to reduce the array length by 2...
2
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to...
6
by: Michael Sparks | last post by:
Hi, I suspect this is a bug with AMK's Crypto package from http://www.amk.ca/python/code/crypto , but want to check to see if I'm being dumb before posting a bug report. I'm looking at...
13
by: Andy Chau | last post by:
I try to use RSA to implement the following scheme but wasn't sucessful. Sever encrypt a message using a public key, the client decrpyt the message using a private key. I don't want the client...
2
by: Mark | last post by:
I have been playing around with encrypting passwords using a class found in a MS KB (see farther down). It seems to work great so long as the original password is comprised of characters on the...
0
by: Slug | last post by:
Hello all, I've been trying to get a public key solution working but have been having a few problems. For starters there is a lot of contradictory information out there, MSDN is not much help,...
5
by: vermarajeev | last post by:
Hi guys, I want to encrypt/decrypt a file with AES in CTR mode using crypto++ library. To encrypt a file using AES in CTR mode the solution is something like this int CRYPTOPP_API...
2
by: vermarajeev | last post by:
Hi guys, I have written code to encrypt and decrypt files using perl script. Please help me to port below code to crypto++ library. //ENCRYPTION my $cipher = Crypt::CBC->new( -cipher =>...
12
by: Fett | last post by:
I need a crypto package that works on windows with python 2.5. Can anyone suggest one for me? I have been searching for a couple days for a good cryptography package to use for public/private...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.