rijndael从文件中写入和读回密钥

时间:2011-12-08 01:46:49

标签: c#

我正在使用C#.Net 4.0。我使用rijindael类生成密钥和IV(初始化向量)。然后我将它们写入文件。当我读取文件时,IV始终是正确的,但是密钥的最后一个字节始终为零。我在写入文件之前查看了密钥并且它很好,在最后一个字节中读回来总是为零。

我尝试将填充模式设置为各种选项,但它们没有什么区别。

using (Rijndael myRijndael = Rijndael.Create())
{
    //Create keys
    try
    {
        byte[] key;
        byte[] iv;

        key = new byte[32];
        iv = new byte[16];

        theKeys.Key = myRijndael.Key;
        theKeys.IV = myRijndael.IV;

        FileStream fs = File.Create("yyy.txt");
        fs.Write(theKeys.Key, 0, theKeys.Key.Length);
        fs.Flush();
        fs.Close();

        FileStream ts = File.Open("yyy.txt", FileMode.Append);
        ts.Write(theKeys.IV, 0, theKeys.IV.Length);
        ts.Flush();
        ts.Close();


        FileStream ms = File.Open("yyy.txt", FileMode.Open);

         ms.Read(key, 0, 31);
         ms.Seek(32, 0);
         ms.Read(iv, 0, 16);
         ms.Flush();
         ms.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

2 个答案:

答案 0 :(得分:0)

// Save key and IV
using (var rijndael = new RijndaelManaged())
using (var writer = new BinaryWriter(File.Create("yyy.dat")))
{
    writer.Write(rijndael.Key, 0, 32);
    writer.Write(rijndael.IV, 0, 16);
}

// Restore key and IV
using (var rijndael = new RijndaelManaged())
using (var reader = new BinaryReader(File.OpenRead("yyy.dat")))
{
    rijndael.Key = reader.ReadBytes(32);
    rijndael.IV = reader.ReadBytes(16);
}

答案 1 :(得分:0)

问题是你只需要读取31个字节:

ms.Read(key, 0, 31);

这应该改为:

ms.Read(key, 0, 32);

此外,这可以更有效率(在此示例中不使用theKeys并仅使用本地变量):

        using (Rijndael myRijndael = Rijndael.Create())
        {
            //Create keys
            try
            {
                byte[] key;
                byte[] iv;

                key = new byte[32];
                iv = new byte[16];

                key = myRijndael.Key;
                iv = myRijndael.IV;

                using (FileStream fs = File.Create("yyy.txt"))
                {
                    fs.Write(key, 0, key.Length);
                    fs.Write(iv, 0, iv.Length);
                }

                using (FileStream ms = File.Open("yyy.txt", FileMode.Open))
                {
                    key = new byte[32];
                    iv = new byte[16];

                    ms.Read(key, 0, 32);
                    ms.Read(iv, 0, 16);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }