private async void LoadCryptoUi()
        {
            switch (CryptoProvider)
            {
            case "Certificate":
                CertificateSelector.Visibility = Visibility.Collapsed;

                await Task.Run(async() =>
                {
                    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    store.Open(OpenFlags.ReadOnly);

                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Certificates.Clear();
                        foreach (var certificate in store.Certificates)
                        {
                            Certificates.Add(certificate);
                        }

                        // Auto-assign the existing certificate if present
                        if (Store.Model.Key is CryptoKey protectedKey &&
                            protectedKey.PrimaryProtector.Provider is CertificateCryptoProvider provider &&
                            provider.Certificate != null)
                        {
                            CertificateSelector.SelectedItem = provider.Certificate;
                        }

                        CertificateSelector.Visibility = Visibility.Visible;
                    });
                }).ConfigureAwait(false);
Exemple #2
0
        public JwtTokenParserBuilder AddCertificate(params X509Certificate2[] certificate)
        {
            certificate.Verify(nameof(certificate)).IsNotNull();

            certificate.ForEach(x => Certificates.Add(x.Thumbprint, x));
            return(this);
        }
Exemple #3
0
        public JwtTokenParserBuilder AddCertificate(X509Certificate2 certificate)
        {
            Verify.IsNotNull(nameof(certificate), certificate);

            Certificates.Add(certificate.Thumbprint, certificate);
            return(this);
        }
Exemple #4
0
        // methods

        public void Add(X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
            if (!IsOpen)
            {
                throw new CryptographicException(Locale.GetText("Store isn't opened."));
            }
            if (IsReadOnly)
            {
                throw new CryptographicException(Locale.GetText("Store is read-only."));
            }

            if (!Exists(certificate))
            {
                try {
                    store.Import(new MX.X509Certificate(certificate.RawData));
                }
                finally {
                    Certificates.Add(certificate);
                }
            }
        }
Exemple #5
0
        public void AddRange(X509Certificate2Collection certificates)
        {
            if (certificates == null)
            {
                throw new ArgumentNullException("certificates");
            }

            if (certificates.Count == 0)
            {
                return;
            }

            if (!IsOpen)
            {
                throw new CryptographicException(Locale.GetText("Store isn't opened."));
            }
            if (IsReadOnly)
            {
                throw new CryptographicException(Locale.GetText("Store is read-only."));
            }

            foreach (X509Certificate2 certificate in certificates)
            {
                if (!Exists(certificate))
                {
                    try {
                        store.Import(new MX.X509Certificate(certificate.RawData));
                    }
                    finally {
                        Certificates.Add(certificate);
                    }
                }
            }
        }
Exemple #6
0
        public void Open(OpenFlags flags)
        {
            if (String.IsNullOrEmpty(_name))
            {
                throw new CryptographicException(Locale.GetText("Invalid store name (null or empty)."));
            }

            /* keep existing Mono installations (pre 2.0) compatible with new stuff */
            string name;

            switch (_name)
            {
            case "Root":
                name = "Trust";
                break;

            default:
                name = _name;
                break;
            }

            bool create = ((flags & OpenFlags.OpenExistingOnly) != OpenFlags.OpenExistingOnly);

            store = Factory.Open(name, create);
            if (store == null)
            {
                throw new CryptographicException(Locale.GetText("Store {0} doesn't exists.", _name));
            }
            _flags = flags;

            foreach (MX.X509Certificate x in store.Certificates)
            {
                Certificates.Add(new X509Certificate2(x.RawData));
            }
        }
        internal X509CertificateEndpointIdentity(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader));
            }

            reader.MoveToContent();
            if (reader.IsEmptyElement)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));
            }

            reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace);
            while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace))
            {
                X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadElementString()));
                if (Certificates.Count == 0)
                {
                    // This is the first certificate. We assume this as the primary
                    // certificate and initialize the base class.
                    Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty));
                }

                Certificates.Add(certificate);
            }

            reader.ReadEndElement();

            if (Certificates.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));
            }
        }
Exemple #8
0
 /// <summary>
 /// Add a X509Certificate to the Certificates collection.
 /// </summary>
 /// <param name="certificate">The certificate to be added.</param>
 internal void AddCertificate(X509Certificate certificate)
 {
     if (null == Certificates)
     {
         Certificates = new X509CertificateCollection();
     }
     Certificates.Add(certificate);
 }
Exemple #9
0
 void decodeCertificates(Asn1Reader asn) {
     if (asn.PayloadLength == 0) { return; }
     Int32 offset = asn.Offset;
     asn.MoveNext();
     do {
         Certificates.Add(new X509Certificate2(asn.GetTagRawData()));
     } while (asn.MoveNextCurrentLevel());
     asn.MoveToPoisition(offset);
 }
Exemple #10
0
		public void LoadCertificatesFromStore() {
			int lastSelectedCertItem = CertificateItem;
			List<X509Certificate2> certs = SignatureProcessor.GetAllCertificatesFromStore(CertificateStore);
			Certificates.Clear();
			foreach(X509Certificate2 c in certs.Where((cert) => cert.HasPrivateKey)) {
				Certificates.Add(c);
			}
			CertificateItem = lastSelectedCertItem;
		}
Exemple #11
0
 /// <summary>
 /// Initializes an instance of <see cref="X509Data"/>.
 /// </summary>
 /// <exception cref="ArgumentNullException">If 'certificate' is null</exception>
 public X509Data(X509Certificate2 certificate)
 {
     if (certificate != null)
     {
         Certificates.Add(Convert.ToBase64String(certificate.RawData));
     }
     else
     {
         throw LogHelper.LogExceptionMessage(new ArgumentNullException(nameof(certificate)));
     }
 }
        public X509CertificateEndpointIdentity(X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(certificate));
            }

            Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty));

            Certificates.Add(certificate);
        }
Exemple #13
0
        public void ScanCurrentPath(bool searchSubfolders = false)
        {
            var certs = certificateOperations.GetCertificates(ScanPath.ToString(), searchSubfolders);

            Certificates.Clear();
            foreach (var cert in certs)
            {
                Certificates.Add(cert);
            }

            NotifyProperyChanged(nameof(CertificatesListText));
        }
Exemple #14
0
        /// <summary>
        /// Attaches a timestamp to signed CMS object.
        /// </summary>
        /// <param name="timestamp">TSP response returned from Time-Stamping Authority.</param>
        /// <param name="signerInfoIndex">Signature index to attach the timestamp.</param>
        /// <exception cref="NotSupportedException">
        /// Time-Stamp Response contains invalid content type.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Data returned from Time-Stamping Authority does not contain valid response.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     <strong>response</strong> parameter is null.
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        ///     <strong>signerInfoIndex</strong> value exceeds the number of attached signatures.
        /// </exception>
        /// <remarks>Call <see cref="Encode"/> method to get timestamped object.</remarks>
        public void AddTimestamp(TspResponse timestamp, Int32 signerInfoIndex)
        {
            if (timestamp == null)
            {
                throw new ArgumentNullException(nameof(timestamp));
            }
            if (timestamp.Status.ResponseStatus != TspResponseStatus.Granted || timestamp.Status.ErrorCode != TspFailureStatus.None)
            {
                throw new ArgumentException("The time-stamp response is not successful.");
            }

            X509Attribute      attribute;
            DefaultSignedPkcs7 tspCms = timestamp.GetSignedCms();

            switch (timestamp.ResponseType.Value)
            {
            case PKCS_7_DATA:
                // add timestamp signing certs to original CMS
                foreach (X509Certificate2 tspCert in tspCms.Certificates)
                {
                    if (!Certificates.Contains(tspCert))
                    {
                        Certificates.Add(tspCert);
                    }
                }
                // for Authenticode timestamp, we add SignerInfo from timestamp CMS
                var asn = new Asn1Reader(tspCms.SignerInfos.Encode());
                attribute = new X509Attribute(new Oid(COUNTER_SIGN), asn.GetPayload());
                break;

            case TST_TOKEN_INFO:
                attribute = new X509Attribute(new Oid(RFC_COUNTER_SIGN), tspCms.RawData);
                break;

            default: throw new NotSupportedException("Time-Stamp response contains invalid content type.");
            }

            var           signerInfoBuilder = new PkcsSignerInfoBuilder(SignerInfos[signerInfoIndex]);
            X509Attribute attr = signerInfoBuilder.UnauthenticatedAttributes[COUNTER_SIGN];

            if (attr != null)
            {
                signerInfoBuilder.UnauthenticatedAttributes.Remove(attr);
            }
            attr = signerInfoBuilder.UnauthenticatedAttributes[RFC_COUNTER_SIGN];
            if (attr != null)
            {
                signerInfoBuilder.UnauthenticatedAttributes.Remove(attr);
            }
            signerInfoBuilder.AddUnauthenticatedAttribute(attribute);
            SignerInfos[signerInfoIndex] = signerInfoBuilder.Encode();
        }
Exemple #15
0
        static MasterCardFtpClientBase()
        {
            // Popualte the Certificates collection.
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName,
                                                                   CloudConfigurationManager.GetSetting(MasterCardFtpConstants.UserName),
                                                                   true).OfType <X509Certificate2>().FirstOrDefault();

            store.Close();
            Certificates.Add(certificate);
        }
        public void RefreshCertificates()
        {
            var originallySelected = this.SelectedCertificate;

            Certificates.Clear();
            var certStore = WindowsCertificateStore.LoadPersonalCurrentUser();

            certStore.GetCertificatesWithKey().ForEach(c => Certificates.Add(new CertificateItem(c)));

            if (originallySelected != null)
            {
                SelectedCertificate = Certificates.FirstOrDefault(c => c.CertificateWithKey.Certificate.Equals(originallySelected.CertificateWithKey.Certificate));
            }
        }
Exemple #17
0
        public Crypter()
        {
            // set certificates
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            foreach (var cert in store.Certificates)
            {
                if (Regex.IsMatch(cert.FriendlyName, @"test"))
                {
                    Certificates.Add(cert);
                }
            }
        }
Exemple #18
0
        public void RefreshCertificates()
        {
            var originallySelected = this.SelectedCertificate;

            Certificates.Clear();
            var certStore = WindowsCertificateStore.LoadPersonalCurrentUser();

            foreach (var item in certStore.GetCertificatesWithKey().Select(c => new CertificateItem(c)).OrderBy(i => i.ToString()))
            {
                Certificates.Add(item);
            }
            if (originallySelected != null)
            {
                SelectedCertificate = Certificates.FirstOrDefault(c => c.CertificateWithKey.Certificate.Equals(originallySelected.CertificateWithKey.Certificate));
            }
        }
Exemple #19
0
 /// <summary>
 /// Initializes an instance of <see cref="X509Data"/>.
 /// </summary>
 /// <exception cref="ArgumentNullException">If 'certificates' is null</exception>
 public X509Data(IEnumerable <X509Certificate2> certificates)
 {
     if (certificates != null)
     {
         foreach (var certificate in certificates)
         {
             if (certificate != null)
             {
                 Certificates.Add(Convert.ToBase64String(certificate.RawData));
             }
         }
     }
     else
     {
         throw LogHelper.LogExceptionMessage(new ArgumentNullException(nameof(certificates)));
     }
 }
 void AddCert(X509Certificate2[] chain, string type)
 {
     if (chain?.Any() == true)
     {
         var crt = new Certificate()
         {
             Chain        = chain,
             Certificate2 = chain[0],
             Type         = type + " Certificate",
             IsValid      = chain.ValidateChain(),
             Name         = chain[0].GetCertDisplayName(),
             NotBefore    = chain[0].NotBefore.ToString("g"),
             NotAfter     = chain[0].NotAfter.ToString("g"),
         };
         crt.IconName = crt.IsValid ? "LockValid" : "LockInvalid";
         Certificates.Add(crt);
     }
 }
        public X509CertificateEndpointIdentity(X509Certificate2 primaryCertificate, X509Certificate2Collection supportingCertificates)
        {
            if (primaryCertificate == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(primaryCertificate));
            }

            if (supportingCertificates == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(supportingCertificates));
            }

            Initialize(new Claim(ClaimTypes.Thumbprint, primaryCertificate.GetCertHash(), Rights.PossessProperty));

            Certificates.Add(primaryCertificate);

            for (int i = 0; i < supportingCertificates.Count; ++i)
            {
                Certificates.Add(supportingCertificates[i]);
            }
        }
Exemple #22
0
        private async Task Load()
        {
            IsBusy = true;
            var certificates = await _certificateStore.GetIdentityCertificates();

            Certificates.Clear();
            foreach (var certificate in certificates)
            {
                var record = new CertificateViewModel
                {
                    IsSelected     = false,
                    Name           = certificate.Name,
                    CreateDateTime = certificate.CreateDateTime
                };
                Certificates.Add(record);
                if (certificate.IsSelected)
                {
                    ActiveCertificate = record;
                }
            }

            ((Command)DeleteCertificateCommand).ChangeCanExecute();
            IsBusy = false;
        }
Exemple #23
0
        public void Open(OpenFlags flags)
        {
            if (String.IsNullOrEmpty(_name))
            {
                throw new CryptographicException(Locale.GetText("Invalid store name (null or empty)."));
            }

            /* keep existing Mono installations (pre 2.0) compatible with new stuff */
            string name;

            switch (_name)
            {
#if !MX_WINCRYPTO
            case "Root":
                name = "Trust";
                break;
#endif
            default:
                name = _name;
                break;
            }

            store = Factory.Open(name, flags);
            if (store == null)
            {
                throw new CryptographicException(Locale.GetText("Store {0} doesn't exists.", _name));
            }
            _flags = flags;

            foreach (MX.X509Certificate x in store.Certificates)
            {
                var cert2 = new X509Certificate2(x.RawData);
                cert2.Impl.PrivateKey = x.RSA;
                Certificates.Add(cert2);
            }
        }
        private async Task GetCertificates(CertificatesFilter filters, bool forceCloud = false)
        {
            try
            {
                using (var dlg = this.Dialogs.Loading("Progress (No Cancel)"))
                {
                    Certificates.Clear();

                    var buildingUsers = await _buildingService.GetBuildingUsers(BuildingId, false);

                    var cnUsers = buildingUsers.Where(x => x.UserPrivileges.Contains("CN")).ToList();

                    var downloadedCertsResult = await _certificatesService.GetAllDownloadedCertificates(BuildingId);

                    if (!downloadedCertsResult.Success)
                    {
                        Dialogs.Toast(downloadedCertsResult.Message);
                        return;
                    }

                    var downloadedCertificates = downloadedCertsResult.ResultObject as List <Certificate>;

                    if (downloadedCertificates != null)
                    {
                        DownloadedCertificates = downloadedCertificates;

                        var certsResult = await _certificatesService.GetAllCertificates(filters, BuildingId, forceCloud);

                        if (!certsResult.Success)
                        {
                            Dialogs.Toast(certsResult.Message);
                            return;
                        }

                        var certsAndNumber = certsResult.ResultObject as Tuple <IEnumerable <CertificateRow>, int, int>;
                        if (certsAndNumber == null)
                        {
                            return;
                        }

                        Dialogs.Toast("Results; " + certsAndNumber.Item3 + " records returned out of " + certsAndNumber.Item2 + " found.");

                        var certificates = certsAndNumber.Item1;

                        if (certificates != null && certificates.Any())
                        {
                            foreach (var certificate in certificates)
                            {
                                var selectableCertificate = new CertificateRowSelect()
                                {
                                    Certificate = certificate, IsSelected = false
                                };
                                //if (downloadedCertificates.Any(x => x.CertId == certificate.CertId))
                                //    selectableCertificate.IsSelected = true;
                                Certificates.Add(selectableCertificate);
                            }
                        }

                        foreach (var cert in Certificates)
                        {
                            cert.Certificate.Contractor = cnUsers?.FirstOrDefault(x => x.UserId == cert.Certificate.ConUserId)?.UserFullname;
                        }
                    }
                }
            }
            catch (ServiceAuthenticationException e)
            {
                var result = await TryToLogin();

                if (!result)
                {
                    await NavigationService.NavigateToAsync <LoginViewModel>();
                }
                else
                {
                    await GetCertificates(filters, forceCloud);
                }
            }
            catch (Exception e)
            {
                await ShowErrorAlert(e.Message);
            }
        }
        public void SetCertificates()
        {
            try
            {
                Certificates.Clear();
                var localStore   = new X509Store(StoreLocation.CurrentUser);
                var machineStore = new X509Store(StoreLocation.LocalMachine);

                localStore.Open(OpenFlags.ReadOnly);
                if (localStore.Certificates.Count > 0)
                {
                    foreach (var certificate in localStore.Certificates)
                    {
                        var cert = new Certificate();
                        if (IsSigningCert(certificate))
                        {
                            if (string.IsNullOrEmpty(certificate.FriendlyName))
                            {
                                cert.FriendlyName = certificate.SubjectName.Name;
                            }
                            else
                            {
                                cert.FriendlyName = certificate.FriendlyName;
                            }

                            cert.IssuerName = certificate.IssuerName.Name;
                            cert.ThumbPrint = certificate.Thumbprint;

                            Certificates.Add(cert);
                        }
                    }
                }

                machineStore.Open(OpenFlags.ReadOnly);
                if (machineStore.Certificates.Count > 0)
                {
                    foreach (var certificate in machineStore.Certificates)
                    {
                        var cert = new Certificate();

                        if (IsSigningCert(certificate))
                        {
                            if (String.IsNullOrEmpty(certificate.FriendlyName))
                            {
                                cert.FriendlyName = certificate.SubjectName.Name;
                            }
                            else
                            {
                                cert.FriendlyName = certificate.FriendlyName;
                            }

                            cert.IssuerName = certificate.IssuerName.Name;
                            cert.ThumbPrint = certificate.Thumbprint;

                            Certificates.Add(cert);
                        }
                    }
                }
                localStore.Close();
                machineStore.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #26
0
        private async Task HandleUploadCertificateCommand()
        {
            var expectedFormat = ZXing.BarcodeFormat.QR_CODE;
            var opts           = new ZXing.Mobile.MobileBarcodeScanningOptions
            {
                PossibleFormats = new List <ZXing.BarcodeFormat> {
                    expectedFormat
                }
            };
            var scanPage = new ZXingScannerPage(opts);

            scanPage.OnScanResult += (result) =>
            {
                scanPage.IsScanning = false;
                Device.BeginInvokeOnMainThread(async() =>
                {
                    var value = result?.Text ?? string.Empty;
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        return;
                    }

                    var splitted = value.Split('$');
                    if (splitted.Count() != 3)
                    {
                        return;
                    }

                    var url      = splitted.First();
                    var password = splitted[1];
                    var name     = splitted[2];
                    using (var httpClient = new HttpClient())
                    {
                        var request = new HttpRequestMessage
                        {
                            RequestUri = new Uri(url),
                            Method     = HttpMethod.Get
                        };
                        var httpResult = await httpClient.SendAsync(request);
                        var json       = await httpResult.Content.ReadAsStringAsync();
                        var base64     = JsonConvert.DeserializeObject <JObject>(json)["file"].ToString();
                        await _certificateStore.Add(new MedikitCertificate
                        {
                            CreateDateTime = DateTime.UtcNow,
                            IsSelected     = false,
                            Name           = name,
                            Password       = password,
                            Payload        = base64,
                            Type           = MedikitCertificateTypes.IDENTITY
                        });
                        Certificates.Add(new CertificateViewModel
                        {
                            IsSelected = false,
                            Name       = name
                        });
                        await _navigation.PopAsync();
                        _alertService.DisplayAlert(AppResources.Success, AppResources.CertificateAdded, AppResources.Ok);
                    }
                });
            };
            scanPage.Title = AppResources.ScanCertificate;
            await _navigation.PushAsync(scanPage);
        }
 /// <summary>
 /// Import the specified certificate and its associated private key.
 /// </summary>
 /// <param name="certificate">The certificate and key, in PKCS12 format.</param>
 /// <param name="passphrase">The passphrase that protects the private key.</param>
 public void Import(byte[] certificate, string passphrase)
 {
     Certificates.Add(new X509Certificate2(certificate, passphrase));
 }
 public void AddCertificate(byte[] certificate)
 {
     Certificates.Add(certificate);
 }