我想解密一个长字节[],但是我无法做到这一点。
接收代码:我直接从流中读取bitmap
(按预期方式工作),然后使用byte[]
将其转换为MemoryStream
,然后解密整个byte[]
,然后解密的数据应该变成bitmap
:
Bitmap bmpTmp = BitmapFactory.DecodeStream(CommunicationHandler.GetStream());
MemoryStream stream = new MemoryStream();
bmpTmp.Compress(Bitmap.CompressFormat.Png, 100, stream);
string imageString = DecryptStringFromBytes_Aes(stream.ToArray());
顺便说一句,我将流读入bitmap
然后将其转换为byte[]
而不是将流读入byte[]
的唯一原因是找不到任何将NetworkStream
读入byte[]
的函数。
我想知道BitmapFactory.DecodeStream()
是如何工作的?该功能如何读取全部数据?它怎么知道什么时候停止?
解密代码:
public static string DecryptStringFromBytes_Aes(byte[] cipherTextCombined)
{
string plaintext = null;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Mode = CipherMode.CBC;
byte[] IV = new byte[16];
byte[] cipherText = new byte[cipherTextCombined.Length - IV.Length];
Array.Copy(cipherTextCombined, IV, IV.Length);
Array.Copy(cipherTextCombined, IV.Length, cipherText, 0, cipherText.Length);
aesAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd(); //The error occurs here:
//System.ArgumentException: Offset and length were out of bounds for the array or count is
//greater than the number of elements from index to the end of the source collection.
}
return plaintext.TrimEnd('\0');
}
加密代码:
def encrypt(self, message):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(str.encode(self.key), AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
填充代码:
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
这是我通过NetworkStream发送的内容:
import mss.tools
def screenshot():
with mss.mss() as sct:
return sct.grab(sct.monitors[1])
socket.send(mss.tools.to_png(image.rgb, image.size))
根据我得到的错误-System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
,我认为输入太长。这是错误堆栈跟踪:at Project.LoadingImage.RunInBackground (Java.Lang.Void[] params) [0x0004d]
。
请注意,方法和系统在简单和简短的输入下都能完美地工作,但是唯一的问题是图像,可能是由于错误提示,byte[]
输入太大了。
此外,请注意,解密方法返回string
而不返回byte[]
,这使得将其解码为bitmap
更加复杂。
最后,有3个主要问题:
错误是什么意思?我该如何解决?
BitmapFactory.DecodeStream()
如何读取整个流?
是否可以将解密函数的返回类型从byte[]
更改为string
?