Reputation: 99
how do you store AES key to file and then retrieve it?
I have tried saving it as string to a text file then retrieve it back and convert it to byte, but the decryption never works…
using (var provider = new AesCryptoServiceProvider())
{
var cryptoTransform = provider.CreateEncryptor();
Key = provider.Key;
IV = provider.IV;
string key_string = Encoding.ASCII.GetString(Key);
File.WriteAllText(@"C:\Documents\AES\Key.txt", key_string);
string string_key = System.IO.File.ReadAllText(@"C:\Documents\AES\Key.txt");
testKey_bytes = Encoding.ASCII.GetBytes(string_key); ;
Upvotes: 1
Views: 1302
Reputation: 631
As mentioned before you can save it using File.WriteAllBytes() and read it back using File.ReadAllBytes().
But you also have to store the IV (at least in CBC mode). This can be done via the BinaryReader and BinaryWriter. Please be assured that your key will be stored in a safe place:
private static void SaveIVAndKey(AesCryptoServiceProvider provider)
{
using (FileStream fileStream = new FileStream("YourKeyFile.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
{
binaryWriter.Write(provider.IV.Length);
binaryWriter.Write(provider.IV);
binaryWriter.Write(provider.Key.Length);
binaryWriter.Write(provider.Key);
}
}
}
To read it back in, you can use the following method:
private static void LoadIVAndKey(AesCryptoServiceProvider provider)
{
using (FileStream fileStream = new FileStream("YourKeyFile.txt", FileMode.Open, FileAccess.Read))
{
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
provider.IV = binaryReader.ReadBytes(binaryReader.ReadInt32());
provider.Key = binaryReader.ReadBytes(binaryReader.ReadInt32());
}
}
}
Upvotes: 3
Reputation: 99
I've managed to work it out:)
File.WriteAllBytes(@"C:\Documents\AES\Key.txt", Key.ToArray());
testKey_bytes = File.ReadAllBytes(@"C:\Documents\AES\Key.txt");
Upvotes: -1