[英]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.
但是,当我运行代码时,我只是得到“解密的数据长度无效”错误:/通过调试我管理,发现由于某种原因字节数组(数组^字节)的长度为12,当我尝试解密字符串,当我加密字符串时,它的长度为8。
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. 对不起,我的英语不好。
You're trying to convert an arbitrary byte array into a string using UTF-8. 您正在尝试使用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.
这就像尝试加载一些随机文本文件,就像它是一个JPEG,并期望它是一个有效的图像。
You should only use Encoding.GetString(byte[])
when the byte array really is text encoded with that encoding. 当字节数组确实是用该编码进行文本编码时,您应该只使用
Encoding.GetString(byte[])
。
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. 如果要表示“任意”二进制数据(通常是压缩或加密数据),则应使用base64或hex,具体取决于您的要求。 (
Convert.ToBase64String
and Convert.FromBase64String
are your friends.) (
Convert.ToBase64String
和Convert.FromBase64String
是你的朋友。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.