/// <summary> /// Computes the detached digital signature of the given text. /// </summary> /// <param name="textToSign">Text to sign.</param> /// <returns>Detached signature in CMS format and base64 encoding.</returns> private string ComputeSignature(string textToSign) { if (UserCertificate == null) { return(null); } return(GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, textToSign)); }
public void CertificateCanBeUsedToComputeDetachedCmsSignature() { var cert = GetTestCertificate(); var sign = GostCryptoHelpers.ComputeDetachedSignature(cert, "Привет!"); Assert.IsNotNull(sign); Assert.IsTrue(sign.StartsWith("MII")); Assert.IsTrue(sign.Length > 1000); }
/// <summary> /// 3.1.1. Метод создания заявки на регистрацию УОТ /// </summary> public string Register(ProductDocument organizationInfo) { var json = Serializer.Serialize(organizationInfo); var signature = GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, json); var jsonBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); var response = Post <RegistrationResponse>("/elk/registration", new Registration { DocumentFormat = Registration.DocumentFormatJson, ProductDocument = jsonBase64, Signature = signature, }); return(response.RegistrationRequestDocID); }
/// <summary> /// 4.2.5.1 Ввод в оборот /// </summary> public string IntroduceGoodsRF(LP_INTRODUCE_GOODS organizationInfo) { throw new NotImplementedException(); var json = Serializer.Serialize(organizationInfo); var signature = GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, json); var jsonBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); var response = Post <RegistrationResponse>("/elk/registration", new Registration { DocumentFormat = Registration.DocumentFormatJson, ProductDocument = jsonBase64, Signature = signature, }); return(response.RegistrationRequestDocID); }
/// <summary> /// 4.2.2.1 Аггрегация /// </summary> //TODO Можно сделать единый метод отправки доументов public string Aggregation(AggregationDocument Document) { var json = Serializer.Serialize(Document); var signature = GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, json); var jsonBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); var response = Post("/lk/documents/create", new DocumentBase() { DocumentFormat = Registration.DocumentFormatJson, Document = jsonBase64, Signature = signature, Type = Document.DocumentName }, new Parameter[] { new RestSharp.Parameter("pg", "milk", ParameterType.QueryString) }); return(response); }
/// <summary> /// 3.5. Подписание исходящего документа /// </summary> /// <param name="docId">Идентификатор документа</param> /// <param name="xmlFileContents">XML-содержимое документа (опционально: если не передать, документ будет запрошен через API).</param> public void SignOutgoingDocument(string docId, string xmlFileContents = null) { // если документ не передан, получить содержимое документа и подписать его xmlFileContents = xmlFileContents ?? GetOutgoingDocument(docId); var docBytes = Encoding.GetEncoding(1251).GetBytes(xmlFileContents); var signature = GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, docBytes); var url = "outgoing-documents/{doc_id}/signature"; var request = new RestRequest(url, Method.POST, DataFormat.Json); request.AddParameter(new Parameter("doc_id", docId, ParameterType.UrlSegment)); request.AddParameter(new Parameter(string.Empty, signature, ParameterType.RequestBody)); request.AddHeader("Content-encoding", "base64"); request.AddHeader("Content-type", "text/plain"); Execute(request); }
protected virtual void SignRequest(IRestRequest request) { // we can sign the request when it's already prepared // because otherwise we don't have the serialized body // that's why we have to do it in OnBeforeRequest handler request.OnBeforeRequest += (IHttp http) => { var data = request.Method == Method.GET ? request.Resource : GetBodyText(request.Body); var cert = UserCertificate; var signature = GostCryptoHelpers.ComputeDetachedSignature(cert, data); // won't be added to headers because the request is already prepared // we add parameter just for the tracing: request.Parameters.Add(new Parameter("X-Signature", signature, ParameterType.HttpHeader)); var header = new HttpHeader("X-Signature", signature); http.Headers.Add(header); }; }
/// <summary> /// 3.1. Метод загрузки файла информации продавца УПД согласно приказу 820 от 19.12.2018 № ММВ-7-15/820@ в формате XML /// </summary> /// <remarks> /// * Сервер принимает только документы в кодировке windows-1251. /// * Трассировка этого метода неполная: multipart/form-data не отображается. /// </remarks> /// <param name="fileName">Имя файла, сформированное согласно стандарту формирования</param> /// <param name="xmlFileContents">Содержимое XML-файла, должно быть согласовано с именем</param> /// <param name="signed">Подписывать документ перед отсылкой</param> public string SendSellerUpdDocument(string fileName, string xmlFileContents, bool signed = true) { var request = new RestRequest("outgoing-documents", Method.POST, DataFormat.Json); request.AlwaysMultipartFormData = true; // сервер принимает XML-документы только в кодировке windows-1251 var content = Encoding.GetEncoding(1251).GetBytes(xmlFileContents); request.AddFile("content", content, fileName, "application/xml"); // если документ подписывается, то в той же кодировке, что и отсылается if (signed) { var signature = GostCryptoHelpers.ComputeDetachedSignature(UserCertificate, content); request.Parameters.Add(new Parameter("signature", signature, ParameterType.GetOrPost)); } var result = Execute <ResID>(request); return(result.ID); }
/// <inheritdoc/> public override AuthToken Authenticate(MdlpClient apiClient) { // load the certificate with a private key by userId var certificate = apiClient.UserCertificate; if (certificate == null) { throw new SecurityException("GOST-compliant certificate not found. " + "Make sure that the certificate is properly installed and has the associated private key. " + "Thumbprint or subject name: " + UserID); } // get authentication code var authCode = apiClient.Authenticate(ClientID, ClientSecret, UserID, AuthTypeEnum.SIGNED_CODE); // compute the signature and save the size var signature = GostCryptoHelpers.ComputeDetachedSignature(certificate, authCode); apiClient.SignatureSize = Encoding.UTF8.GetByteCount(signature); // get authentication token return(apiClient.GetToken(authCode, signature: signature)); }