HalfEvil
HalfEvil

Reputation: 113

Load byte array from string isn't working correctly?

I'm trying to encrypt a string, save it in a file and then later read the string from the file and decrypt it. But when I run the code I just get "length of the data to decrypt is invalid" error :/ By debugging I manged to find out that the byte array (array^ bytes) for some reason has a length of 12 when I try to decrypt the string, and it has a length of 8 when I encrypt the string.

Here is the code to encrypt the string:

String^ EncryptS(){
String^ DecryptedS;
MD5CryptoServiceProvider^ md5Crypt = gcnew MD5CryptoServiceProvider();
UTF8Encoding^ utf8Crypt = gcnew UTF8Encoding();
TripleDESCryptoServiceProvider^ crypt = gcnew TripleDESCryptoServiceProvider();
crypt->Key = md5Crypt->ComputeHash(utf8Crypt->GetBytes("123"));
crypt->Mode = CipherMode::ECB;
crypt->Padding = PaddingMode::PKCS7;
ICryptoTransform^ transCrypt = crypt->CreateEncryptor();    
DecryptedS = utf8Crypt->GetString(transCrypt->TransformFinalBlock(utf8Crypt->GetBytes(form1::passwordTextBox->Text), 0, utf8Crypt->GetBytes(form1::passwordTextBox->Text)->Length));
return DecryptedS; }

And here is the code to decrypt the string

String^ decryptS(String^ encryptedS){
String^ decryptedS;
array<Byte>^ bytes;
MD5CryptoServiceProvider^ md5Crypt = gcnew MD5CryptoServiceProvider();
UTF8Encoding^ utf8Crypt = gcnew UTF8Encoding();
UTF8Encoding^ utf8ToByte = gcnew UTF8Encoding();
TripleDESCryptoServiceProvider^ crypt = gcnew TripleDESCryptoServiceProvider();
crypt->Key = md5Crypt->ComputeHash(utf8Crypt->GetBytes("123"));
crypt->Mode = CipherMode::ECB;
crypt->Padding = PaddingMode::PKCS7;
ICryptoTransform^ transCrypt = crypt->CreateDecryptor();
bytes = utf8ToByte->GetBytes(encryptedS);
return decryptedS = utf8Crypt->GetString(transCrypt->TransformFinalBlock(bytes, 0, bytes->Length)); }

I've been trying to fix this in hours now, but with no success, help would be much appreciated :)

Sorry for my bad English.

Upvotes: 1

Views: 244

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502796

You're trying to convert an arbitrary byte array into a string using UTF-8. That's like trying to load some random text file as if it were a JPEG, and expecting it to be a valid image.

You should only use Encoding.GetString(byte[]) when the byte array really is text encoded with that encoding.

If you want to represent "arbitrary" binary data (which compressed or encrypted data typically is) you should use base64 or perhaps hex, depending on your requirements. (Convert.ToBase64String and Convert.FromBase64String are your friends.)

Upvotes: 4

Related Questions