List of usage examples for org.bouncycastle.asn1.x509 GeneralName getName
public ASN1Encodable getName()
From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.CRLDistributionPointRevocationChecker.java
License:Apache License
/** * Gets the distribution points.//from ww w . jav a 2 s . c o m * * @param cert the cert * @return the url distribution points */ private URI[] getDistributionPoints(final X509Certificate cert) { final List<DistributionPoint> points; try { points = new ExtensionReader(cert).readCRLDistributionPoints(); } catch (final RuntimeException e) { logger.error("Error reading CRLDistributionPoints extension field on {}", CertUtils.toString(cert), e); return new URI[0]; } final List<URI> urls = new ArrayList<>(); if (points != null) { for (final DistributionPoint point : points) { final DistributionPointName pointName = point.getDistributionPoint(); if (pointName != null) { final ASN1Sequence nameSequence = ASN1Sequence.getInstance(pointName.getName()); for (int i = 0; i < nameSequence.size(); i++) { final GeneralName name = GeneralName.getInstance(nameSequence.getObjectAt(i)); logger.debug("Found CRL distribution point {}.", name); try { addURL(urls, DERIA5String.getInstance(name.getName()).getString()); } catch (final RuntimeException e) { logger.warn("{} not supported. String or GeneralNameList expected.", pointName); } } } } } return urls.toArray(new URI[urls.size()]); }
From source file:org.jruby.ext.openssl.OCSPRequest.java
License:Common Public License
@JRubyMethod(name = "verify", rest = true) public IRubyObject verify(IRubyObject[] args) { Ruby runtime = getRuntime();/*from www . j a v a2s . com*/ ThreadContext context = runtime.getCurrentContext(); int flags = 0; boolean ret = false; if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) { flags = RubyFixnum.fix2int((RubyFixnum) args[2]); } IRubyObject certificates = args[0]; IRubyObject store = args[1]; OCSPReq bcOCSPReq = getBCOCSPReq(); if (bcOCSPReq == null) { throw newOCSPError(runtime, new NullPointerException("Missing BC asn1bcReq. Missing certIDs or signature?")); } if (!bcOCSPReq.isSigned()) { return RubyBoolean.newBoolean(runtime, ret); } GeneralName genName = bcOCSPReq.getRequestorName(); if (genName.getTagNo() != 4) { return RubyBoolean.newBoolean(runtime, ret); } X500Name genX500Name = X500Name.getInstance(genName.getName()); X509StoreContext storeContext = null; JcaContentVerifierProviderBuilder jcacvpb = new JcaContentVerifierProviderBuilder(); jcacvpb.setProvider("BC"); try { java.security.cert.Certificate signer = findCertByName(genX500Name, certificates, flags); if (signer == null) return RubyBoolean.newBoolean(runtime, ret); if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOINTERN))) > 0 && ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) > 0)) flags |= RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY)); if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) { PublicKey signerPubKey = signer.getPublicKey(); ContentVerifierProvider cvp = jcacvpb.build(signerPubKey); ret = bcOCSPReq.isSignatureValid(cvp); if (!ret) { return RubyBoolean.newBoolean(runtime, ret); } } if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) { if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOCHAIN))) > 0) { storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), context.nil); } else { RubyArray certs = RubyArray.newEmptyArray(runtime); ASN1Sequence bcCerts = asn1bcReq.getOptionalSignature().getCerts(); if (bcCerts != null) { Iterator<ASN1Encodable> it = bcCerts.iterator(); while (it.hasNext()) { Certificate cert = Certificate.getInstance(it.next()); certs.add(X509Cert.wrap(runtime, new X509AuxCertificate(cert))); } } storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), certs); } storeContext.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER")); storeContext.set_trust(context, _X509(runtime).getConstant("TRUST_OCSP_REQUEST")); ret = storeContext.verify(context).isTrue(); if (!ret) return RubyBoolean.newBoolean(runtime, false); } } catch (Exception e) { debugStackTrace(e); throw newOCSPError(runtime, e); } return RubyBoolean.newBoolean(getRuntime(), ret); }
From source file:org.jruby.ext.openssl.X509Extension.java
License:LGPL
@SuppressWarnings("unchecked") private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) { final ASN1Encodable obj = name.getName(); String val; boolean tagged = false; switch (name.getTagNo()) { case GeneralName.rfc822Name: if (!tagged) out.append('e').append('m').append('a').append('i').append('l').append(':'); tagged = true;/*from w w w. j av a2s.co m*/ case GeneralName.dNSName: if (!tagged) out.append('D').append('N').append('S').append(':'); tagged = true; case GeneralName.uniformResourceIdentifier: if (!tagged) out.append('U').append('R').append('I').append(':'); val = DERIA5String.getInstance(obj).getString(); out.append(ByteList.plain(val)); break; case GeneralName.directoryName: out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':'); final X500Name dirName = X500Name.getInstance(obj); if (slashed) { final RDN[] rdns = dirName.getRDNs(); final Hashtable defaultSymbols = getDefaultSymbols(); for (int i = 0; i < rdns.length; i++) { appendRDN(out.append('/'), rdns[i], defaultSymbols); } } else { out.append(ByteList.plain(dirName.toString())); } break; case GeneralName.iPAddress: out.append('I').append('P').append(':'); final byte[] ip = ((ASN1OctetString) name.getName()).getOctets(); int len = ip.length; boolean ip4 = len == 4; for (int i = 0; i < ip.length; i++) { out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff)); if (i != len - 1) { if (ip4) out.append('.'); else out.append(':').append(':'); } } break; case GeneralName.otherName: out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m') .append('e').append(':'); out.append(ByteList.plain(obj.toString())); return true; //tagged = true; case GeneralName.registeredID: out.append('R').append('I').append('D').append(':'); //tagged = true; default: out.append(ByteList.plain(obj.toString())); } return false; }
From source file:org.keycloak.common.util.CRLUtils.java
License:Apache License
/** * Retrieves a list of CRL distribution points from CRLDP v3 certificate extension * See <a href="www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-cchain-and-verify-clr-with-bouncy-castle/">CRL validation</a> * @param cert//from w ww.j a v a2 s . c o m * @return * @throws IOException */ public static List<String> getCRLDistributionPoints(X509Certificate cert) throws IOException { byte[] data = cert.getExtensionValue(CRL_DISTRIBUTION_POINTS_OID); if (data == null) { return Collections.emptyList(); } List<String> distributionPointUrls = new LinkedList<>(); DEROctetString octetString; try (ASN1InputStream crldpExtensionInputStream = new ASN1InputStream(new ByteArrayInputStream(data))) { octetString = (DEROctetString) crldpExtensionInputStream.readObject(); } byte[] octets = octetString.getOctets(); CRLDistPoint crlDP; try (ASN1InputStream crldpInputStream = new ASN1InputStream(new ByteArrayInputStream(octets))) { crlDP = CRLDistPoint.getInstance(crldpInputStream.readObject()); } for (DistributionPoint dp : crlDP.getDistributionPoints()) { DistributionPointName dpn = dp.getDistributionPoint(); if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { GeneralName[] names = GeneralNames.getInstance(dpn.getName()).getNames(); for (GeneralName gn : names) { if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { String url = DERIA5String.getInstance(gn.getName()).getString(); distributionPointUrls.add(url); } } } } return distributionPointUrls; }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
@Override public String getCertificateEmail(X509Certificate certificate) throws CertException { String emailOID = "2.5.29.17"; byte[] emailBytes = certificate.getExtensionValue(emailOID); String certificateEmail = null; try {/*from w ww.j a v a 2s.com*/ byte[] octets = ((DEROctetString) org.bouncycastle.asn1.ASN1Object.fromByteArray(emailBytes)) .getOctets(); GeneralNames generalNameCont = GeneralNames .getInstance(org.bouncycastle.asn1.ASN1Object.fromByteArray(octets)); GeneralName[] generalNames = generalNameCont.getNames(); if (generalNames.length > 0) { GeneralName generalName = generalNames[0]; certificateEmail = generalName.getName().toString(); } } catch (IOException e) { throw new CertException("Email could not be extracted from certificate", e); } return certificateEmail; }
From source file:org.opensaml.security.x509.X509Support.java
License:Open Source License
/** * Gets the list of alternative names of a given name type. * //from w w w . j av a 2s . c o m * @param certificate the certificate to extract the alternative names from * @param nameTypes the name types * * @return the alt names, of the given type, within the cert */ @Nullable public static List getAltNames(@Nullable final X509Certificate certificate, @Nullable final Integer[] nameTypes) { if (certificate == null || nameTypes == null || nameTypes.length == 0) { return null; } final List<Object> altNames = new LinkedList<>(); final GeneralNameType[] types = new GeneralNameType[nameTypes.length]; for (int i = 0; i < nameTypes.length; i++) { types[i] = GeneralNameType.fromTagNumber(nameTypes[i]); } final GeneralNames names = CertUtil.subjectAltNames(certificate, types); if (names != null) { for (GeneralName name : names.getNames()) { altNames.add(convertAltNameType(name.getTagNo(), name.getName().toASN1Primitive())); } } return altNames; }
From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java
License:Open Source License
@Override public Map.Entry<X509GeneralName, String> asImmutableMapEntry(GeneralName generalName) { int nameType = generalName.getTagNo(); X509GeneralName x509GeneralName = null; String value = null;/* w w w.j a v a 2 s . c o m*/ switch (nameType) { case GeneralName.otherName: ASN1Sequence otherName = (ASN1Sequence) generalName.getName(); // String oid = ( ( DERObjectIdentifier ) otherName.getObjectAt( 0 ) ).getId(); x509GeneralName = X509GeneralName.otherName; value = cryptCodex.toString(otherName.getObjectAt(1)); break; case GeneralName.rfc822Name: x509GeneralName = X509GeneralName.rfc822Name; value = generalName.getName().toString(); break; case GeneralName.dNSName: x509GeneralName = X509GeneralName.dNSName; value = generalName.getName().toString(); break; case GeneralName.registeredID: x509GeneralName = X509GeneralName.registeredID; value = generalName.getName().toString(); break; case GeneralName.x400Address: x509GeneralName = X509GeneralName.x400Address; value = generalName.getName().toString(); break; case GeneralName.ediPartyName: x509GeneralName = X509GeneralName.ediPartyName; value = generalName.getName().toString(); break; case GeneralName.directoryName: x509GeneralName = X509GeneralName.directoryName; value = new X500Principal(((X509Name) generalName.getName()).toString()) .getName(X500Principal.CANONICAL); break; case GeneralName.uniformResourceIdentifier: x509GeneralName = X509GeneralName.uniformResourceIdentifier; value = generalName.getName().toString(); break; case GeneralName.iPAddress: // What about IPv6 addresses ? ASN1OctetString iPAddress = (ASN1OctetString) generalName.getName(); byte[] iPAddressBytes = iPAddress.getOctets(); StringBuilder sb = new StringBuilder(); for (int idx = 0; idx < iPAddressBytes.length; idx++) { sb.append(iPAddressBytes[idx] & 0xFF); if (idx + 1 < iPAddressBytes.length) { sb.append("."); } } x509GeneralName = X509GeneralName.iPAddress; value = sb.toString(); break; default: x509GeneralName = X509GeneralName.unknownGeneralName; value = generalName.getName().toString(); } return new ImmutableMapEntry(x509GeneralName, value); }
From source file:org.tdmx.client.crypto.certificate.PKIXCertificate.java
License:Open Source License
private X500Name getSubjectNameConstraint() { Extension e = holder.getExtension(Extension.nameConstraints); if (e != null && e.isCritical()) { NameConstraints nc = NameConstraints.getInstance(e.getParsedValue()); GeneralSubtree[] permitted = nc.getPermittedSubtrees(); if (permitted != null && permitted.length > 0) { GeneralName base = permitted[0].getBase(); if (base != null) { if (GeneralName.directoryName == base.getTagNo()) { X500Name baseName = X500Name.getInstance(base.getName()); return baseName; }//from w w w. ja va 2 s .c om } } } return null; }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.crl.CRLVerifier.java
License:Apache License
/** * Extracts all CRL distribution point URLs from the * "CRL Distribution Point"// ww w. j a va2s. c o m * extension in a X.509 certificate. If CRL distribution point extension is * unavailable, returns an empty list. */ private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException { // Gets the DER-encoded OCTET string for the extension value for // CRLDistributionPoints byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()); if (crlDPExtensionValue == null) throw new CertificateVerificationException("Certificate doesn't have CRL Distribution points"); // crlDPExtensionValue is encoded in ASN.1 format. ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue); // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules // defined in ITU-T X.690, 2002, specification. // ASN.1 encoding rules can be used to encode any data object into a // binary file. Read the object in octets. CRLDistPoint distPoint; try { DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject(); // Get Input stream in octets ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets()); DERObject crlDERObject = asn1InOctets.readObject(); distPoint = CRLDistPoint.getInstance(crlDERObject); } catch (IOException e) { throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e); } List<String> crlUrls = new ArrayList<String>(); // Loop through ASN1Encodable DistributionPoints for (DistributionPoint dp : distPoint.getDistributionPoints()) { // get ASN1Encodable DistributionPointName DistributionPointName dpn = dp.getDistributionPoint(); if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { // Create ASN1Encodable General Names GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for a URI // todo: May be able to check for OCSP url specifically. for (GeneralName genName : genNames) { if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { // DERIA5String contains an ascii string. // A IA5String is a restricted character string type in // the ASN.1 notation String url = DERIA5String.getInstance(genName.getName()).getString().trim(); crlUrls.add(url); } } } } if (crlUrls.isEmpty()) throw new CertificateVerificationException("Cant get CRL urls from certificate"); return crlUrls; }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java
License:Apache License
/** * Authority Information Access (AIA) is a non-critical extension in an X509 * Certificate. This contains the/* ww w .j ava 2 s. co m*/ * URL of the OCSP endpoint if one is available. * TODO: This might contain non OCSP urls as well. Handle this. * * @param cert * is the certificate * @return a lit of URLs in AIA extension of the certificate which will * hopefully contain an OCSP endpoint. * @throws CertificateVerificationException * */ private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException { // Gets the DER-encoded OCTET string for the extension value for // Authority information access Points byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId()); if (aiaExtensionValue == null) throw new CertificateVerificationException( "Certificate Doesnt have Authority Information Access points"); // might have to pass an ByteArrayInputStream(aiaExtensionValue) ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue); AuthorityInformationAccess authorityInformationAccess; try { DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject()); ASN1InputStream asn1Inoctets = new ASN1InputStream(aiaDEROctetString.getOctets()); ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1Inoctets.readObject(); authorityInformationAccess = new AuthorityInformationAccess(aiaASN1Sequence); } catch (IOException e) { throw new CertificateVerificationException("Cannot read certificate to get OSCP urls", e); } List<String> ocspUrlList = new ArrayList<String>(); AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions(); for (AccessDescription accessDescription : accessDescriptions) { GeneralName gn = accessDescription.getAccessLocation(); if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { DERIA5String str = DERIA5String.getInstance(gn.getName()); String accessLocation = str.getString(); ocspUrlList.add(accessLocation); } } if (ocspUrlList.isEmpty()) throw new CertificateVerificationException("Cant get OCSP urls from certificate"); return ocspUrlList; }