- Updated NuGet packages across projects for compatibility and bug fixes - Switched to Microsoft.OpenApi and refactored Swagger setup - Added AES encryption/decryption for connection strings - Stored encrypted DB/cache connection strings in config - Improved encryption reliability in Program.cs - Added AutoMapper to multiple projects for mapping support - Enhanced security and code maintainability
73 lines
2.8 KiB
C#
73 lines
2.8 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace KBR.Shared.Extensions
|
|
{
|
|
public static class ConfigurationExtensions
|
|
{
|
|
public static string EncryptConnectionString(this IConfiguration configuration, string plainConnectionString)
|
|
{
|
|
string keyBase64 = configuration.GetSection("ConnectionStrings:Key").Value;
|
|
|
|
using (Aes aesAlgorithm = Aes.Create())
|
|
{
|
|
aesAlgorithm.Key = Convert.FromBase64String(keyBase64);
|
|
aesAlgorithm.GenerateIV();
|
|
aesAlgorithm.Mode = CipherMode.CBC;
|
|
aesAlgorithm.Padding = PaddingMode.PKCS7;
|
|
|
|
ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor();
|
|
|
|
byte[] encryptedData;
|
|
using (MemoryStream ms = new MemoryStream())
|
|
{
|
|
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
|
{
|
|
byte[] plainBytes = Encoding.UTF8.GetBytes(plainConnectionString);
|
|
cs.Write(plainBytes, 0, plainBytes.Length);
|
|
cs.FlushFinalBlock(); // Explicitly apply padding
|
|
}
|
|
encryptedData = ms.ToArray();
|
|
}
|
|
|
|
string cipherBase64 = Convert.ToBase64String(encryptedData);
|
|
string ivBase64 = Convert.ToBase64String(aesAlgorithm.IV);
|
|
|
|
return $"{cipherBase64}:{ivBase64}";
|
|
}
|
|
}
|
|
|
|
public static string DecryptConnectionString(this IConfiguration configuration, string encryptedConnectionString)
|
|
{
|
|
string keyBase64 = configuration.GetSection("ConnectionStrings:Key").Value;
|
|
|
|
string vectorBase64 = encryptedConnectionString.Split(":")[1];
|
|
string cipherText = encryptedConnectionString.Split(":")[0];
|
|
|
|
using (Aes aesAlgorithm = Aes.Create())
|
|
{
|
|
aesAlgorithm.Key = Convert.FromBase64String(keyBase64);
|
|
aesAlgorithm.IV = Convert.FromBase64String(vectorBase64);
|
|
aesAlgorithm.Mode = CipherMode.CBC;
|
|
aesAlgorithm.Padding = PaddingMode.PKCS7;
|
|
|
|
ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor();
|
|
|
|
byte[] cipher = Convert.FromBase64String(cipherText);
|
|
|
|
using (MemoryStream ms = new MemoryStream(cipher))
|
|
{
|
|
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
|
|
{
|
|
using (StreamReader sr = new StreamReader(cs, Encoding.UTF8))
|
|
{
|
|
return sr.ReadToEnd();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|