好的,我一直在尝试加密和解密文件一段时间,但我不断收到此异常
System.Security.Cryptography.CryptographicException:参数不正确。
它完美地写入了文件,并且字节数组确实有合法的条目。但是当我尝试解密时仍然会抛出这个问题。
这是整个功能:
private static void loadTimes()
{
try
{
short[] encShorts = new short[bestTimes.Length / 2];
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("test.txt", FileMode.Open, FileAccess.ReadWrite, store);
StreamReader stmReader = new StreamReader(stream);
int i = 0;
while (!stmReader.EndOfStream)
{
encShorts[i] = short.Parse(stmReader.ReadLine());
i++;
}
stmReader.Close();
byte[] encBytes = new byte[bestTimes.Length];
for (int j = 0; j < encShorts.Length; j++)
{
encBytes[j * 2] = (byte)(encShorts[j] / 256);
encBytes[j * 2 + 1] = (byte)(encShorts[j] % 256);
}
bestTimes = ProtectedData.Unprotect(encBytes, null);
checkForTimeAds();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
基本上它是从文件中加载以获得游戏中的最佳时间分数,并且由于它们是短裤,我将它们分成两个位。
以下代码引发异常:
bestTimes = ProtectedData.Unprotect(encBytes, null);
我到处看了看,似乎很多人还没有解决它,有些人说“比赛条件”,但我不完全确定这是否适用于此。为什么我会收到此异常?
Jon Skeet 要求的保存代码:
private static void saveTimes()
{
try
{
byte[] encResult = ProtectedData.Protect(bestTimes, null);
short[] encShorts = new short[bestTimes.Length / 2];
for (int i = 0; i < encShorts.Length; i++)
{
encShorts[i] = (short) (encResult[i] * 256 + encResult[i + 1]);
}
IsolatedStorageFile store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("test.txt", FileMode.Create, FileAccess.Write, store);
StreamWriter writer = new StreamWriter(stream);
foreach (short part in encShorts)
{
writer.WriteLine(part);
}
writer.Close();
}
catch (Exception)
{
MessageBox.Show("Couldn't save the file.");
}
checkForTimeAds();
}