TriplesDes corrputing in SQL database

J

JC

Hi,

I have had a couple of postings regarding this topic already and some
very helpfull advice for which I am very gratefull indeed.

However, I am still getting some really odd behaviour from my
encryption routines. As an overview I have one function that takes a
string and encrypts it (thank you Jon for help here). Another function
that accepts byte[] and decrypts it. These two functions (below)
appear to work reliably. However, when I store the results of the
encrypt function in a SQL database (varbinary 128) then try to decrypt
it, the results are not reliable.

For example, sometimes the decryption is fine, then with exactly the
same data in the database it will error with 'bad data', then
sometimes it will jumble the result. I am only encrypting 4 characters
so varbinary 128 is large enough, and the results are being brought
back in a dataset, then into a DataRow, then the items I need
decypingting are passed to the function. But, for instance, just now I
loaded the web page and intially the results errored, then with a page
refresh it all worked fine.

Totally confused so help would be so appreciated.

James

public Byte[] myEncrypt(string sInput)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(sInput);

TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform =
tdesProvider.CreateEncryptor(tripleDes.Key,tripleDes.IV);

MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(encryptedStream,cryptoTransform,CryptoStreamMode.Write);

cryptStream.Write(inputBytes,0,inputBytes.Length);
cryptStream.FlushFinalBlock();
encryptedStream.Position = 0;

Byte[] bResult = encryptedStream.ToArray();
cryptStream.Close();
return bResult;
}
public string myDecrypt(Byte[] inputInBytes)
{
try
{
TripleDESCryptoServiceProvider tdesProvider = new
TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTranform =
tdesProvider.CreateDecryptor(tripleDes.Key,tripleDes.IV);

MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptStream = new
CryptoStream(decryptedStream,cryptoTranform,CryptoStreamMode.Write);
cryptStream.Write(inputInBytes,0,inputInBytes.Length);
cryptStream.FlushFinalBlock();
decryptedStream.Position=0;

Byte[] result = decryptedStream.ToArray();
//Byte[] result = new Byte[decryptedStream.Length];
//decryptedStream.Read(result,0,decryptedStream.ToArray().Length);
cryptStream.Close();

return Encoding.UTF8.GetString(result).ToString();
}
catch(Exception ex)
{
return "error";
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top