转换为字符串时,我有一个额外的问号 这是我的代码:
我的加密方法:
public static Stream EncryptStream(Stream inputStream)
{
string key = "ThisIsMySuperSecureKey";
byte[] keyBytes = Encoding.UTF32.GetBytes(key);
Rfc2898DeriveBytes derviedKey = new Rfc2898DeriveBytes(key, keyBytes);
RijndaelManaged rijndaelCSP = new RijndaelManaged();
rijndaelCSP.Key = derviedKey.GetBytes(rijndaelCSP.KeySize / 8);
rijndaelCSP.IV = derviedKey.GetBytes(rijndaelCSP.BlockSize / 8);
var encryptor = rijndaelCSP.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
//inputStream.Position = 0;
byte[] toEncrypt = StreamToByteArray(inputStream);
cs.Write(toEncrypt, 0, toEncrypt.Length);
cs.FlushFinalBlock();
MemoryStream output = new MemoryStream(ms.ToArray());
ms.Close();
return (Stream)output;
}
我将流转换为字节数组的方法:
public static byte[] StreamToByteArray(Stream inputStream)
{
var ms = new MemoryStream();
inputStream.Position = 0;
inputStream.CopyTo(ms);
return ms.ToArray();
}
public static Stream DecryptStream(Stream inputStream)
{
string key = "ThisIsMySuperSecureKey";
byte[] keyBytes = Encoding.UTF32.GetBytes(key);
Rfc2898DeriveBytes derviedKey = new Rfc2898DeriveBytes(key, keyBytes);
RijndaelManaged rijndaelCSP = new RijndaelManaged();
rijndaelCSP.Key = derviedKey.GetBytes(rijndaelCSP.KeySize / 8);
rijndaelCSP.IV = derviedKey.GetBytes(rijndaelCSP.BlockSize / 8);
var decryptor = rijndaelCSP.CreateDecryptor();
byte[] arrayOfEncrypedStream = StreamToByteArray(inputStream);
MemoryStream ms = new MemoryStream(arrayOfEncrypedStream);
CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
cs.Read(arrayOfEncrypedStream, 0, arrayOfEncrypedStream.Length);
MemoryStream output = new MemoryStream(ms.ToArray());
ms.Close();
return output;
}
我检查Stream是否已加密的方法:
public static string IsCryptedStream(Stream cryptedStream)
{
string result = "";
byte[] convStremToBytes = Encryption.StreamToByteArray(cryptedStream);
return result = Encoding.UTF32.GetString(convStremToBytes);
}
我在这个问题上阅读了类似的文章,但它没有成功。需要帮忙。谢谢!!!
更新
static void Main(string[] args)
{
byte[] streamBytes = Encoding.Unicode.GetBytes("Hello people");
MemoryStream ms = new MemoryStream(streamBytes);
var cryptedStream = Encryption.EncryptStream(ms);
var decryptStream = Encryption.DecryptStream(cryptedStream);
string isCryptedStreamAfterDecryption =
Demo3.IsCryptedStream(decryptStream);
Console.WriteLine($"After Decryption: {isCryptedStreamAfterDecryption}");
}
结果:“Hello people ???”