Thursday, March 7, 2024

Encrypt/Decrypt the App.Config

Program.cs
using System;
using System.Diagnostics;
using System.IO;
namespace EncryptAppConfig
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string aspNetRegIisPath = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\";
            var configFile = "C:\\Users\\SamalSub\\Desktop\\EncryptAppConfig\\BSS.SubApp.App1.exe.config";
            var path = Path.GetDirectoryName(configFile);
            var webConfigFile = Path.Combine(path, "Web.config");
            //Rename to web.config
            if (File.Exists(configFile)) File.Move(configFile, webConfigFile);
            //Encrypt appSettings
            var tagCmd = $"aspnet_regiis -pef appSettings {path}";
            //tagCmd = $"aspnet_regiis -pdf appSettings {path}";
            var encryptTagCmdLine = $"{aspNetRegIisPath}{tagCmd}";
            ExecuteEncryptCmd(encryptTagCmdLine);
            //Rename to ***.exe.config
            if (File.Exists(webConfigFile)) File.Move(webConfigFile, configFile);
            Console.ReadKey();
        }
        private static void ExecuteEncryptCmd(string encryptTagCmdLine)
        {
            var startInfo = new ProcessStartInfo("cmd", "/c " + encryptTagCmdLine)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };
            var process = Process.Start(startInfo);
            while (!process.StandardOutput.EndOfStream)
            {
                Console.WriteLine(process.StandardOutput.ReadLine());
            }
            process.Close();
        }
    }
}


EncryptAppConfig.ps1
[CmdletBinding()]
Param(   
    [parameter(Mandatory=$false, HelpMessage="Encrypt the secure app settings")]
    [switch]$Encrypt,
    [parameter(Mandatory=$false, HelpMessage="Decrypt the secure app settings")]
    [switch]$Decrypt
)
$ErrorActionPreference = "Stop"
function Get-EncryptionMode()
{
    if($Encrypt.IsPresent -and $Decrypt.IsPresent) { Write-Error "Use either -Encrypt or -Decrypt" }
    if($Decrypt.IsPresent)
    { 
        return "Decrypt"
    }
    
    return "Encrypt"
}
function Find-ConfigurationFile()
{
    $configFiles  = @(Get-ChildItem -Filter "*.exe.config")
    $configFiles += @(Get-ChildItem -Filter "App.config")
    if($configFiles.Count -gt 1) { Write-Error ("Found more than one configuration file: {0}" -f [string]::Join(", ", $configFiles.Name)) }
    if($configFiles.Count -ne 1) { Write-Error "Could not find the .config file" }
    return $configFiles.Get(0)
}
function Get-DotNetFrameworkDirectory()
{
    $([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory())
}
function Copy-ToTempWebConfig($configurationFile)
{
    if (!(Test-Path -path ".\temp")) 
    {
        Write-Verbose ("Creating temp directory {0}" -f ".\temp")
        New-Item ".\temp" -Type Directory
    }
    Copy-Item $configurationFile "temp\Web.config"
    return Get-Item "temp\Web.config"
}
function Copy-FromTempWebConfig($configurationFile)
{
    Move-Item "temp\Web.config" $configurationFile -Force | Out-Null
    if((Get-ChildItem ".\temp").Count -eq 0)
    {
        Write-Verbose ("Removing empty temp directory {0}" -f ".\temp")
        Remove-Item ".\temp"
    }
}
function Encrypt-ConfigurationSection([string] $configurationPath, $mode){  
  $currentDirectory = (Get-Location)
  Set-Location (Get-DotNetFrameworkDirectory)
  if($mode -eq "Decrypt")
  {
    .\aspnet_regiis -pdf "secureAppSettings" "$configurationPath"
  } else
  {
    .\aspnet_regiis -pef "secureAppSettings" "$configurationPath"
  }
  Set-Location $currentDirectory
}
$mode = Get-EncryptionMode
$configurationFile = (Find-ConfigurationFile)
Write-Verbose ("{0} configuation file {1}" -f $mode, $configurationFile.FullName)
$tempFile = Copy-ToTempWebConfig $configurationFile
Write-Verbose ("Attempting to {0} {1}" -f $mode, $configurationFile.FullName)
Encrypt-ConfigurationSection $tempFile.Directory.FullName $mode
Copy-FromTempWebConfig $configurationFile
InPowershell
./EncryptAppConfig.ps1

Monday, January 15, 2024

What's new in C# 12

 C# 12 includes the following new features. You can try these features using the latest Visual Studio 2022 version or the .NET 8 SDK.

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...