在特定字节索引处序列化对象

时间:2016-11-17 17:36:57

标签: c# encryption serialization

VS2015中,我想将数据表序列化为文件,从byte 16开始,因为文件要加密而IV使用bytes 0-15。我还没有找到一个带偏移参数的序列化方法,所以我应该将表转换为字节数组吗?必须有一个更清洁的方法。以下是其中一项功能:

internal static void EncryptData(DataTable dTable, string userName, string password, string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
    {
        using (Aes aes = SetAes(userName, password)) // simply performs aes initialization
        {
            fs.Write(aes.IV, 0, 16); // writing the IV
            using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                dTable.WriteXml(cs, XmlWriteMode.WriteSchema); // This is overwriting the bytes 0-15 :(
            }
        }
    }
}

编辑:添加反序列化函数,抛出异常“要解密的数据长度无效”

internal static void DecryptData(DataTable dTable, string userName, string password, string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Open))
    {
        byte[] IV = new byte[16];
        fs.Read(IV, 0, 16);
        using (Aes aes = SetAes(userName, password, IV)) // simply setting aes
        {
            using (CryptoStream cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read))
            {
                dTable.ReadXml(cs);
            }
        }
    }
}

FINAL EDIT:解决方案:使用File.WriteAllBytes添加IV字节,并在序列化方法(EncryptData)中使用FileStream filemode.Append:

    using (Aes aes = SetAes(userName, password))
    {
        File.WriteAllBytes(fileName, aes.IV);
        using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None))
        {                                       
            using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                dTable.WriteXml(cs, XmlWriteMode.WriteSchema);                                                                                                                                       
            }
        }
    }

0 个答案:

没有答案