public void CertificateThumbprintIsCleanedUp()
 {
     Assert.AreEqual(null, GostCryptoHelpers.CleanupThumbprint(null));
     Assert.AreEqual(string.Empty, GostCryptoHelpers.CleanupThumbprint(string.Empty));
     Assert.AreEqual(string.Empty, GostCryptoHelpers.CleanupThumbprint(" \t\v\r\n"));
     Assert.AreEqual("1234abcd", GostCryptoHelpers.CleanupThumbprint(" 12 34  ab cd   "));
     Assert.AreEqual(TestCertificateThumbprint, GostCryptoHelpers.CleanupThumbprint(TestCertificateThumbprintCopiedFromTheSnapin));
 }
        public void CertificateCanBeUsedToComputeAttachedCmsSignature()
        {
            var cert = GetTestCertificate();
            var sign = GostCryptoHelpers.ComputeAttachedSignature(cert, "Привет!");

            Assert.IsNotNull(sign);
            Assert.IsTrue(sign.StartsWith("MII"));
            Assert.IsTrue(sign.Length > 1000);
        }
Exemplo n.º 3
0
        /// <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));
        }
Exemplo n.º 4
0
        /// <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);
        }
Exemplo n.º 8
0
        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);
            };
        }
Exemplo n.º 9
0
        /// <summary>
        /// Performs authentication, returns access token with a limited lifetime.
        /// </summary>
        /// <param name="apiClient">API client to perform API calls.</param>
        /// <returns><see cref="AuthToken"/> instance.</returns>
        public override AuthToken Authenticate(CommonApiClient apiClient)
        {
            // make sure it's an OMS client
            var edoLiteClient = apiClient as EdoLiteClient;

            if (edoLiteClient == null)
            {
                throw new InvalidOperationException("EdoLiteCredentials requires EdoLiteClient.");
            }

            // check if the token is already available
            var authToken = CheckSessionToken(edoLiteClient);

            if (authToken != null)
            {
                return(authToken);
            }

            // 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: " + CertificateThumbprint);
            }

            // get authentication code
            var authResponse = Authenticate(edoLiteClient);

            // compute the signature and save the size
            var signedData = GostCryptoHelpers.ComputeAttachedSignature(certificate, authResponse.Data);

            apiClient.SignatureSize = Encoding.UTF8.GetByteCount(signedData);

            // get authentication token
            return(GetToken(edoLiteClient, authResponse, signedData));
        }
        /// <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);
        }
Exemplo n.º 11
0
        // <summary>
        // Gets or sets the OMS Identity, taken from the user's profile,
        // see https://intuot.crpt.ru:12011/configuration/profile
        // </summary>
        // public string OmsID { get; set; }

        // <summary>
        // Gets or sets the device token, taken from the device properties,
        // see https://intuot.crpt.ru:12011/management/devices
        // </summary>
        // public string DeviceToken { get; set; }

        /// <summary>
        /// Performs authentication, returns access token with a limited lifetime.
        /// </summary>
        /// <param name="apiClient">GIS MT client to perform API calls.</param>
        /// <returns><see cref="AuthToken"/> instance.</returns>
        public AuthToken Authenticate(CommonApiClient 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: " + CertificateThumbprint);
            }

            // get authentication code
            var authResponse = apiClient.Authenticate();

            // compute the signature and save the size
            var signedData = GostCryptoHelpers.ComputeAttachedSignature(certificate, authResponse.Data);

            apiClient.SignatureSize = Encoding.UTF8.GetByteCount(signedData);

            // get authentication token
            return(apiClient.GetToken(authResponse, signedData));
        }
        /// <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));
        }
Exemplo n.º 13
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     //tbxSignedText.Text = GostCryptoHelpers.ComputeDetachedSignature(TrueApiClient.UserCertificate, tbxTextToSign.Text);
     tbxSignedText.Text = GostCryptoHelpers.ComputeAttachedSignature(TrueApiClient.UserCertificate, tbxTextToSign.Text.Trim()).Trim();
 }
 private X509Certificate2 GetTestCertificate()
 {
     return(GostCryptoHelpers.FindCertificate(TestCertificateSubjectName));
 }
        public void CertificateIsLoadedByThumbprint()
        {
            var cert = GostCryptoHelpers.FindCertificate(TestCertificateThumbprint);

            Assert.NotNull(cert);
        }
 public void GostCryproProviderIsInstalled()
 {
     Assert.IsTrue(GostCryptoHelpers.IsGostCryptoProviderInstalled());
 }