Моя проблема заключается в том, что когда я отладкую в коде VS, код ведет себя так же, как и ожидалось. Но затем я попытался упаковать в EXE, используя Pyinstaller и назвал его в C#, поведение изменяется на дешифрирование вместо InvalidKeyError. Эта текущая итерация затем использовала мою Венва, когда вызывая файл Python напрямую. Тот же результат, к сожалению. Если есть лучшие решения, я открыт для этого
Вот мой быстрый сценарий Python: < /p>
import io
import msoffcrypto
import argparse
from msoffcrypto.exceptions import InvalidKeyError, DecryptionError
if __name__ == '__main__':
parser= parser = argparse.ArgumentParser()
parser.add_argument('--filepath', required=True, help='Path to the encrypted Office file')
parser.add_argument('--test_string', required=True, help='Password to test against the encrypted file')
args = parser.parse_args()
file_path = args.filepath
test_pass = args.test_string
try:
# Attempt to open the file and decrypt it with the pseudo password
with open(file_path, 'rb') as f:
office_file = msoffcrypto.OfficeFile(f)
office_file.load_key(password=test_pass)
decrypted = io.BytesIO()
office_file.decrypt(decrypted)
# Case where there is password encryption
except InvalidKeyError:
print(True)
# Case where there is NOT password encryption
except DecryptionError as e:
print(False)
# Edge case
except Exception as e:
print(False)
< /code>
Вот моя реализация C#: < /p>
private static bool IsExcelFilePasswordProtected(string filePath)
{
string venvPython = Path.Combine(AppContext.BaseDirectory, "venv", "Scripts", "python.exe"); // Windows
string scriptPath = Path.Combine(AppContext.BaseDirectory, "CheckPass.py");
string args = $"\"{scriptPath}\" --filepath \"{filePath}\" --test_string notapassword";
var psi = new ProcessStartInfo
{
FileName = venvPython,
Arguments = args,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
try
{
using (var process = Process.Start(psi))
{
string output = process?.StandardOutput.ReadToEnd() ?? string.Empty;
process?.WaitForExit();
bool hasPassword = bool.TryParse(output.Trim(), out bool result) && result;
return hasPassword;
}
}
catch (Exception e)
{
return false;
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -of-python
Мобильная версия