public string SignWithCachedCert(string xmlData, string elementId) { if (string.IsNullOrEmpty(xmlData)) { throw new ArgumentNullException("xmlData"); } if (string.IsNullOrEmpty(elementId)) { throw new ArgumentNullException("elementId"); } if (CachedCert is null) { throw new ArgumentNullException("Call CacheCertificate before!"); } var originalDoc = XmlDocumentHelper.Create(xmlData); var xadesSignedXml = new XadesBesSignedXml(originalDoc) { SignedElementId = elementId, CryptoProvider = new GostCryptoProvider() }; var element = xadesSignedXml.FindElement(elementId, originalDoc); if (element == null) { throw new InvalidOperationException(string.Format("Не удалось найти узел c Id {0}", elementId)); } xadesSignedXml.ComputeSignature(CachedCert, CachedCertKey); xadesSignedXml.InjectSignatureTo(originalDoc); return(originalDoc.OuterXml); }
/// <summary> /// Формирует XML тело сообщения на основе структуры GisDataPack. /// </summary> /// <param name="gisRequest">Структура типа GisDataPack</param> /// <returns>Строковое представление сформированного XML</returns> private static string GetBodyXML(DataPack gisRequest) { var soapFormatter = new GisSoapFormatter { Template = PathHelper.ToAppAbsolutePath(gisRequest.TemplatePath), SchemaVersion = gisRequest.SchemaVersion, AddOrgPPAGuid = gisRequest.AddOrgPPAGUID, ValuesDictionary = gisRequest.Xpath2Values, OrgPPAGuid = gisRequest.OrgPPAGUID, Config = gisRequest.SoapConfig }; var soapString = soapFormatter.GetSoapRequest(gisRequest.RequesterMessageGuid); #if DEBUG Notificator.Write(soapString); #endif if (gisRequest.AddSignature && gisRequest.Action != "urn:getState") { var soapXml = XmlDocumentHelper.Create(soapString); soapString = SignNode(soapXml, Constants.SoapContentXpath, gisRequest.CertificateThumbprint, gisRequest.SignPasswd, gisRequest.RequesterMessageGuid); #if DEBUG Notificator.Write(soapString); #endif return(soapString); } return(soapString); }
public void ValidateSignature(string xmlData, string elementId) { if (string.IsNullOrEmpty(xmlData)) { throw new ArgumentNullException("xmlData"); } if (string.IsNullOrWhiteSpace(elementId)) { throw new ArgumentNullException("elementId"); } var document = XmlDocumentHelper.Create(xmlData); var signedXml = new XadesBesSignedXml(document, elementId) { CertificateMatcher = new CertificateMatcher(new GostCryptoProvider()) }; signedXml.Validate(); }
private IEnumerable <Tuple <string, string> > ProcessSoapResponse(string response) { var soapXml = XmlDocumentHelper.Create(response); var manager = soapXml.CreateNamespaceManager(); var bodyResponse = soapXml.SelectSingleNode(Constants.SoapContentXpath, manager); var idAttribute = bodyResponse.Attributes["Id"]?.Value; if (!string.IsNullOrEmpty(idAttribute) && bodyResponse.ChildNodes.OfType <XmlNode>().Any(x => x.LocalName == Constants.SignatureName)) { Info("Проверка подписи ответа..."); Validate(soapXml, idAttribute); } else { Info("Ответ не содержит подписи"); } return(FindXmlDataNode(bodyResponse, $"{bodyResponse.Name}/")); }
public XmlDocument Sign(string xmlData, string elementId, string certificateThumbprint, string certificatePassword) { if (string.IsNullOrEmpty(xmlData)) { throw new ArgumentNullException("xmlData"); } if (string.IsNullOrEmpty(elementId)) { throw new ArgumentNullException("elementId"); } if (string.IsNullOrEmpty(certificateThumbprint)) { throw new ArgumentNullException("certificateThumbprint"); } var originalDoc = XmlDocumentHelper.Create(xmlData); var certificate = CertificateHelper.GetCertificateByThumbprint(certificateThumbprint); var xadesSignedXml = new XadesBesSignedXml(originalDoc) { SignedElementId = elementId, CryptoProvider = new GostCryptoProvider() }; var element = xadesSignedXml.FindElement(elementId, originalDoc); if (element == null) { throw new InvalidOperationException(string.Format("Не удалось найти узел c Id {0}", elementId)); } xadesSignedXml.ComputeSignature(certificate, certificatePassword); xadesSignedXml.InjectSignatureTo(originalDoc); return(originalDoc); }
protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values) { var service = _serviceConfig.Services[serviceName]; if (service == null) { throw new ConfigurationErrorsException($"Конфигурация для сервиса {serviceName} не задана"); } var method = service.Methods[methodName]; if (method == null) { throw new ConfigurationErrorsException($"Конфигурация для метода {methodName} не задана"); } if (method.RequiredBody && !xpath2Values.Any()) { throw new ConfigurationErrorsException($"Метод {methodName} имеет обязательные параметры для запроса (-с файл)"); } Info("Создание запроса..."); var soapFormatter = new GisSoapFormatter { Template = PathHelper.ToAppAbsolutePath(method.Template), //SchemaVersion = _serviceConfig.SchemaVersion, TODO Удалить если всё норм AddOrgPPAGuid = service.AddSenderId, ValuesDictionary = xpath2Values, // TODO обратить внимание на эту строчку, нужно ли из конфига брать? или из базы guid организации. OrgPPAGuid = _serviceConfig.RIRCorgPPAGUID, Config = _serviceConfig.SoapConfiguration, MessageGuid = "" }; var soapString = soapFormatter.GetSoapRequest(soapFormatter.MessageGuid); System.IO.File.WriteAllText(@"soapString.txt", soapString); if (IsSignatureRequired && service.AddSignature) { Info("Добавление подписи в запрос..."); var soapXml = XmlDocumentHelper.Create(soapString); soapString = SignNode(soapXml, Constants.SoapContentXpath); System.IO.File.WriteAllText(@"soapStringSign.txt", soapString); } IEnumerable <Tuple <string, string> > resultValues; try { Info($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}"); Console.WriteLine($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}"); var response = CallGisService($"{_serviceConfig.BaseUrl}{service.Path}", method.Action, soapString, _serviceConfig.Login, _serviceConfig.Password); Console.WriteLine(response); Info("Обработка ответа на запрос..."); resultValues = ProcessSoapResponse(response); Console.WriteLine(resultValues); } catch (XadesBesValidationException ex) { Error($"Подпись ответа от ГИС ЖКХ не прошла проверку: {ex.Message}", ex); return; } catch (WebException ex) { Warning($"Сервер ответил с ошибкой: {ex.Message}"); using (var streamWriter = new StreamReader(ex.Response.GetResponseStream())) { var response = streamWriter.ReadToEnd(); resultValues = ProcessSoapResponse(response); } } Info($"Сохранение ответа ..."); Console.WriteLine(resultValues); Success("Запрос успешно выполнен"); }
protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values, string outputFile) { var service = _serviceConfig.Services[serviceName]; if (service == null) { throw new ConfigurationErrorsException(string.Format("Конфигурация для сервиса {0} не задана", serviceName)); } var method = service.Methods[methodName]; if (method == null) { throw new ConfigurationErrorsException(string.Format("Конфигурация для метода {0} не задана", methodName)); } if (method.RequiredBody && !xpath2Values.Any()) { throw new ConfigurationErrorsException(string.Format("Метод {0} имеет обязательные параметры для запроса (-с файл)", methodName)); } Info("Создание запроса..."); var soapFormatter = new GisSoapFormatter { Template = PathHelper.ToAppAbsolutePath(method.Template), AddSenderId = service.AddOrgPpaGuid, ValuesDictionary = xpath2Values, OrgPpaGuid = _serviceConfig.OrgPpaGuid, Config = _serviceConfig.SoapConfiguration }; var soapString = soapFormatter.GetSoapRequest(); if (IsSignatureRequired && service.AddSignature) { Info("Добавление подписи в запрос..."); var soapXml = XmlDocumentHelper.Create(soapString); soapString = SignNode(soapXml, Constants.SoapContentXpath); } IEnumerable <Tuple <string, string> > resultValues; try { Info(string.Format("Отправка запроса по адресу: {0}{1}/{2}", _serviceConfig.BaseUrl, service.Path, method.Action)); var response = CallGisService(_serviceConfig.BaseUrl + service.Path, method.Action, soapString, Option.BasicAuthorization); Info("Обработка ответа на запрос..."); resultValues = ProcessSoapResponse(response); } catch (XadesBesValidationException ex) { Error(string.Format("Подпись ответа от ГИС ЖКХ не прошла проверку: {0}", ex.Message), ex); return; } catch (WebException ex) { Warning(string.Format("Сервер ответил с ошибкой: {0}", ex.Message)); using (var streamWriter = new StreamReader(ex.Response.GetResponseStream())) { var response = streamWriter.ReadToEnd(); resultValues = ProcessSoapResponse(response); } } Info(string.Format("Сохранение ответа в файл {0}...", outputFile)); Helpers.CsvHelper.WriteCsv(outputFile, resultValues); Success("Запрос успешно выполнен"); }