Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从字符串加载字节数组工作不正常?_C++_.net - Fatal编程技术网

C++ 从字符串加载字节数组工作不正常?

C++ 从字符串加载字节数组工作不正常?,c++,.net,C++,.net,我试图加密一个字符串,将其保存在一个文件中,然后从文件中读取该字符串并对其解密。但是当我运行代码时,我只得到了要解密的数据的长度是无效的错误:/通过调试,我发现字节数组^bytes由于某种原因在我尝试解密字符串时的长度为12,在我加密字符串时的长度为8 以下是加密字符串的代码: String^ EncryptS(){ String^ DecryptedS; MD5CryptoServiceProvider^ md5Crypt = gcnew MD5CryptoServiceProvider();

我试图加密一个字符串,将其保存在一个文件中,然后从文件中读取该字符串并对其解密。但是当我运行代码时,我只得到了要解密的数据的长度是无效的错误:/通过调试,我发现字节数组^bytes由于某种原因在我尝试解密字符串时的长度为12,在我加密字符串时的长度为8

以下是加密字符串的代码:

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; }
这是解密字符串的代码

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)); }
我一直试图在几个小时内解决这个问题,但没有成功,我非常感谢您的帮助:


对不起,我的英语不好

您试图使用UTF-8将任意字节数组转换为字符串。这就像试图加载一些随机的文本文件,就好像它是一个JPEG,并期望它是一个有效的图像

当字节数组实际上是使用该编码进行文本编码时,您应该只使用Encoding.GetStringbyte[]


如果要表示压缩或加密数据通常为的任意二进制数据,则应根据需要使用base64或hex。是您的朋友。

您正在尝试使用UTF-8将任意字节数组转换为字符串。这就像试图加载一些随机的文本文件,就好像它是一个JPEG,并期望它是一个有效的图像

当字节数组实际上是使用该编码进行文本编码时,您应该只使用Encoding.GetStringbyte[]

如果要表示压缩或加密数据通常为的任意二进制数据,则应根据需要使用base64或hex。他们是你的朋友