C# .NET文件解密-错误数据
我正在重写一个旧的应用程序。旧应用程序将数据存储在记分板文件中,该文件使用以下代码加密:C# .NET文件解密-错误数据,c#,.net,cryptography,encryption,C#,.net,Cryptography,Encryption,我正在重写一个旧的应用程序。旧应用程序将数据存储在记分板文件中,该文件使用以下代码加密: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard();
private const String SSecretKey = @"?B?n?Mj?";
public DataTable GetScoreboardFromFile()
{
FileInfo f = new FileInfo(scoreBoardLocation);
if (!f.Exists)
{
return setupNewScoreBoard();
}
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desdecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
DataTable dTable = new DataTable("scoreboard");
dTable.ReadXml(new StreamReader(cryptostreamDecr));
cryptostreamDecr.Close();
fsread.Close();
return dTable;
}
这个很好用。我已经将代码复制到我的新应用程序中,这样我就可以创建一个遗留加载程序,并将数据转换为新格式。问题是我得到了一个“坏数据”错误:
System.Security.Cryptography.CryptographyException未处理
Message=“错误数据。\r\n”
Source=“mscorlib”
该错误将在此行触发:
dTable.ReadXml(new StreamReader(cryptostreamDecr));
加密文件是今天用旧代码在同一台机器上创建的。我猜加密/解密过程可能使用了应用程序名/文件或其他东西,因此意味着我无法打开它
是否有人有以下想法:
A) 你能解释为什么这不起作用吗?
B) 请提供一个解决方案,使我能够打开使用旧应用程序创建的文件并能够转换它们
下面是处理加载和保存记分板的整个类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.IO;
using System.Data;
using System.Xml;
using System.Threading;
namespace JawBreaker
{
[Serializable]
class ScoreBoardLoader
{
private Jawbreaker jawbreaker;
private String sSecretKey = @"?B?n?Mj?";
private String scoreBoardFileLocation = "";
private bool keepScoreBoardUpdated = true;
private int intTimer = 180000;
public ScoreBoardLoader(Jawbreaker jawbreaker, String scoreBoardFileLocation)
{
this.jawbreaker = jawbreaker;
this.scoreBoardFileLocation = scoreBoardFileLocation;
}
// Call this function to remove the key from memory after use for security
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
// Function to Generate a 64 bits Key.
private string GenerateKey()
{
// Create an instance of Symetric Algorithm. Key and IV is generated automatically.
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
// Use the Automatically generated key for Encryption.
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
public void writeScoreboardToFile()
{
DataTable tempScoreBoard = getScoreboardFromFile();
//add in the new scores to the end of the file.
for (int i = 0; i < jawbreaker.Scoreboard.Rows.Count; i++)
{
DataRow row = tempScoreBoard.NewRow();
row.ItemArray = jawbreaker.Scoreboard.Rows[i].ItemArray;
tempScoreBoard.Rows.Add(row);
}
//before it is written back to the file make sure we update the sync info
if (jawbreaker.SyncScoreboard)
{
//connect to webservice, login and update all the scores that have not been synced.
for (int i = 0; i < tempScoreBoard.Rows.Count; i++)
{
try
{
//check to see if that row has been synced to the server
if (!Boolean.Parse(tempScoreBoard.Rows[i].ItemArray[7].ToString()))
{
//sync info to server
//update the row to say that it has been updated
object[] tempArray = tempScoreBoard.Rows[i].ItemArray;
tempArray[7] = true;
tempScoreBoard.Rows[i].ItemArray = tempArray;
tempScoreBoard.AcceptChanges();
}
}
catch (Exception ex)
{
jawbreaker.writeErrorToLog("ERROR OCCURED DURING SYNC TO SERVER UPDATE: " + ex.Message);
}
}
}
FileStream fsEncrypted = new FileStream(scoreBoardFileLocation, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
MemoryStream ms = new MemoryStream();
tempScoreBoard.WriteXml(ms, XmlWriteMode.WriteSchema);
ms.Position = 0;
byte[] bitarray = new byte[ms.Length];
ms.Read(bitarray, 0, bitarray.Length);
cryptostream.Write(bitarray, 0, bitarray.Length);
cryptostream.Close();
ms.Close();
//now the scores have been added to the file remove them from the datatable
jawbreaker.Scoreboard.Rows.Clear();
}
public void startPeriodicScoreboardWriteToFile()
{
while (keepScoreBoardUpdated)
{
//three minute sleep.
Thread.Sleep(intTimer);
writeScoreboardToFile();
}
}
public void stopPeriodicScoreboardWriteToFile()
{
keepScoreBoardUpdated = false;
}
public int IntTimer
{
get
{
return intTimer;
}
set
{
intTimer = value;
}
}
public DataTable getScoreboardFromFile()
{
FileInfo f = new FileInfo(scoreBoardFileLocation);
if (!f.Exists)
{
jawbreaker.writeInfoToLog("Scoreboard not there so creating new one");
return setupNewScoreBoard();
}
else
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(scoreBoardFileLocation, FileMode.Open, FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desdecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
DataTable dTable = new DataTable("scoreboard");
dTable.ReadXml(new StreamReader(cryptostreamDecr));
cryptostreamDecr.Close();
fsread.Close();
return dTable;
}
}
public DataTable setupNewScoreBoard()
{
//scoreboard info into dataset
DataTable scoreboard = new DataTable("scoreboard");
scoreboard.Columns.Add(new DataColumn("playername", System.Type.GetType("System.String")));
scoreboard.Columns.Add(new DataColumn("score", System.Type.GetType("System.Int32")));
scoreboard.Columns.Add(new DataColumn("ballnumber", System.Type.GetType("System.Int32")));
scoreboard.Columns.Add(new DataColumn("xsize", System.Type.GetType("System.Int32")));
scoreboard.Columns.Add(new DataColumn("ysize", System.Type.GetType("System.Int32")));
scoreboard.Columns.Add(new DataColumn("gametype", System.Type.GetType("System.String")));
scoreboard.Columns.Add(new DataColumn("date", System.Type.GetType("System.DateTime")));
scoreboard.Columns.Add(new DataColumn("synced", System.Type.GetType("System.Boolean")));
scoreboard.AcceptChanges();
return scoreboard;
}
private void Run()
{
// For additional security Pin the key.
GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned);
// Remove the Key from memory.
ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
gch.Free();
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Security.Cryptography;
使用System.Runtime.InteropServices;
使用System.IO;
使用系统数据;
使用System.Xml;
使用系统线程;
名称空间断颚器
{
[可序列化]
类记分板加载器
{
私家断颚器;
私有字符串sSecretKey=@?B?n?Mj;
私有字符串scoreBoardFileLocation=“”;
私有bool keepScoreBoardUpdated=true;
私有整数定时器=180000;
公共记分板加载程序(Jawbreaker Jawbreaker、字符串记分板文件位置)
{
this.jawbreaker=jawbreaker;
this.scoreBoardFileLocation=scoreBoardFileLocation;
}
//为安全起见,使用后调用此函数从内存中取出密钥
[System.Runtime.InteropServices.DllImport(“KERNEL32.DLL”,EntryPoint=“RtlZeroMemory”)]
公共静态外部布尔零内存(IntPtr目的地,int长度);
//函数生成64位密钥。
私有字符串GenerateKey()
{
//创建对称算法的实例。密钥和IV自动生成。
DESCryptoServiceProvider desCrypto=(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
//使用自动生成的密钥进行加密。
返回ascienceoding.ASCII.GetString(desCrypto.Key);
}
公共无效写入CoreboardToFile()
{
DataTable tempScoreBoard=getScoreboardFromFile();
//将新分数添加到文件末尾。
for(int i=0;i