【发布时间】:2018-09-05 04:00:43
【问题描述】:
我正在 .txt 文件中编写一个加密的 (Rijndael) 字节数组。 当我读出来时,我得到一个字节[48]。一旦我解密它,我就会得到一个字节[32]。
为什么我会在这里丢失字节?如果我在控制台中写入结果,它也会在特定点切割。
static void ShowEntries()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = path + @"\SafePass\";
byte[] file = File.ReadAllBytes(path + @"\crypt.txt");
using (MemoryStream memory = new MemoryStream(file))
{
using (BinaryReader binary = new BinaryReader(memory))
{
byte[] result = binary.ReadBytes(file.Length);
byte[] plainText = new byte[48];
plainText = Decrypt(result);
string SplainText = Converter(plainText);
Console.WriteLine(SplainText);
}
}
}
static string Converter(byte[] data)
{
string base64 = Convert.ToBase64String(data);
return base64;
}
static byte[] Decrypt(byte[] encryptedByte)
{
{
string password = @"mykey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
MemoryStream mem = new MemoryStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(mem,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Write);
cs.Write(encryptedByte, 0, encryptedByte.Length);
byte[] cipherText = null;
cipherText = mem.ToArray();
cs.Close();
return cipherText;
}
}
【问题讨论】:
-
在 cs.Close() 之前添加 cs.Flush()
-
使用
File.ReadAllText和File.WriteAllBytes进行加密,使用File.ReadAllBytes和File.WriteAllText进行解密。我也认为BinaryReader和ShowEntries中的MemoryStream没有用。您已经使用File.ReadAllBytes读取了字节,只需传递该变量
标签: c#