I have two functions that should encrypt and decrypt a given file:
public static void Encrypt(string name, string skey)
{
using (var sourceStream = File.OpenRead(name))
using (var destinationStream = File.Create(name + ".sav"))
using (var provider = new AesCryptoServiceProvider())
using (var cryptoTransform = provider.CreateEncryptor())
using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write))
{
provider.Padding = PaddingMode.None;
List<byte> key = new List<byte>();
key.AddRange(ASCIIEncoding.ASCII.GetBytes(skey));
while (key.Count < 32)
{
key.Add(0);
}
provider.Key = key.ToArray();
destinationStream.Write(provider.IV, 0, provider.IV.Length);
sourceStream.CopyTo(cryptoStream);
}
}
public static void Decrypt(string name, string skey)
{
// Decrypt the source file and write it to the destination file.
using (var sourceStream = File.OpenRead(name + ".sav"))
using (var destinationStream = File.Create(name))
using (var provider = new AesCryptoServiceProvider())
{
provider.Padding = PaddingMode.None;
List<byte> key = new List<byte>();
key.AddRange(ASCIIEncoding.ASCII.GetBytes(skey));
while(key.Count < 32)
{
key.Add(0);
}
var IV = new byte[provider.IV.Length];
sourceStream.Read(IV, 0, IV.Length);
using (var cryptoTransform = provider.CreateDecryptor(key.ToArray(), IV))
using (var cryptoStream = new CryptoStream(sourceStream, cryptoTransform, CryptoStreamMode.Read))
{
cryptoStream.CopyTo(destinationStream);
}
}
}
Using the text document (d):
<?xml version="1.0" encoding="utf-8"?>
<Game xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<username>d</username>
<superSecretString>foo</superSecretString>
</Game>
The following program:
static void Main(string[] args)
{
string pass = "foo";
Encrypt("d", pass);
Decrypt("d", pass);
}
Results in the text document (d):
豄襚釞뮲冋ⵂૠɥ摸▪穨嶾⏘ﳿ僣ꙍ帏પ軆ꝍ遨䄩䰀玢⊟尩㯇Ўꉚ파 駧㪡襻긗몸뵊➯턊鏶㠌늸㗐蕛貣ㆪⲫ咻ꨱ壉뷢䅱眡�׀罹吗㶝�晊垚猰Ġ�淧脽ᣉ赮榑舎㈁쾹͂쵎숵戥힠┻蔦쬦눲ꔲ빬䁔㸻�ⵄ➞ޅ㥿࠾ऱ룮2侚神ヵ튙腶㖮衦ྗ
It seems that decrypting the message is causing the unexpected result however I don't what I should expect in the "*.sav" files besides random noise. Checking the watchlist provider.key is an array that reads out 102, 111, 111, 0 ... 0 in both Encrypt and Decrypt methods.