У меня есть код, который считывает защищенные значения из файла конфигурации и расшифровывает их в строки. Затем код использует эти значения в функциях Windows Logon и TokenService.
Код работает нормально, когда я отлаживаю его со своего рабочего стола, но значения не расшифровываются правильно, когда я развертываю код на сервер. Мой рабочий стол — Windows 11, а развернутый сервер работает на Windows Server 2016.
Если я жестко закодирую расшифрованные значения конфигурации непосредственно в эти две функции, они будут работать на развернутом сервере.
Когда я отлаживаю код, расшифровывающий значения конфигурации, переменные идентичны тем, которые я жестко запрограммировал.
Что мне не хватает?
public class EncryptionService : IEncryptionService
{
private readonly IDataProtector _protector;
private static readonly ILog _log = LogManager.GetLogger(typeof(EncryptionService));
// Constructor to initialize the IDataProtector using dependency injection
public EncryptionService(IDataProtectionProvider provider)
{
// unique string that ensures different protection policies for different purposes
_protector = provider.CreateProtector("MyPurposeIs...");
}
// Method to encrypt plain text data
public string EncryptData(string plainText)
{
return _protector.Protect(plainText);
}
// Method to decrypt the encrypted data
public string DecryptData(string encryptedData)
{
try
{
return _protector.Unprotect(encryptedData);
}
catch (Exception ex)
{
// If decryption fails (e.g., data is tampered or invalid), handle the exception
return $"Decryption failed: {ex.Message}";
}
}
}
public class Utilities : IUtilities
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);
public IConfiguration _config;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
private static readonly ILog _log = LogManager.GetLogger(typeof(Utilities));
private readonly IEncryptionService _encryptionService;
public Utilities(IConfiguration configuration, IEncryptionService encryptionService)
{
_config = configuration;
_encryptionService = encryptionService;
}
//domain, username and password are read from a config file, decrypted, then passed into this function
public string[]? ImpersonateAndGetFiles(string domain, string username, string password, string sourcePath, string fileSpec)
{
string[]? resultArray = null;
try
{
SafeAccessTokenHandle? safeAccessTokenHandle;
bool returnValue = LogonUser(username, domain, password,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
out safeAccessTokenHandle);
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
_log.Error($"LogonUser failed with error code : {ret}");
return resultArray;
}
if (safeAccessTokenHandle is not null)
{
_log.Info("Logon Successful. Getting file list.");
#pragma warning disable CA1416 // Validate platform compatibility
WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
{
resultArray = Directory.GetFiles(sourcePath, fileSpec);
return Task.CompletedTask;
});
#pragma warning restore CA1416 // Validate platform compatibility
}
}
catch (Exception ex)
{
_log.Error($"Error: {ex}");
return resultArray;
}
return resultArray;
}
}
//code that uses the functions
string? domain = _config["domainCL"];
string? userName = _config["userNameCL"];
string? password = _config["passwordCL"];
string? unEncryptedDomain = null;
string? unEncryptedUserName = null;
string? unEncryptedPassword = null;
unEncryptedDomain = _encryptionService.DecryptData(domain);
unEncryptedUserName = _encryptionService.DecryptData(userName);
unEncryptedPassword = _encryptionService.DecryptData(password);
fileList = _utils.ImpersonateAndGetFiles(unEncryptedDomain, unEncryptedUserName, unEncryptedPassword, folder, "*.xml");
Подробнее здесь: https://stackoverflow.com/questions/792 ... kenservice
Функция расшифровки C# Dataprotector не работает с Logon или TokenService ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение