сам ключ и IV сохранил в файле с расширением конфиг:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="EncryptionKey" value="your-32-char-long-encryption-key-here1234" />
<add key="IV" value="your-16-char-IV-here" />
</appSettings>
</configuration>
и класс, где я пытаюсь прочитать данные и использовать их:
public class ElGamalParametersExporter
{
private string connectionString;
private byte[] key;
private byte[] iv;
//private static readonly byte[] Key = Encoding.UTF8.GetBytes("your-32-char-long-encryption-key-here1234"); // 32 bytes for AES-256
//private static readonly byte[] IV = Encoding.UTF8.GetBytes("your-16-char-IV-here"); // 16 bytes for AES
public ElGamalParametersExporter(string dbFileName)
{
LoadEncryptionSettings();
string relativePathToDB = Path.Combine("database", dbFileName);
string absolutePathToDB = Path.GetFullPath(relativePathToDB);
connectionString = "Data Source=" + absolutePathToDB + ";Version=3;";
}
private void LoadEncryptionSettings()
{
// Прочитать ключ и IV из файла конфигурации
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string encryptionKey = config.AppSettings.Settings["EncryptionKey"]?.Value;
string initializationVector = config.AppSettings.Settings["IV"]?.Value;
// Проверка на наличие ключей
if (string.IsNullOrEmpty(encryptionKey))
{
MessageBox.Show("EncryptionKey отсутствует или пуст в файле конфигурации.");
throw new ArgumentNullException("EncryptionKey отсутствует или пуст в файле конфигурации.");
}
if (string.IsNullOrEmpty(initializationVector))
{
MessageBox.Show("IV отсутствует или пуст в файле конфигурации.");
throw new ArgumentNullException("IV отсутствует или пуст в файле конфигурации.");
}
// Проверка длины ключа и IV
if (encryptionKey.Length != 32)
{
MessageBox.Show("EncryptionKey должен быть ровно 32 символа длиной.");
throw new ArgumentException("EncryptionKey должен быть ровно 32 символа длиной.");
}
if (initializationVector.Length != 16)
{
MessageBox.Show("IV должен быть ровно 16 символов длиной.");
throw new ArgumentException("IV должен быть ровно 16 символов длиной.");
}
// Конвертация ключа и IV из строк в массивы байт
key = Encoding.UTF8.GetBytes(encryptionKey);
iv = Encoding.UTF8.GetBytes(initializationVector);
// Вывод отладочной информации
MessageBox.Show("Ключ: " + Convert.ToBase64String(key));
MessageBox.Show("IV: " + Convert.ToBase64String(iv));
}
private static byte[] EnsureCorrectLength(byte[] input, int length)
{
if (input.Length == length)
return input;
byte[] output = new byte[length];
if (input.Length > length)
{
Array.Copy(input, output, length);
}
else
{
Array.Copy(input, output, input.Length);
for (int i = input.Length; i < length; i++)
{
output[i] = 0x00; // Zero padding for shorter inputs
}
}
return output;
}
private string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = EnsureCorrectLength(key, 32);
aesAlg.IV = EnsureCorrectLength(iv, 16);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
Получаю ошибку что ключ или файл не существует, в общем вернул мне ноль. Может я неправильно файл создал или неправильно читаю их, подскажите пожалуйста.
Вот подробная ошибка: "Значение не может быть неопределенным.
Имя параметра: EncryptionKey отсутствует или пуст в файле конфигурации."
Заранее спасибо за помощь