/** * Build and validate a CertPath using the given parameter. * * @param params PKIXBuilderParameters object containing all information to * build the CertPath */ public virtual PkixCertPathBuilderResult Build( PkixBuilderParameters pkixParams) { // search target certificates IX509Selector certSelect = pkixParams.GetTargetCertConstraints(); if (!(certSelect is X509CertStoreSelector)) { throw new PkixCertPathBuilderException( "TargetConstraints must be an instance of " + typeof(X509CertStoreSelector).FullName + " for " + this.GetType() + " class."); } ISet targets = new HashSet(); try { targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores())); // TODO Should this include an entry for pkixParams.GetAdditionalStores() too? } catch (Exception e) { throw new PkixCertPathBuilderException( "Error finding target certificate.", e); } if (targets.IsEmpty) throw new PkixCertPathBuilderException("No certificate found matching targetContraints."); PkixCertPathBuilderResult result = null; IList certPathList = Platform.CreateArrayList(); // check all potential target certificates foreach (X509Certificate cert in targets) { result = Build(cert, pkixParams, certPathList); if (result != null) break; } if (result == null && certPathException != null) { throw new PkixCertPathBuilderException(certPathException.Message, certPathException.InnerException); } if (result == null && certPathException == null) { throw new PkixCertPathBuilderException("Unable to find certificate chain."); } return result; }
public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix) { ISet completeSet = new HashSet(); // get complete CRL(s) try { completeSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores())); } catch (Exception e) { throw new Exception("Exception obtaining complete CRLs.", e); } return completeSet; }
public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix, DateTime currentDate) { ISet initialSet = new HashSet(); // get complete CRL(s) try { initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetAdditionalStores())); initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores())); } catch (Exception e) { throw new Exception("Exception obtaining complete CRLs.", e); } ISet finalSet = new HashSet(); DateTime validityDate = currentDate; if (paramsPkix.Date != null) { validityDate = paramsPkix.Date.Value; } // based on RFC 5280 6.3.3 foreach (X509Crl crl in initialSet) { if (crl.NextUpdate.Value.CompareTo(validityDate) > 0) { X509Certificate cert = crlselect.CertificateChecking; if (cert != null) { if (crl.ThisUpdate.CompareTo(cert.NotAfter) < 0) { finalSet.Add(crl); } } else { finalSet.Add(crl); } } } return finalSet; }
protected virtual ISet GetExtensionOids( bool critical) { X509Extensions extensions = GetX509Extensions(); if (extensions != null) { HashSet set = new HashSet(); foreach (DerObjectIdentifier oid in extensions.ExtensionOids) { X509Extension ext = extensions.GetExtension(oid); if (ext.IsCritical == critical) { set.Add(oid.Id); } } return set; } return null; }
/** * Calculates the union if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the union of both addresses. */ private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { ISet set = new HashSet(); // difficult, adding always all IPs is not wrong if (Arrays.AreEqual(ipWithSubmask1, ipWithSubmask2)) { set.Add(ipWithSubmask1); } else { set.Add(ipWithSubmask1); set.Add(ipWithSubmask2); } return set; }
/** * Returns the intersection of the permitted IP ranges in * <code>permitted</code> with <code>ip</code>. * * @param permitted A <code>Set</code> of permitted IP addresses with * their subnet mask as byte arrays. * @param ips The IP address with its subnet mask. * @return The <code>Set</code> of permitted IP ranges intersected with * <code>ip</code>. */ private ISet IntersectIP(ISet permitted, ISet ips) { ISet intersect = new HashSet(); for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); ) { byte[] ip = Asn1OctetString.GetInstance( ((GeneralSubtree)it.Current).Base.Name).GetOctets(); if (permitted == null) { if (ip != null) { intersect.Add(ip); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { byte[] _permitted = (byte[])it2.Current; intersect.AddAll(IntersectIPRange(_permitted, ip)); } } } return intersect; }
private ISet IntersectEmail(ISet permitted, ISet emails) { ISet intersect = new HashSet(); for (IEnumerator it = emails.GetEnumerator(); it.MoveNext(); ) { String email = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (email != null) { intersect.Add(email); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { String _permitted = (String)it2.Current; intersectEmail(email, _permitted, intersect); } } } return intersect; }
/** * Updates the permitted ISet of these name constraints with the intersection * with the given subtree. * * @param permitted The permitted subtrees */ public void IntersectPermittedSubtree(Asn1Sequence permitted) { IDictionary subtreesMap = Platform.CreateHashtable(); // group in ISets in a map ordered by tag no. for (IEnumerator e = permitted.GetEnumerator(); e.MoveNext(); ) { GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current); int tagNo = subtree.Base.TagNo; if (subtreesMap[tagNo] == null) { subtreesMap[tagNo] = new HashSet(); } ((ISet)subtreesMap[tagNo]).Add(subtree); } for (IEnumerator it = subtreesMap.GetEnumerator(); it.MoveNext(); ) { DictionaryEntry entry = (DictionaryEntry)it.Current; // go through all subtree groups switch ((int)entry.Key ) { case 1: permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail, (ISet)entry.Value); break; case 2: permittedSubtreesDNS = intersectDNS(permittedSubtreesDNS, (ISet)entry.Value); break; case 4: permittedSubtreesDN = IntersectDN(permittedSubtreesDN, (ISet)entry.Value); break; case 6: permittedSubtreesURI = intersectURI(permittedSubtreesURI, (ISet)entry.Value); break; case 7: permittedSubtreesIP = IntersectIP(permittedSubtreesIP, (ISet)entry.Value); break; } } }
private ISet IntersectDN(ISet permitted, ISet dns) { ISet intersect = new HashSet(); for (IEnumerator it = dns.GetEnumerator(); it.MoveNext(); ) { Asn1Sequence dn = Asn1Sequence.GetInstance(((GeneralSubtree)it .Current).Base.Name.ToAsn1Object()); if (permitted == null) { if (dn != null) { intersect.Add(dn); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)_iter.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(dn); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(subtree); } } } } return intersect; }
protected ISet unionDNS(ISet excluded, String dns) { if (excluded.IsEmpty) { if (dns == null) { return excluded; } excluded.Add(dns); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; if (WithinDomain(_permitted, dns)) { union.Add(dns); } else if (WithinDomain(dns, _permitted)) { union.Add(_permitted); } else { union.Add(_permitted); union.Add(dns); } } return union; } }
internal static ISet[] ProcessCrlA1ii( DateTime currentDate, PkixParameters paramsPKIX, X509Certificate cert, X509Crl crl) { ISet deltaSet = new HashSet(); X509CrlStoreSelector crlselect = new X509CrlStoreSelector(); crlselect.CertificateChecking = cert; try { IList issuer = Platform.CreateArrayList(); issuer.Add(crl.IssuerDN); crlselect.Issuers = issuer; } catch (IOException e) { throw new Exception("Cannot extract issuer from CRL." + e, e); } crlselect.CompleteCrlEnabled = true; ISet completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRL(s) try { deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { throw new Exception("Exception obtaining delta CRLs.", e); } } return new ISet[]{ completeSet, deltaSet }; }
internal static PkixPolicyNode PrepareCertB( PkixCertPath certPath, int index, IList[] policyNodes, PkixPolicyNode validPolicyTree, int policyMapping) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // (b) // Asn1Sequence pm = null; try { pm = (Asn1Sequence)Asn1Sequence.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings)); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Policy mappings extension could not be decoded.", ex, certPath, index); } PkixPolicyNode _validPolicyTree = validPolicyTree; if (pm != null) { Asn1Sequence mappings = (Asn1Sequence)pm; IDictionary m_idp = Platform.CreateHashtable(); ISet s_idp = new HashSet(); for (int j = 0; j < mappings.Count; j++) { Asn1Sequence mapping = (Asn1Sequence) mappings[j]; string id_p = ((DerObjectIdentifier) mapping[0]).Id; string sd_p = ((DerObjectIdentifier) mapping[1]).Id; ISet tmp; if (!m_idp.Contains(id_p)) { tmp = new HashSet(); tmp.Add(sd_p); m_idp[id_p] = tmp; s_idp.Add(id_p); } else { tmp = (ISet)m_idp[id_p]; tmp.Add(sd_p); } } IEnumerator it_idp = s_idp.GetEnumerator(); while (it_idp.MoveNext()) { string id_p = (string)it_idp.Current; // // (1) // if (policyMapping > 0) { bool idp_found = false; IEnumerator nodes_i = policyNodes[i].GetEnumerator(); while (nodes_i.MoveNext()) { PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (node.ValidPolicy.Equals(id_p)) { idp_found = true; node.ExpectedPolicies = (ISet)m_idp[id_p]; break; } } if (!idp_found) { nodes_i = policyNodes[i].GetEnumerator(); while (nodes_i.MoveNext()) { PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(node.ValidPolicy)) { ISet pq = null; Asn1Sequence policies = null; try { policies = (Asn1Sequence)PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies); } catch (Exception e) { throw new PkixCertPathValidatorException( "Certificate policies extension could not be decoded.", e, certPath, index); } foreach (Asn1Encodable ae in policies) { PolicyInformation pinfo = null; try { pinfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Policy information could not be decoded.", ex, certPath, index); } if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) { try { pq = PkixCertPathValidatorUtilities .GetQualifierSet(pinfo.PolicyQualifiers); } catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( "Policy qualifier info set could not be decoded.", ex, certPath, index); } break; } } bool ci = false; ISet critExtOids = cert.GetCriticalExtensionOids(); if (critExtOids != null) { ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id); } PkixPolicyNode p_node = (PkixPolicyNode)node.Parent; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(p_node.ValidPolicy)) { PkixPolicyNode c_node = new PkixPolicyNode(Platform.CreateArrayList(), i, (ISet)m_idp[id_p], p_node, pq, id_p, ci); p_node.AddChild(c_node); policyNodes[i].Add(c_node); } break; } } } // // (2) // } else if (policyMapping <= 0) { foreach (PkixPolicyNode node in Platform.CreateArrayList(policyNodes[i])) { if (node.ValidPolicy.Equals(id_p)) { node.Parent.RemoveChild(node); for (int k = i - 1; k >= 0; k--) { foreach (PkixPolicyNode node2 in Platform.CreateArrayList(policyNodes[k])) { if (!node2.HasChildren) { _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode( _validPolicyTree, policyNodes, node2); if (_validPolicyTree == null) break; } } } } } } } } return _validPolicyTree; }
/** * Searches for a holder public key certificate and verifies its * certification path. * * @param attrCert the attribute certificate. * @param pkixParams The PKIX parameters. * @return The certificate path of the holder certificate. * @throws Exception if * <ul> * <li>no public key certificate can be found although holder * information is given by an entity name or a base certificate * ID</li> * <li>support classes cannot be created</li> * <li>no certification path for the public key certificate can * be built</li> * </ul> */ internal static PkixCertPath ProcessAttrCert1( IX509AttributeCertificate attrCert, PkixParameters pkixParams) { PkixCertPathBuilderResult result = null; // find holder PKCs ISet holderPKCs = new HashSet(); if (attrCert.Holder.GetIssuer() != null) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.SerialNumber = attrCert.Holder.SerialNumber; X509Name[] principals = attrCert.Holder.GetIssuer(); for (int i = 0; i < principals.Length; i++) { try { // if (principals[i] is X500Principal) { selector.Issuer = principals[i]; } holderPKCs.AddAll(PkixCertPathValidatorUtilities .FindCertificates(selector, pkixParams.GetStores())); } catch (Exception e) { throw new PkixCertPathValidatorException( "Public key certificate for attribute certificate cannot be searched.", e); } } if (holderPKCs.IsEmpty) { throw new PkixCertPathValidatorException( "Public key certificate specified in base certificate ID for attribute certificate cannot be found."); } } if (attrCert.Holder.GetEntityNames() != null) { X509CertStoreSelector selector = new X509CertStoreSelector(); X509Name[] principals = attrCert.Holder.GetEntityNames(); for (int i = 0; i < principals.Length; i++) { try { // if (principals[i] is X500Principal) { selector.Issuer = principals[i]; } holderPKCs.AddAll(PkixCertPathValidatorUtilities .FindCertificates(selector, pkixParams.GetStores())); } catch (Exception e) { throw new PkixCertPathValidatorException( "Public key certificate for attribute certificate cannot be searched.", e); } } if (holderPKCs.IsEmpty) { throw new PkixCertPathValidatorException( "Public key certificate specified in entity name for attribute certificate cannot be found."); } } // verify cert paths for PKCs PkixBuilderParameters parameters = (PkixBuilderParameters) PkixBuilderParameters.GetInstance(pkixParams); PkixCertPathValidatorException lastException = null; foreach (X509Certificate cert in holderPKCs) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.Certificate = cert; parameters.SetTargetConstraints(selector); PkixCertPathBuilder builder = new PkixCertPathBuilder(); try { result = builder.Build(PkixBuilderParameters.GetInstance(parameters)); } catch (PkixCertPathBuilderException e) { lastException = new PkixCertPathValidatorException( "Certification path for public key certificate of attribute certificate could not be build.", e); } } if (lastException != null) { throw lastException; } return result.CertPath; }
internal static ICollection FindCertificates( X509AttrCertStoreSelector certSelect, IList certStores) { ISet certs = new HashSet(); foreach (IX509Store certStore in certStores) { try { // certs.AddAll(certStore.GetMatches(certSelect)); foreach (X509V2AttributeCertificate ac in certStore.GetMatches(certSelect)) { certs.Add(ac); } } catch (Exception e) { throw new Exception( "Problem while picking certificates from X.509 store.", e); } } return certs; }
/** * Fetches delta CRLs according to RFC 3280 section 5.2.4. * * @param currentDate The date for which the delta CRLs must be valid. * @param paramsPKIX The extended PKIX parameters. * @param completeCRL The complete CRL the delta CRL is for. * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs. * @throws Exception if an exception occurs while picking the delta * CRLs. */ internal static ISet GetDeltaCrls( DateTime currentDate, PkixParameters paramsPKIX, X509Crl completeCRL) { X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector(); // 5.2.4 (a) try { IList deltaSelectIssuer = Platform.CreateArrayList(); deltaSelectIssuer.Add(completeCRL.IssuerDN); deltaSelect.Issuers = deltaSelectIssuer; } catch (IOException e) { new Exception("Cannot extract issuer from CRL.", e); } BigInteger completeCRLNumber = null; try { Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber); if (asn1Object != null) { completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue; } } catch (Exception e) { throw new Exception( "CRL number extension could not be extracted from CRL.", e); } // 5.2.4 (b) byte[] idp = null; try { Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint); if (obj != null) { idp = obj.GetDerEncoded(); } } catch (Exception e) { throw new Exception( "Issuing distribution point extension value could not be read.", e); } // 5.2.4 (d) deltaSelect.MinCrlNumber = (completeCRLNumber == null) ? null : completeCRLNumber.Add(BigInteger.One); deltaSelect.IssuingDistributionPoint = idp; deltaSelect.IssuingDistributionPointEnabled = true; // 5.2.4 (c) deltaSelect.MaxBaseCrlNumber = completeCRLNumber; // find delta CRLs ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate); ISet result = new HashSet(); foreach (X509Crl crl in temp) { if (isDeltaCrl(crl)) { result.Add(crl); } } return result; }
/** * Build and validate a CertPath using the given parameter. * * @param params PKIXBuilderParameters object containing all information to * build the CertPath */ public virtual PkixCertPathBuilderResult Build( PkixBuilderParameters pkixParams) { // search target certificates IX509Selector certSelect = pkixParams.GetTargetConstraints(); if (!(certSelect is X509AttrCertStoreSelector)) { throw new PkixCertPathBuilderException( "TargetConstraints must be an instance of " + typeof(X509AttrCertStoreSelector).FullName + " for " + typeof(PkixAttrCertPathBuilder).FullName + " class."); } ICollection targets; try { targets = PkixCertPathValidatorUtilities.FindCertificates( (X509AttrCertStoreSelector)certSelect, pkixParams.GetStores()); } catch (Exception e) { throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e); } if (targets.Count == 0) { throw new PkixCertPathBuilderException( "No attribute certificate found matching targetContraints."); } PkixCertPathBuilderResult result = null; // check all potential target certificates foreach (IX509AttributeCertificate cert in targets) { X509CertStoreSelector selector = new X509CertStoreSelector(); X509Name[] principals = cert.Issuer.GetPrincipals(); ISet issuers = new HashSet(); for (int i = 0; i < principals.Length; i++) { try { selector.Subject = principals[i]; issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores())); } catch (Exception e) { throw new PkixCertPathBuilderException( "Public key certificate for attribute certificate cannot be searched.", e); } } if (issuers.IsEmpty) throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found."); IList certPathList = Platform.CreateArrayList(); foreach (X509Certificate issuer in issuers) { result = Build(cert, issuer, pkixParams, certPathList); if (result != null) break; } if (result != null) break; } if (result == null && certPathException != null) { throw new PkixCertPathBuilderException( "Possible certificate chain could not be validated.", certPathException); } if (result == null && certPathException == null) { throw new PkixCertPathBuilderException( "Unable to find certificate chain."); } return result; }
private ISet intersectDNS(ISet permitted, ISet dnss) { ISet intersect = new HashSet(); for (IEnumerator it = dnss.GetEnumerator(); it.MoveNext(); ) { String dns = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (dns != null) { intersect.Add(dns); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; if (WithinDomain(_permitted, dns)) { intersect.Add(_permitted); } else if (WithinDomain(dns, _permitted)) { intersect.Add(dns); } } } } return intersect; }
internal static ISet ProcessCrlA1i( DateTime currentDate, PkixParameters paramsPKIX, X509Certificate cert, X509Crl crl) { ISet deltaSet = new HashSet(); if (paramsPKIX.IsUseDeltasEnabled) { CrlDistPoint freshestCRL = null; try { freshestCRL = CrlDistPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.FreshestCrl)); } catch (Exception e) { throw new Exception("Freshest CRL extension could not be decoded from certificate.", e); } if (freshestCRL == null) { try { freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.FreshestCrl)); } catch (Exception e) { throw new Exception("Freshest CRL extension could not be decoded from CRL.", e); } } if (freshestCRL != null) { try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL, paramsPKIX); } catch (Exception e) { throw new Exception( "No new delta CRL locations could be added from Freshest CRL extension.", e); } // get delta CRL(s) try { deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { throw new Exception("Exception obtaining delta CRLs.", e); } } } return deltaSet; }
private ISet intersectURI(ISet permitted, ISet uris) { ISet intersect = new HashSet(); for (IEnumerator it = uris.GetEnumerator(); it.MoveNext(); ) { String uri = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (uri != null) { intersect.Add(uri); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; intersectURI(_permitted, uri, intersect); } } } return intersect; }
internal static PkixPolicyNode WrapupCertG( PkixCertPath certPath, PkixParameters paramsPKIX, ISet userInitialPolicySet, int index, IList[] policyNodes, PkixPolicyNode validPolicyTree, ISet acceptablePolicies) { int n = certPath.Certificates.Count; // // (g) // PkixPolicyNode intersection; // // (g) (i) // if (validPolicyTree == null) { if (paramsPKIX.IsExplicitPolicyRequired) { throw new PkixCertPathValidatorException( "Explicit policy requested but none available.", null, certPath, index); } intersection = null; } else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g) // (ii) { if (paramsPKIX.IsExplicitPolicyRequired) { if (acceptablePolicies.IsEmpty) { throw new PkixCertPathValidatorException( "Explicit policy requested but none available.", null, certPath, index); } else { ISet _validPolicyNodeSet = new HashSet(); for (int j = 0; j < policyNodes.Length; j++) { IList _nodeDepth = policyNodes[j]; for (int k = 0; k < _nodeDepth.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) { foreach (object o in _node.Children) { _validPolicyNodeSet.Add(o); } } } } foreach (PkixPolicyNode _node in _validPolicyNodeSet) { string _validPolicy = _node.ValidPolicy; if (!acceptablePolicies.Contains(_validPolicy)) { // TODO? // validPolicyTree = // removePolicyNode(validPolicyTree, policyNodes, // _node); } } if (validPolicyTree != null) { for (int j = (n - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, node); } } } } } } intersection = validPolicyTree; } else { // // (g) (iii) // // This implementation is not exactly same as the one described in // RFC3280. // However, as far as the validation result is concerned, both // produce // adequate result. The only difference is whether AnyPolicy is // remain // in the policy tree or not. // // (g) (iii) 1 // ISet _validPolicyNodeSet = new HashSet(); for (int j = 0; j < policyNodes.Length; j++) { IList _nodeDepth = policyNodes[j]; for (int k = 0; k < _nodeDepth.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) { foreach (PkixPolicyNode _c_node in _node.Children) { if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(_c_node.ValidPolicy)) { _validPolicyNodeSet.Add(_c_node); } } } } } // // (g) (iii) 2 // IEnumerator _vpnsIter = _validPolicyNodeSet.GetEnumerator(); while (_vpnsIter.MoveNext()) { PkixPolicyNode _node = (PkixPolicyNode)_vpnsIter.Current; string _validPolicy = _node.ValidPolicy; if (!userInitialPolicySet.Contains(_validPolicy)) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, _node); } } // // (g) (iii) 4 // if (validPolicyTree != null) { for (int j = (n - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, node); } } } } intersection = validPolicyTree; } return intersection; }
private ISet unionURI(ISet excluded, String uri) { if (excluded.IsEmpty) { if (uri == null) { return excluded; } excluded.Add(uri); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { String _excluded = (String)_iter.Current; unionURI(_excluded, uri, union); } return union; } }
internal static PkixPolicyNode ProcessCertD( PkixCertPath certPath, int index, ISet acceptablePolicies, PkixPolicyNode validPolicyTree, IList[] policyNodes, int inhibitAnyPolicy) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // // (d) policy Information checking against initial policy and // policy mapping // Asn1Sequence certPolicies = null; try { certPolicies = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Could not read certificate policies extension from certificate.", e, certPath, index); } if (certPolicies != null && validPolicyTree != null) { // // (d) (1) // ISet pols = new HashSet(); foreach (Asn1Encodable ae in certPolicies) { PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); DerObjectIdentifier pOid = pInfo.PolicyIdentifier; pols.Add(pOid.Id); if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(pOid.Id)) { ISet pq = null; try { pq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); } catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( "Policy qualifier info set could not be build.", ex, certPath, index); } bool match = PkixCertPathValidatorUtilities.ProcessCertD1i(i, policyNodes, pOid, pq); if (!match) { PkixCertPathValidatorUtilities.ProcessCertD1ii(i, policyNodes, pOid, pq); } } } if (acceptablePolicies.IsEmpty || acceptablePolicies.Contains(Rfc3280CertPathUtilities.ANY_POLICY)) { acceptablePolicies.Clear(); acceptablePolicies.AddAll(pols); } else { ISet t1 = new HashSet(); foreach (object o in acceptablePolicies) { if (pols.Contains(o)) { t1.Add(o); } } acceptablePolicies.Clear(); acceptablePolicies.AddAll(t1); } // // (d) (2) // if ((inhibitAnyPolicy > 0) || ((i < n) && PkixCertPathValidatorUtilities.IsSelfIssued(cert))) { foreach (Asn1Encodable ae in certPolicies) { PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id)) { ISet _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); IList _nodes = policyNodes[i - 1]; for (int k = 0; k < _nodes.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodes[k]; IEnumerator _policySetIter = _node.ExpectedPolicies.GetEnumerator(); while (_policySetIter.MoveNext()) { object _tmp = _policySetIter.Current; string _policy; if (_tmp is string) { _policy = (string)_tmp; } else if (_tmp is DerObjectIdentifier) { _policy = ((DerObjectIdentifier)_tmp).Id; } else { continue; } bool _found = false; foreach (PkixPolicyNode _child in _node.Children) { if (_policy.Equals(_child.ValidPolicy)) { _found = true; } } if (!_found) { ISet _newChildExpectedPolicies = new HashSet(); _newChildExpectedPolicies.Add(_policy); PkixPolicyNode _newChild = new PkixPolicyNode(Platform.CreateArrayList(), i, _newChildExpectedPolicies, _node, _apq, _policy, false); _node.AddChild(_newChild); policyNodes[i].Add(_newChild); } } } break; } } } PkixPolicyNode _validPolicyTree = validPolicyTree; // // (d) (3) // for (int j = (i - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree, policyNodes, node); if (_validPolicyTree == null) { break; } } } } // // d (4) // ISet criticalExtensionOids = cert.GetCriticalExtensionOids(); if (criticalExtensionOids != null) { bool critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id); IList nodes = policyNodes[i]; for (int j = 0; j < nodes.Count; j++) { PkixPolicyNode node = (PkixPolicyNode)nodes[j]; node.IsCritical = critical; } } return _validPolicyTree; } return null; }
private ISet UnionDN(ISet excluded, Asn1Sequence dn) { if (excluded.IsEmpty) { if (dn == null) { return excluded; } excluded.Add(dn); return excluded; } else { ISet intersect = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(subtree); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(dn); } else { intersect.Add(subtree); intersect.Add(dn); } } return intersect; } }
/** * Obtain and validate the certification path for the complete CRL issuer. * If a key usage extension is present in the CRL issuer's certificate, * verify that the cRLSign bit is set. * * @param crl CRL which contains revocation information for the certificate * <code>cert</code>. * @param cert The attribute certificate or certificate to check if it is * revoked. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>. * @param defaultCRLSignKey The public key of the issuer certificate * <code>defaultCRLSignCert</code>. * @param paramsPKIX paramsPKIX PKIX parameters. * @param certPathCerts The certificates on the certification path. * @return A <code>Set</code> with all keys of possible CRL issuer * certificates. * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or * some error occurs. */ internal static ISet ProcessCrlF( X509Crl crl, object cert, X509Certificate defaultCRLSignCert, AsymmetricKeyParameter defaultCRLSignKey, PkixParameters paramsPKIX, IList certPathCerts) { // (f) // get issuer from CRL X509CertStoreSelector selector = new X509CertStoreSelector(); try { selector.Subject = crl.IssuerDN; } catch (IOException e) { throw new Exception( "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e); } // get CRL signing certs IList coll = Platform.CreateArrayList(); try { CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetStores())); CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetAdditionalStores())); } catch (Exception e) { throw new Exception("Issuer certificate for CRL cannot be searched.", e); } coll.Add(defaultCRLSignCert); IEnumerator cert_it = coll.GetEnumerator(); IList validCerts = Platform.CreateArrayList(); IList validKeys = Platform.CreateArrayList(); while (cert_it.MoveNext()) { X509Certificate signingCert = (X509Certificate)cert_it.Current; /* * CA of the certificate, for which this CRL is checked, has also * signed CRL, so skip the path validation, because is already done */ if (signingCert.Equals(defaultCRLSignCert)) { validCerts.Add(signingCert); validKeys.Add(defaultCRLSignKey); continue; } try { // CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX"); PkixCertPathBuilder builder = new PkixCertPathBuilder(); selector = new X509CertStoreSelector(); selector.Certificate = signingCert; PkixParameters temp = (PkixParameters)paramsPKIX.Clone(); temp.SetTargetCertConstraints(selector); PkixBuilderParameters parameters = (PkixBuilderParameters) PkixBuilderParameters.GetInstance(temp); /* * if signingCert is placed not higher on the cert path a * dependency loop results. CRL for cert is checked, but * signingCert is needed for checking the CRL which is dependent * on checking cert because it is higher in the cert path and so * signing signingCert transitively. so, revocation is disabled, * forgery attacks of the CRL are detected in this outer loop * for all other it must be enabled to prevent forgery attacks */ if (certPathCerts.Contains(signingCert)) { parameters.IsRevocationEnabled = false; } else { parameters.IsRevocationEnabled = true; } IList certs = builder.Build(parameters).CertPath.Certificates; validCerts.Add(signingCert); validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0)); } catch (PkixCertPathBuilderException e) { throw new Exception("Internal error.", e); } catch (PkixCertPathValidatorException e) { throw new Exception("Public key of issuer certificate of CRL could not be retrieved.", e); } //catch (Exception e) //{ // throw new Exception(e.Message); //} } ISet checkKeys = new HashSet(); Exception lastException = null; for (int i = 0; i < validCerts.Count; i++) { X509Certificate signCert = (X509Certificate)validCerts[i]; bool[] keyusage = signCert.GetKeyUsage(); if (keyusage != null && (keyusage.Length < 7 || !keyusage[CRL_SIGN])) { lastException = new Exception( "Issuer certificate key usage extension does not permit CRL signing."); } else { checkKeys.Add(validKeys[i]); } } if ((checkKeys.Count == 0) && lastException == null) { throw new Exception("Cannot find a valid issuer certificate."); } if ((checkKeys.Count == 0) && lastException != null) { throw lastException; } return checkKeys; }
private ISet UnionEmail(ISet excluded, String email) { if (excluded.IsEmpty) { if (email == null) { return excluded; } excluded.Add(email); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { String _excluded = (String)it.Current; unionEmail(_excluded, email, union); } return union; } }
/** * Checks a distribution point for revocation information for the * certificate <code>cert</code>. * * @param dp The distribution point to consider. * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status should be * checked. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>. * @param defaultCRLSignKey The public key of the issuer certificate * <code>defaultCRLSignCert</code>. * @param certStatus The current certificate revocation status. * @param reasonMask The reasons mask which is already checked. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ private static void CheckCrl( DistributionPoint dp, PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate defaultCRLSignCert, AsymmetricKeyParameter defaultCRLSignKey, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts) //throws AnnotatedException { DateTime currentDate = DateTime.UtcNow; if (validDate.Ticks > currentDate.Ticks) { throw new Exception("Validation time is in future."); } // (a) /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional * CRLs must be enabled in the ExtendedPKIXParameters and are in * getAdditionalStore() */ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; IEnumerator crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { X509Crl crl = (X509Crl)crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); // (e) /* * The reasons mask is updated at the end, so only valid CRLs * can update it. If this CRL does not contain new reasons it * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) { continue; } // (f) ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, paramsPKIX, certPathCerts); // (g) AsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, key); } /* * CRL must be be valid at the current time, not the validation * time. If a certificate is revoked with reason keyCompromise, * cACompromise, it can be used for forgery, also for the past. * This reason may not be contained in older CRLs. */ /* * in the chain model signatures stay valid also after the * certificate has been expired, so they do not have to be in * the CRL validity time */ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel) { /* * if a certificate has expired, but was revoked, it is not * more in the CRL, so it would be regarded as valid if the * first check is not done */ if (cert.NotAfter.Ticks < crl.ThisUpdate.Ticks) { throw new Exception("No valid CRL for current time found."); } } Rfc3280CertPathUtilities.ProcessCrlB1(dp, cert, crl); // (b) (2) Rfc3280CertPathUtilities.ProcessCrlB2(dp, cert, crl); // (c) Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX); // (j) Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, cert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) { certStatus.Status = CertStatus.Unrevoked; } // update reasons mask reasonMask.AddReasons(interimReasonsMask); ISet criticalExtensions = crl.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("CRL contains unsupported critical extensions."); } if (deltaCRL != null) { criticalExtensions = deltaCRL.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("Delta CRL contains unsupported critical extension."); } } validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } }
/** * Returns the union of the excluded IP ranges in <code>excluded</code> * with <code>ip</code>. * * @param excluded A <code>Set</code> of excluded IP addresses with their * subnet mask as byte arrays. * @param ip The IP address with its subnet mask. * @return The <code>Set</code> of excluded IP ranges unified with * <code>ip</code> as byte arrays. */ private ISet UnionIP(ISet excluded, byte[] ip) { if (excluded.IsEmpty) { if (ip == null) { return excluded; } excluded.Add(ip); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { byte[] _excluded = (byte[])it.Current; union.AddAll(UnionIPRange(_excluded, ip)); } return union; } }
public void Save(Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } // // handle the key // var keyS = new Asn1EncodableVector(); foreach (string name in _keys.Keys) { var kSalt = new byte[SaltSize]; random.NextBytes(kSalt); var privKey = (AsymmetricKeyEntry) _keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(_keyAlgorithm, password, kSalt, MinIterations, privKey.Key); var kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } kName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } var kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); var keyString = new BerOctetString(derEncodedBytes); // // certificate processing // var cSalt = new byte[SaltSize]; random.NextBytes(cSalt); var certSeq = new Asn1EncodableVector(); var cParams = new Pkcs12PbeParams(cSalt, MinIterations); var cAlgId = new AlgorithmIdentifier(_certAlgorithm, cParams.ToAsn1Object()); ISet doneCerts = new HashSet(); foreach (string name in _keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); var cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); var fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } var sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } foreach (string certId in _certs.Keys) { var cert = (X509CertificateEntry) _certs[certId]; if (_keys[certId] != null) { continue; } var cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); var fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } var sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } foreach (CertId certId in _chainCerts.Keys) { var cert = (X509CertificateEntry) _chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) { continue; } var cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); var fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } var sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes); var cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); ContentInfo[] info = {new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object())}; byte[] data = new AuthenticatedSafe(info).GetEncoded(_useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber); var mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // var mSalt = new byte[20]; random.NextBytes(mSalt); byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, MinIterations, password, false, data); var algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); var dInfo = new DigestInfo(algId, mac); var mData = new MacData(dInfo, mSalt, MinIterations); // // output the Pfx // var pfx = new Pfx(mainInfo, mData); DerOutputStream derOut; if (_useDerEncoding) { derOut = new DerOutputStream(stream); } else { derOut = new BerOutputStream(stream); } derOut.WriteObject(pfx); }
/** * Calculates the interesction if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the single IP address with its subnet * mask as a byte array or an empty <code>Set</code>. */ private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { if (ipWithSubmask1.Length != ipWithSubmask2.Length) { //Collections.EMPTY_SET; return new HashSet(); } byte[][] temp = ExtractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2); byte[] ip1 = temp[0]; byte[] subnetmask1 = temp[1]; byte[] ip2 = temp[2]; byte[] subnetmask2 = temp[3]; byte[][] minMax = MinMaxIPs(ip1, subnetmask1, ip2, subnetmask2); byte[] min; byte[] max; max = Min(minMax[1], minMax[3]); min = Max(minMax[0], minMax[2]); // minimum IP address must be bigger than max if (CompareTo(min, max) == 1) { //return Collections.EMPTY_SET; return new HashSet(); } // OR keeps all significant bits byte[] ip = Or(minMax[0], minMax[2]); byte[] subnetmask = Or(subnetmask1, subnetmask2); //return new HashSet( ICollectionsingleton(IpWithSubnetMask(ip, subnetmask)); ISet hs = new HashSet(); hs.Add(IpWithSubnetMask(ip, subnetmask)); return hs; }
private PkixCertPathBuilderResult Build( IX509AttributeCertificate attrCert, X509Certificate tbvCert, PkixBuilderParameters pkixParams, IList tbvPath) { // If tbvCert is readily present in tbvPath, it indicates having run // into a cycle in the // PKI graph. if (tbvPath.Contains(tbvCert)) return null; // step out, the certificate is not allowed to appear in a certification // chain if (pkixParams.GetExcludedCerts().Contains(tbvCert)) return null; // test if certificate path exceeds maximum length if (pkixParams.MaxPathLength != -1) { if (tbvPath.Count - 1 > pkixParams.MaxPathLength) return null; } tbvPath.Add(tbvCert); PkixCertPathBuilderResult builderResult = null; // X509CertificateParser certParser = new X509CertificateParser(); PkixAttrCertPathValidator validator = new PkixAttrCertPathValidator(); try { // check whether the issuer of <tbvCert> is a TrustAnchor if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null) { PkixCertPath certPath = new PkixCertPath(tbvPath); PkixCertPathValidatorResult result; try { result = validator.Validate(certPath, pkixParams); } catch (Exception e) { throw new Exception("Certification path could not be validated.", e); } return new PkixCertPathBuilderResult(certPath, result.TrustAnchor, result.PolicyTree, result.SubjectPublicKey); } else { // add additional X.509 stores from locations in certificate try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams); } catch (CertificateParsingException e) { throw new Exception("No additional X.509 stores can be added from certificate locations.", e); } // try to get the issuer certificate from one of the stores ISet issuers = new HashSet(); try { issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams)); } catch (Exception e) { throw new Exception("Cannot find issuer certificate for certificate in certification path.", e); } if (issuers.IsEmpty) throw new Exception("No issuer certificate for certificate in certification path found."); foreach (X509Certificate issuer in issuers) { // if untrusted self signed certificate continue if (PkixCertPathValidatorUtilities.IsSelfIssued(issuer)) continue; builderResult = Build(attrCert, issuer, pkixParams, tbvPath); if (builderResult != null) break; } } } catch (Exception e) { certPathException = new Exception("No valid certification path could be build.", e); } if (builderResult == null) { tbvPath.Remove(tbvCert); } return builderResult; }