Retention policy and crypto

I just deleted an old post because I re-read it and I was attempting my own crypto on config files instead of using DPAPI. I reserve the right to delete old posts if they turn out to be complete bollocks.

Just to show how you encrypt an app config file on a machine where you do not have IIS installed and cannot use the traditional aspnet_regiis command-line tool that your first googlebing will tell you all about – I give you the below piece of code.

Note that you need to encrypt the file on the target machine as DPAPI is machine specific, so there will be a brief moment when the file is on disk in clear text which is a basic flaw of the entire DPAPI concept, but at least you are not rolling your own crypto.

static int Main(string[] args)
{
    if (args.Length != 1)
        Console.Error.WriteLine("Wrong number of arguments.\r\n{0} <configfile_to_encrypt>", GetExeName());

    return EncyptAppSettings(args[0]);
}

private static int EncyptAppSettings(string pathToFile)
{
    if (!File.Exists(pathToFile))
         return LogFatalError(string.Format("Executable {0} not found", pathToFile), 2);
    if (!File.Exists(pathToFile + ".config"))
         return LogFatalError(string.Format("Config file {0} not found", pathToFile), 3);

   var configuration = ConfigurationManager.OpenExeConfiguration(pathToFile);
   var appSettings = configuration.GetSection("appSettings") as AppSettingsSection;
   appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
   appSettings.SectionInformation.ForceSave = true;
   configuration.Save();
   return 0;
}

private static int LogFatalError(string message, int exitCode)
{
    Console.Error.WriteLine("{0} failed: {1}", GetExeName(), message);
    return exitCode;
}

private static string GetExeName()
{
    return Process.GetCurrentProcess().ProcessName;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *