Example #1
0
        //this class is a pretty thin useless wrapper now that I look at it...
        public static ApiStack CreateApiStack(this Construct scope,
                                              string apiName,
                                              Cluster cluster,
                                              Vpc vpc,
                                              Repository ecrRepo,
                                              string subDomain,
                                              string hostedZoneName,
                                              string hostedZoneId,
                                              ICertificate sslCert,
                                              Dictionary <string, string> containerEnvVars = null,
                                              Dictionary <string, Secret> containerSecrets = null,
                                              Environment env = null)
        {
            env ??= Constants.DefaultEnv;
            containerEnvVars ??= new Dictionary <string, string>();
            containerSecrets ??= new Dictionary <string, Secret>();

            containerEnvVars.Add("AWS__REGION", env.Region);
            var serviceName = $"{apiName.ToLowerInvariant()}-api";

            return(new ApiStack(scope, $"{serviceName}-stack", new ApiProps
            {
                Vpc = vpc,
                Env = env,
                ServiceName = serviceName,
                EcsCluster = cluster,
                EcrRepository = ecrRepo,
                ContainerEnvVars = containerEnvVars,
                ContainerSecrets = containerSecrets,
                SubDomain = subDomain,
                HostedZoneName = hostedZoneName,
                HostedZoneId = hostedZoneId,
                Certificate = sslCert
            }));
        }
Example #2
0
 protected virtual IClientCertificate OnCertificateSelectionCallback(
     TestContext ctx, string targetHost, ICertificate[] localCertificates,
     ICertificate remoteCertificate, string[] acceptableIssuers)
 {
     // Derived classes must override this when using 'NeedCustomCertificateSelectionCallback'.
     throw new NotImplementedException();
 }
 public bool CreateSignature2(string Content, ICertificate CreateCertificate, IAdditionalInfoList AdditionalInfo, out string Signature, out string CreateMsg, ref DateTime CreateDateTime)
 {
     CreateMsg      = string.Empty;
     CreateDateTime = DateTime.UtcNow;
     Signature      = $"Signature: CreateDateTime={ CreateDateTime };";
     return(true);
 }
 /// <summary>
 /// Get bcgov_Certificate from bcgov_certificatetermsandconditionses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bcgovCertificatetermsandconditionsid'>
 /// key: bcgov_certificatetermsandconditionsid of
 /// bcgov_certificatetermsandconditions
 /// </param>
 /// <param name='select'>
 /// Select properties to be returned
 /// </param>
 /// <param name='expand'>
 /// Expand related entities
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <MicrosoftDynamicsCRMbcgovCertificate> GetAsync(this ICertificate operations, string bcgovCertificatetermsandconditionsid, IList <string> select = default(IList <string>), IList <string> expand = default(IList <string>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetWithHttpMessagesAsync(bcgovCertificatetermsandconditionsid, select, expand, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #5
0
        public void only_has_to_match_on_one_cert()
        {
            var certs = new ICertificate[]
            {
                new InMemoryCertificate(),
                new InMemoryCertificate(),
                new InMemoryCertificate(),
                new InMemoryCertificate()
            };

            var response = new SamlResponse
            {
                Issuer       = "this:guy",
                Certificates = certs
            };

            var samlCert = ObjectMother.SamlCertificateMatching(response.Issuer, certs[3]);

            MockFor <ISamlCertificateRepository>().Stub(x => x.Find(response.Issuer))
            .Return(samlCert);


            ClassUnderTest.MatchesIssuer(response)
            .ShouldBeTrue();
        }
Example #6
0
        internal static void AddDataProtection(
            this IServiceCollection services,
            string applicationName,
            ICertificate certificate)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (certificate is null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (string.IsNullOrWhiteSpace(applicationName))
            {
                return;
            }

            if (certificate.IsAvailable)
            {
                AddDataProtection(services, applicationName, certificate.Instance);
            }
            else
            {
                AddDataProtection(services, applicationName);
            }
        }
Example #7
0
        public async Task UpdateAsync(ICertificate cert, CancellationToken cancellationToken)
        {
            if (cert.Store.Type != "keyVault")
            {
                throw new NotSupportedException("Azure CDN can only use certificates from store keyVault. Found: " + cert.Store.Type);
            }

            // CDN seems to not like certs that have just been uploaded
            // checking if waiting a long time fixes the issue
            // note that overall max execution time is 10min
            // TODO: might have to use durable functions to make this scale with many renewals
            _logger.LogInformation("Waiting 2 minutes before deploying certificate to CDN");
            await Task.Delay(TimeSpan.FromMinutes(2), cancellationToken);

            var endpoints = await MatchEndpointsAsync(cert, cancellationToken);

            var results = await _azureCdnClient.UpdateEndpointsAsync(_resourceGroupName, Name, endpoints, cert, cancellationToken);

            foreach (var r in results)
            {
                var content = await r.Content.ReadAsStringAsync();

                r.EnsureSuccessStatusCode();
                // would now have to query this URL until operation completed successfully
                // but it may take up to 6h, so just ignore
                //var queryUrl = r.Headers.Location;
                //while (queryUrl != null)
                //{
                //    var resp = await httpClient.GetAsync(queryUrl);
                //    if (resp.StatusCode != HttpStatusCode.Accepted)
                //        break;
                //}
            }
        }
Example #8
0
        private void EnsureInit()
        {
            if (_cert != null)
            {
                return;
            }

            try {
                using (X509Certificate2 cert = !string.IsNullOrEmpty(_privateKeyPassword) ?
                                               new X509Certificate2(_file.Path, _privateKeyPassword) :
                                               new X509Certificate2(_file.Path)) {
                    cert.FriendlyName = _file.Name;
                    _cert             = new Certificates.Certificate(cert, _store, _file.Name);
                }
            }
            catch (UnauthorizedAccessException) {
                throw new ForbiddenArgumentException("certificate_store", "Cannot access store", _store.Name);
            }
            catch (CryptographicException e) {
                if (e.HResult == HResults.IncorrectPassword)
                {
                    throw new ForbiddenArgumentException("certificate_store", "Invalid private key password", _store.Name, e);
                }
                throw;
            }
        }
Example #9
0
        public Task AuthenticateSslStreamAsServer(Stream stream, ICertificate certificate)
        {
            var sslStream = (SslStream)stream;
            var cert      = (Certificate)certificate;

            return(sslStream.AuthenticateAsServerAsync(cert.X509Certificate));
        }
        private async Task UploadCertificateAsync(
            AppServiceProperties prop,
            HttpClient httpClient,
            ICertificate cert,
            string uploadCertName,
            string targetResourceGroup,
            CancellationToken cancellationToken)
        {
            var certificateUploadUrl = "https://management.azure.com" +
                                       $"/subscriptions/{_azureHelper.GetSubscriptionId()}/" +
                                       $"resourceGroups/{targetResourceGroup}/" +
                                       $"providers/Microsoft.Web/certificates/{uploadCertName}?api-version=2018-11-01";
            var content = new StringContent(JsonConvert.SerializeObject(new
            {
                prop.Location,
                properties = new
                {
                    keyVaultId         = cert.Store.ResourceId,
                    keyVaultSecretName = cert.Name,
                    prop.ServerFarmId,
                }
            }), Encoding.UTF8, "application/json");

            var response = await httpClient.PutAsync(certificateUploadUrl, content, cancellationToken);

            await response.EnsureSuccessAsync($"Failed to upload certificate {uploadCertName} to resource group {targetResourceGroup}.");
        }
Example #11
0
        internal static IIdentityServerBuilder AddCustomSigningCredential(
            this IIdentityServerBuilder builder,
            ICertificate certificate,
            ILogger logger)
        {
            if (certificate is null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (!certificate.IsAvailable)
            {
                logger.Information("Using developer signing credential");
                return(builder.AddDeveloperSigningCredential());
            }

            logger.Information("Using certificate {path}", certificate.Path);

            return(builder.AddSigningCredential(certificate.Instance));
        }
Example #12
0
        public static string SendAmendmentRequest(List <Docflow.IOfficialDocument> documents, Parties.ICounterparty receiver, string note, bool throwError,
                                                  ExchangeCore.IBoxBase box, ICertificate certificate, bool isInvoiceAmendmentRequest)
        {
            if (!documents.Any())
            {
                return(string.Empty);
            }

            var error       = Resources.AmendmentRequestError;
            var serviceDocs = new List <Structures.Module.ReglamentDocumentWithCertificate>();

            try
            {
                serviceDocs.AddRange(Functions.Module.Remote.GenerateAmendmentRequestDocuments(documents.ToList(), box, note, throwError, certificate, isInvoiceAmendmentRequest));
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(ex.Message);
            }

            if (!serviceDocs.Any())
            {
                return(Resources.AllAnswersIsAlreadySent);
            }

            try
            {
                var signs = ExternalSignatures.Sign(certificate, serviceDocs.ToDictionary(d => d.ParentDocumentId, d => d.Content));

                foreach (var doc in serviceDocs)
                {
                    doc.Signature = signs[doc.ParentDocumentId];
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(Resources.DocumentEndorseError);
            }

            try
            {
                var serviceCounterpartyId = string.Empty;
                var externalDocumentInfo  = Functions.ExchangeDocumentInfo.Remote.GetIncomingExDocumentInfo(documents.FirstOrDefault());
                if (externalDocumentInfo != null)
                {
                    serviceCounterpartyId = externalDocumentInfo.ServiceCounterpartyId;
                }

                Functions.Module.Remote.SendAmendmentRequest(serviceDocs, receiver, box, note);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(string.Format("{0}: {1}", error, ex.Message.ToString().ToLower()));
            }

            return(string.Empty);
        }
Example #13
0
        public HttpListenerHost(IServerApplicationHost applicationHost,
                                ILogger logger,
                                IServerConfigurationManager config,
                                string serviceName,
                                string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, IEnvironmentInfo environment, ICertificate certificate, IStreamFactory streamFactory, Func <Type, Func <string, object> > funcParseFn, bool enableDualModeSockets, IFileSystem fileSystem)
        {
            Instance = this;

            _appHost               = applicationHost;
            DefaultRedirectPath    = defaultRedirectPath;
            _networkManager        = networkManager;
            _memoryStreamProvider  = memoryStreamProvider;
            _textEncoding          = textEncoding;
            _socketFactory         = socketFactory;
            _cryptoProvider        = cryptoProvider;
            _jsonSerializer        = jsonSerializer;
            _xmlSerializer         = xmlSerializer;
            _environment           = environment;
            _certificate           = certificate;
            _streamFactory         = streamFactory;
            _funcParseFn           = funcParseFn;
            _enableDualModeSockets = enableDualModeSockets;
            _fileSystem            = fileSystem;
            _config = config;

            _logger = logger;

            RequestFilters  = new List <Action <IRequest, IResponse, object> >();
            ResponseFilters = new List <Action <IRequest, IResponse, object> >();
        }
Example #14
0
        public static int GetCertificatesSize(ICertificate certificate)
        {
            var size = 3 * (certificate.CertificateChain.Length + 1);

            size += certificate.CertificateData.Length;
            size += certificate.CertificateChain.Sum(c => c.Length);
            return(size);
        }
Example #15
0
        public void SetPeerKey(BigEndianAdvancingSpan peerKey, ICertificate certificate, SignatureScheme scheme)
        {
            peerKey = peerKey.ReadVector <ushort>();
            var decryptedLength = certificate.Decrypt(scheme, peerKey.ToSpan(), peerKey.ToSpan());

            peerKey          = peerKey.TakeSlice(decryptedLength);
            _premasterSecret = peerKey.ToArray();
        }
Example #16
0
        public async Task RevokeAsync(ICertificate certificate)
        {
            Ensure.NotNull(certificate, nameof(certificate));

            await db.Certificates.PatchAsync(certificate.Id, new[] {
                Change.Replace("revoked", Expression.Now)
            }, condition : Expression.IsNull("revoked"));
        }
 public void SetPeerKey(BigEndianAdvancingSpan peerKey, ICertificate certificate, SignatureScheme scheme)
 {
     peerKey = peerKey.ReadVector <byte>();
     if (peerKey.Length != _keyExchangeSize)
     {
         Alerts.AlertException.ThrowAlert(Alerts.AlertLevel.Fatal, Alerts.AlertDescription.illegal_parameter, $"The peer key is not the length of the keyexchange size {peerKey.Length} - {_keyExchangeSize}");
     }
     InternalSetPeerKey(peerKey.ToSpan());
 }
        private ICertificate MockCertificate(int numberOfCertificatesHeld, int numberOfCommittedCertificates, int remainingBalance)
        {
            ICertificate certificate = Mock.Of <ICertificate>();

            Mock.Get(certificate).Setup(c => c.NumberOfCertificatesHeld).Returns(numberOfCertificatesHeld);
            Mock.Get(certificate).Setup(c => c.NumberOfCommittedCertificates).Returns(numberOfCommittedCertificates);
            Mock.Get(certificate).Setup(c => c.RemainingBalance).Returns(remainingBalance);
            return(certificate);
        }
 public void SetPeerKey(BigEndianAdvancingSpan peerKey, ICertificate certificate, SignatureScheme scheme)
 {
     peerKey = peerKey.ReadVector <byte>();
     if (peerKey.Length != _keyExchangeSize)
     {
         Alerts.AlertException.ThrowAlert(Alerts.AlertLevel.Fatal, Alerts.AlertDescription.decode_error, "Peer key is bad");
     }
     InternalSetPeerKey(peerKey.ToSpan());
 }
        protected internal virtual X509Chain CreateChain(ICertificate certificate, CertificateValidationOptions options)
        {
            var chainPolicy = this.CreateChainPolicy(certificate, options);

            var chain = this.CreateChain(options?.UseMachineContext);

            chain.ChainPolicy = chainPolicy;

            return(chain);
        }
        public bool VerifySignature(string Content, string Signature, out ICertificate VerifyCertificate, out string VerifyMsg, out DateTime SignDate)
        {
            VerifyCertificate = new Certificate();
            VerifyMsg         = string.Empty;
            var signParts  = Signature.Split(new string[] { ": " }, StringSplitOptions.None);
            var signParams = signParts[1].Split(';');

            SignDate = DateTime.Parse(signParams[0].Split('=')[1]).ToLocalTime();
            return(true);
        }
Example #22
0
        public bool Add(ICertificate entity)
        {
            var cert = new Certificate
            {
                Name    = entity.Name,
                Content = entity.Content
            };

            return(Add(cert));
        }
Example #23
0
 public static SamlCertificate SamlCertificateMatching(string issuer, ICertificate certificate)
 {
     if (certificate == null) throw new ArgumentNullException("certificate");
     return new SamlCertificate
     {
         CertificateIssuer = certificate.Issuer,
         SerialNumber = certificate.SerialNumber,
         Issuer = issuer
     };
 }
        protected internal virtual IValidationResult EvaluateMatching(ICertificate certificate, CertificateValidationOptions options)
        {
            var validationResult = new ValidationResult();

            var matching = options?.Matching ?? new MatchingOptions();

            // ReSharper disable InvertIf
            if (matching.Criteria.Any())
            {
                var messagePrefix = $"Certificate {this.ValueAsFormatItem(certificate?.Subject)}: ";
                var results       = new List <KeyValuePair <string, bool> >();

                foreach (var criterion in matching.Criteria)
                {
                    var formattedPropertyName       = this.ValueAsFormatItem(criterion.PropertyName);
                    var formattedValuePattern       = this.ValueAsFormatItem(criterion.ValuePattern);
                    var canNotEvaluateMessagePrefix = $"{messagePrefix}Can not evaluate if certificate-property {formattedPropertyName} matches value {formattedValuePattern} because";

                    if (certificate == null)
                    {
                        results.Add(new KeyValuePair <string, bool>($"{canNotEvaluateMessagePrefix} because the certificate is NULL.", false));
                        continue;
                    }

                    if (!this.TryGetCertificatePropertyValue(certificate, criterion.PropertyName, out var propertyValue))
                    {
                        results.Add(new KeyValuePair <string, bool>($"{canNotEvaluateMessagePrefix} because the certificate-property does not exist.", false));
                        continue;
                    }

                    var evaluateMessagePrefix = $"{messagePrefix}The value {this.ValueAsFormatItem(propertyValue)}, for certificate-property {formattedPropertyName}";

                    if ((propertyValue == null && criterion.ValuePattern == null) || (propertyValue != null && propertyValue.Like(criterion.ValuePattern)))
                    {
                        if (!matching.AllCriteriaShouldMatch)
                        {
                            return(validationResult);
                        }

                        results.Add(new KeyValuePair <string, bool>($"{evaluateMessagePrefix}, matches value {formattedValuePattern}.", true));
                        continue;
                    }

                    results.Add(new KeyValuePair <string, bool>($"{evaluateMessagePrefix}, do not match value {formattedValuePattern}.", false));
                }

                if ((matching.AllCriteriaShouldMatch && results.Any(item => !item.Value)) || (!matching.AllCriteriaShouldMatch && !results.Any(item => item.Value)))
                {
                    validationResult.Exceptions.Add(results.Where(item => !item.Value).Select(item => new EvaluateException(item.Key)));
                }
            }
            // ReSharper restore InvertIf

            return(validationResult);
        }
 protected internal virtual X509Certificate2 UnwrapCertificate(ICertificate certificate)
 {
     try
     {
         return(certificate.Unwrap <X509Certificate2>());
     }
     catch (Exception exception)
     {
         throw new InvalidOperationException($"Could not unwrap certificate {this.ValueAsFormatItem(certificate?.Subject)}.", exception);
     }
 }
Example #26
0
        private void ValidateCertificate(ICertificate certificate)
        {
            //очищаем поле проверки сертификата
            this.textBox_check_result.Text = "";

            //выводим информацию о проверке самого сертификата
            if (certificate != null)
            {
                this.textBox_check_result.Text = _validator.Validate(certificate).ToString();
            }
        }
 public static object ToJsonModelRef(ICertificate cert, Fields fields = null)
 {
     if (fields == null || !fields.HasFields)
     {
         return(ToJsonModel(cert, RefFields, false));
     }
     else
     {
         return(ToJsonModel(cert, fields, false));
     }
 }
        private static object KeyToJsonModel(ICertificate cert)
        {
            if (cert == null || !cert.HasPrivateKey)
            {
                return(null);
            }

            return(new {
                exportable = cert.IsPrivateKeyExportable
            });
        }
Example #29
0
        public ICertificate GenerateChildCertificate(ICertificate parent, string areaOfUsage, string holderName, DateTime expirationDate)
        {
            var child = GenerateChildInternal(parent);

            if (StoreGeneratedCertificate(child))
            {
                return(child);
            }

            return(null);
        }
Example #30
0
        private async Task <CdnResponse[]> MatchEndpointsAsync(ICertificate cert, CancellationToken cancellationToken)
        {
            var endpoints = await _azureCdnClient.ListEndpointsAsync(_resourceGroupName, Name, cancellationToken);

            var matchingEndpoints = endpoints
                                    .Where(endpoint => _endpoints.Contains(endpoint.Name, StringComparison.OrdinalIgnoreCase) &&
                                           endpoint.CustomDomains.Any(domain =>
                                                                      cert.HostNames.Contains(domain.HostName, StringComparison.OrdinalIgnoreCase)))
                                    .ToList();

            return(matchingEndpoints.ToArray());
        }
        protected internal virtual bool IsSelfSignedCertificate(ICertificate certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            Span <byte> subject = certificate.SubjectName.RawData.ToArray();
            Span <byte> issuer  = certificate.IssuerName.RawData.ToArray();

            return(subject.SequenceEqual(issuer));
        }
		protected override IClientCertificate OnCertificateSelectionCallback (
			TestContext ctx, string targetHost, ICertificate[] localCertificates,
			ICertificate remoteCertificate, string[] acceptableIssuers)
		{
			LogDebug (ctx, 1, "CertificateSelectionCallback", renegotiationStartedTcs.Task.Status, targetHost,
				localCertificates != null ? localCertificates.Length : -1, remoteCertificate,
				acceptableIssuers != null ? acceptableIssuers.Length : -1);
			if (renegotiationStartedTcs.Task.IsCompleted) {
				ctx.Assert (remoteCertificate, Is.Not.Null, "have remote certificate");
				return ResourceManager.MonkeyCertificate;
			} else {
				ctx.Assert (remoteCertificate, Is.Null, "first call");
				return null;
			}
		}
        /// <summary>
        /// Проверка валидности и отозванности с использованием базовой политики проверки
        /// </summary>
        /// <returns>Список сообщений/ошибок о валидности и/или отозвонности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            bool isValid = certificate.NotBefore < DateTime.Now && DateTime.Now < certificate.NotAfter;
            result.Add(isValid, "Срок действия", String.Format("{0} ({1} - {2})", isValid ? "действителен" : "истек", certificate.NotBefore.ToShortDateString(), certificate.NotAfter.ToShortDateString()));

            result.AddNewLine();

            bool isVerified = certificate.CertificateX509.Verify();
            result.Add(isVerified, "Базовая проверка", isVerified ? "сертификат действителен и не отозван (прошел стандартную проверку)" : "сертификат НЕ валиден (НЕ прошел стандартную проверку)");

            return result;
        }
        /// <summary>
        /// Проверка валидности и отозванности с использованием пользовательской политики проверки
        /// </summary>
        /// <returns>Список сообщений/ошибок о валидности и/или отозвонности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            //создаем цепочку сертификата
            X509Chain ch = new X509Chain();
            //отозванность сертификата хотим получать онлайн
            ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
            //хотим проверить всю цепочку сертификатов
            ch.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
            //проверка валидности самая полная
            ch.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
            //строим цепочку на основе сертификата
            ch.Build(certificate.CertificateX509);

            result.Add("Проверка цепочки сертификатов:");
            result.AddNewLine();

            bool isValid = true;
            foreach (X509ChainElement element in ch.ChainElements)
            {
                bool verify = element.Certificate.Verify();

                isValid = isValid && verify;

                result.Add("  Субъект", element.Certificate.Subject);
                result.Add("  Издатель", element.Certificate.Issuer);
                result.Add("  Отпечаток", element.Certificate.Thumbprint);
                result.Add("  Серийный номер", element.Certificate.SerialNumber);
                result.Add("  Срок действия", String.Format("c {0} по {1}", element.Certificate.NotBefore, element.Certificate.NotAfter));
                result.Add(verify, "  Валиден", verify.ToString());
                result.AddNewLine();
            }

            result.Add(isValid, "Результат проверки цепочки", isValid ? "Сертификат прошел проверку" : "Сертификат НЕ прошел проверку");

            return result;
        }
Example #35
0
        /// <summary>
        /// Подписание данных (файла) с помощью сертификата ЭП 
        /// </summary>
        /// <param name="certificate">Сертификат Электронной Подписи, которым будет подписан файл</param>
        /// <returns>Файл с подписью (в случае прикрепленной подписи будет файл с данными и подписью) </returns>
        public byte[] Sign(ICertificate certificate)
        {
            //создаем контейнер с данными, которые будут подписываться
            var content = new ContentInfo(this.Original);

            //создаем пакет, в который помещаем контейнер с данными и параметры подписи
            //это основной объект, в рамках которого формируются проверки и преобразования подписи
            var cms = new SignedCms(content, this.Detached);

            //создаем подписанта (объект на основе сертификата, который будет подписывать)
            var signer = new CmsSigner(certificate.CertificateX509);

            //с помощью подписанта подписываем пакет так,
            //что теперь в пакете находятся не сами данные,
            //а именно подписанные данные, то есть:
            //  - сама подпись в случае отсоединенной подписи
            //  - подпись с оригинальными данными в случае присоединенной подписи
            cms.ComputeSignature(signer, false);

            // сохраняем подписанный пакет
            byte[] result = cms.Encode();

            return result;
        }
		protected virtual IClientCertificate OnCertificateSelectionCallback (
			TestContext ctx, string targetHost, ICertificate[] localCertificates,
			ICertificate remoteCertificate, string[] acceptableIssuers)
		{
			// Derived classes must override this when using 'NeedCustomCertificateSelectionCallback'.
			throw new NotImplementedException ();
		}
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            result.Add("Отпечаток сертификата", certificate.Thumbprint);
            result.Add("Серийный номер сертификата", certificate.SerialNumber);

            result.AddNewLine(2);
            result.AddRange(new CertificateCommonValidator().Validate(certificate));

            result.AddNewLine(2);
            result.AddRange(new CertificateChainValidator().Validate(certificate));

            result.AddNewLine(2);
            result.AddRange(new CertificateQualifiedValidator().Validate(certificate));

            return result;
        }
Example #38
0
        private void ValidateCertificate(ICertificate certificate)
        {
            //очищаем поле проверки сертификата
            this.textBox_check_result.Text = "";

            //выводим информацию о проверке самого сертификата
            if (certificate != null)
                this.textBox_check_result.Text = _validator.Validate(certificate).ToString();
        }
        /// <summary>
        /// Проверка сертификата на квалифицированность
        /// </summary>
        /// <returns>Список сообщений/ошибок о квалифицированности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            bool isQualified = true;

            result.Add("Проверка квалифицированного сертификатов:");
            result.AddNewLine();

            string subjectCommonName = certificate.SubjectCommonName;

            if (subjectCommonName == "")
            {
                result.AddError("  Не задано наименование (CN) Субъекта");
                isQualified = false;
            }

            if (certificate.Organization == "")
            {
                result.AddError("  Не задана организация (O) Субъекта");
                isQualified = false;
            }

            if (certificate.Locality == "")
            {
                result.AddError("  Не задана расположение (L) Субъекта");
                isQualified = false;
            }

            if (certificate.Email == "")
            {
                result.AddError("  Не задан e-mail (E) Субъекта");
                isQualified = false;
            }

            if (certificate.INN.Trim().Length != 12)
            {
                result.AddError("  ИНН Субъекта должен состоять из 12 знаков");
                isQualified = false;
            }

            if (String.IsNullOrEmpty(certificate.OGRN))
            {
                result.AddError("  Не задан ОГРН Субъекта");
                isQualified = false;
            }

            int CN_fio = 0;
            int CN_org = 0;

            string[] splits = subjectCommonName.Split(new string[1] { " " }, StringSplitOptions.RemoveEmptyEntries);

            if (splits.Length == 3)
            {
                CN_fio += 3;

                if (splits[2].EndsWith("вич") || splits[2].EndsWith("вна"))
                    CN_fio += 1;
            }
            else CN_org += 2;

            if (subjectCommonName.Contains("\""))
                CN_org += 3;
            else CN_fio += 1;

            if (subjectCommonName.ToLower().Contains("ооо") || subjectCommonName.ToLower().Contains("зао") || subjectCommonName.ToLower().Contains("оао") || subjectCommonName.ToLower().Contains("пао") || subjectCommonName.ToLower().StartsWith("ип"))
                CN_org += 2;

            if (CN_fio > CN_org && String.IsNullOrEmpty(certificate.SNILS))
            {
                result.AddError("  Не задан СНИЛС Субъекта");
                isQualified = false;
            }

            result.Add(isQualified, "Результат проверки квалифицированного сертификата", isQualified ? "Сертификат является Квалифицированным" : "Сертификат НЕ является Квалифицированным");

            return result;
        }
Example #40
0
 public bool Matches(ICertificate certificate)
 {
     return certificate.SerialNumber == SerialNumber &&
            certificate.Issuer == CertificateIssuer;
 }
Example #41
0
        /// <summary>
        /// Проверка файла с подписью на валидность подписи
        /// </summary>
        /// <returns>Сообщения (или ошибки) о проверки подписи</returns>
        public ValidationResult Verify()
        {
            var result = new ValidationResult();

            if (this.Signature == null)
            {
                result.AddError("Отсутствует файл с подписью!");
                return result;
            }

            //Создаем пакет с подписью для проверки самой подписи
            SignedCms cms = null;

            if (this.Detached)
            {//отсоединенная подпись

                //создаем контейнер с оригинальными данными, подпись которых будет проверяться
                ContentInfo content = new ContentInfo(this.Original);

                //формируем пакет с оригинальными данными и параметрами подписи
                cms = new SignedCms(content, true);
            }
            else
            {// присоединенная подпись

                //формируем пустой пакет с данными
                //так как в случае присоединенной подписи
                //данные содержатся в самом подписанном файле
                cms = new SignedCms();
            }

            try
            {
                //декодируем файл, содержащий подпись
                //если вылетает ошибка - значит подпись не верна!!!
                cms.Decode(this.Signature);

                //возможно, информация о подписаниях отсутствует
                if (cms.SignerInfos.Count <= 0)
                {
                    result.AddError("Нет информации о подписях (возможно файл не подписан)");
                    return result;
                }

                result.AddInfo("Электронная Подпись Вернa.");
                result.AddNewLine();
                result.Add("Файл подписан следующим(и) сертификатом(и):");

                foreach (SignerInfo si in cms.SignerInfos)
                {
                    var certificate = new Certificate(si.Certificate);
                    if (_certificate == null)
                        _certificate = certificate;

                    result.AddNewLine();
                    result.Add(certificate.SerialNumber + " [" + certificate.Thumbprint + "]");
                    result.Add(certificate.SubjectCommonName);

                    //дергаем время подписания документа текущей подписью
                    for (int i = 0; i < si.SignedAttributes.Count; i++)
                    {
                        if (si.SignedAttributes[i].Oid.Value == "1.2.840.113549.1.9.5") // Oid время подписания
                        {
                            Pkcs9SigningTime pkcs9_time = new Pkcs9SigningTime(si.SignedAttributes[i].Values[0].RawData);
                            result.Add("Дата и Время подписания:  " + pkcs9_time.SigningTime.ToString());
                            break;
                        }
                    }
                }
            }
            catch
            {
                result.AddError("Подпись НЕ верна!");
            }

            return result;
        }