Доступ к пути запрещен в File.ReadAllBytes в зашифрованном файле AES
Я пытаюсь прочитать двоичное содержимое файла с помощью File.ReadAllBytes и получаю исключение, что доступ к файлу запрещен. Должен ли я сначала открыть файл? В этом примере используется выбор пути исключения.
Невозможно загрузить данные конфигурации. Доступ к пути 'c:\worl\Project Alpha\Code\AlphaBackendService\AlphaBackendService\bin\Debug\alphaService.xml' запрещен.
Что мне не хватает?
try
{
string path = AppDomain.CurrentDomain.BaseDirectory;
eventLog1.WriteEntry(path);
string fileName = System.IO.Path.Combine(path, "alphaService.xml");
string sKey = "LvtZELDrB394hbSOi3SurLWAvC8adNpZiJmQDJHdfJU=";
Byte[] keyBytes = Convert.FromBase64String(sKey);
Byte[] contentsBytes = File.ReadAllBytes(fileName);
string xmlStr = Encoding.UTF8.GetString(contentsBytes);
DecryptStringFromBase64String(xmlStr, keyBytes);
eventLog1.WriteEntry(xmlStr);
using (XmlReader reader = XmlReader.Create(new StringReader(xmlStr)))
{
reader.ReadToFollowing("DatabaseServerName");
DatabaseServerName = reader.ReadElementContentAsString();
reader.ReadToFollowing("DatabaseUserName");
DatabaseUserName = reader.ReadElementContentAsString();
reader.ReadToFollowing("DatabasePassword");
DatabasePassword = reader.ReadElementContentAsString();
reader.ReadToFollowing("RegistrationCode");
RegistrationCode = reader.ReadElementContentAsString();
}
eventLog1.WriteEntry("Configuration data loaded successfully");
}
catch (Exception ex)
{
eventLog1.WriteEntry("Unable to load configuration data. " + ex.Message);
}
Функция Decrypt требует строку с содержимым, но она выполняет Convert.FromBase84String, поэтому я не знаю, следует ли использовать File.ReadAllBytes.
static string DecryptStringFromBase64String(string cipherText, byte[] Key)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
string plaintext = null;
// this is all of the bytes
var allBytes = Convert.FromBase64String(cipherText);
// get our IV that we pre-pended to the data
byte[] iv = new byte[KeySize / 16];
Array.Copy(allBytes, iv, iv.Length);
// get the data we need to decrypt
byte[] cipherBytes = new byte[allBytes.Length - iv.Length];
Array.Copy(allBytes, iv.Length, cipherBytes, 0, cipherBytes.Length);
using (var aes = Aes.Create())
{
// Create a decrytor to perform the stream transform.
var decryptor = aes.CreateDecryptor(Key, iv);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}