Example usage for org.bouncycastle.asn1.x509 GeneralName getName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName getName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName getName.

Prototype

public ASN1Encodable getName() 

Source Link

Usage

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress
                                .getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException e) {
                    }/* ww w. j ava  2  s .  co m*/
                }
            }
        }
    }
    return ipAddresses;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private void printCRLDistributionPoints(PrintStream outStream) throws Exception {

    outStream.format("X509v3 CRL Distribution Points: \n");

    String extOid = X509Extension.cRLDistributionPoints.getId(); // 2.5.29.31
    byte[] extVal = cert.getExtensionValue(extOid);
    if (extVal == null) {
        return;/*ww w .j  a  v  a 2s. co m*/
    }

    /* http://download.oracle.com/javase/6/docs/api/java/security/cert/X509Extension.html#getExtensionValue(java.lang.String)
     *
       The ASN.1 definition for this is:
            
     Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
            
     Extension  ::=  SEQUENCE  {
         extnId        OBJECT IDENTIFIER,
         critical      BOOLEAN DEFAULT FALSE,
         extnValue     OCTET STRING
                       -- contains a DER encoding of a value
                       -- of the type registered for use with
                       -- the extnId object identifier value
     }
     */

    byte[] extnValue = DEROctetString.getInstance(ASN1Object.fromByteArray(extVal)).getOctets();

    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(ASN1Object.fromByteArray(extnValue));
    DistributionPoint[] distPoints = crlDistPoint.getDistributionPoints();

    for (DistributionPoint distPoint : distPoints) {
        DistributionPointName distPointName = distPoint.getDistributionPoint();
        int type = distPointName.getType();

        if (DistributionPointName.FULL_NAME == type) {
            outStream.format("Full Name: \n");
            GeneralNames generalNames = GeneralNames.getInstance(distPointName.getName());
            GeneralName[] names = generalNames.getNames();
            for (GeneralName generalname : names) {
                int tag = generalname.getTagNo();
                if (GeneralName.uniformResourceIdentifier == tag) {
                    DEREncodable name = generalname.getName();
                    DERIA5String str = DERIA5String.getInstance(name);
                    String value = str.getString();
                    outStream.format("    %s\n", value);
                } else {
                    outStream.format("tag %d not yet implemented", tag);
                }
            }
        } else {
            outStream.format("type %d not yet implemented", type);
        }
    }
}

From source file:de.mendelson.util.security.cert.KeystoreCertificate.java

/**
 * Returns the subject alternative name of this cert, OID 2.5.29.17
 *//*  w  w  w.j a  v  a 2 s  .  co  m*/
public List<String> getSubjectAlternativeNames() {
    List<String> alternativeNames = new ArrayList<String>();
    byte[] extensionValue = this.certificate.getExtensionValue("2.5.29.17");
    if (extensionValue == null) {
        return (alternativeNames);
    }
    try {
        byte[] octedBytes = ((ASN1OctetString) ASN1Primitive.fromByteArray(extensionValue)).getOctets();
        GeneralName[] names = (GeneralNames.getInstance(ASN1Primitive.fromByteArray(octedBytes))).getNames();
        for (GeneralName name : names) {
            alternativeNames.add(((ASN1String) name.getName()).getString() + " ("
                    + this.generalNameTagNoToString(name) + ")");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (alternativeNames);
}

From source file:de.mendelson.util.security.cert.KeystoreCertificate.java

/**
 * Get extension values for CRL Distribution Points as a string list or an
 * empty list if an exception occured or the extension doesnt exist OID
 * 2.5.29.31//from   ww  w .java  2s  . com
 */
public List<String> getCrlDistributionURLs() {
    List<String> ulrList = new ArrayList<String>();
    //CRL destribution points has OID 2.5.29.31
    byte[] extensionValue = this.certificate.getExtensionValue("2.5.29.31");
    if (extensionValue == null) {
        return (ulrList);
    }
    try {
        byte[] octedBytes = ((ASN1OctetString) ASN1Primitive.fromByteArray(extensionValue)).getOctets();
        CRLDistPoint distPoint = CRLDistPoint.getInstance(ASN1Primitive.fromByteArray(octedBytes));
        DistributionPoint[] points = distPoint.getDistributionPoints();
        for (DistributionPoint point : points) {
            DistributionPointName distributionPointName = point.getDistributionPoint();
            if (distributionPointName != null) {
                if (distributionPointName.getType() == DistributionPointName.FULL_NAME) {
                    GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
                    for (GeneralName generalName : generalNames.getNames()) {
                        //generalName.getTagNo() is GeneralName.uniformResourceIdentifier in this case
                        ulrList.add(((ASN1String) generalName.getName()).getString());
                    }
                }
            }
        }
    } catch (Exception e) {
        //nop
    }
    return (ulrList);
}

From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java

License:Mozilla Public License

private List<String> getOCSPUrls(AuthorityInformationAccess authInfoAccess) {
    List<String> urls = new ArrayList<String>();

    if (authInfoAccess != null) {
        AccessDescription[] ads = authInfoAccess.getAccessDescriptions();
        for (int i = 0; i < ads.length; i++) {
            if (ads[i].getAccessMethod().equals(AccessDescription.id_ad_ocsp)) {
                GeneralName name = ads[i].getAccessLocation();
                if (name.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = ((DERIA5String) name.getName()).getString();
                    urls.add(url);/*from   w  ww  . jav a2  s.co  m*/
                }
            }
        }
    }

    return urls;
}

From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java

License:Mozilla Public License

/**
 * Get an URL to use when downloading CRL
 * /*from w  ww. j a va2  s . c o  m*/
 * @param conf
 * @param entityId
 * @param certificate
 * @return the URL to use
 */
private String getCRLUrl(Configuration conf, String entityId, X509Certificate certificate) {
    String url = conf.getString(Constants.PROP_CRL + entityId);

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

    log.debug("No CRL configured for " + entityId
            + " attempting to extract distribution point from certificate " + certificate.getSubjectDN());

    byte[] val = certificate.getExtensionValue("2.5.29.31");

    if (val != null) {
        try {
            CRLDistPoint point = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(val));
            for (DistributionPoint dp : point.getDistributionPoints()) {
                if (dp.getDistributionPoint() == null)
                    continue;

                if (dp.getDistributionPoint().getName() instanceof GeneralNames) {
                    GeneralNames gn = (GeneralNames) dp.getDistributionPoint().getName();
                    for (GeneralName g : gn.getNames()) {
                        if (g.getName() instanceof DERIA5String) {
                            url = ((DERIA5String) g.getName()).getString();
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.debug("Cannot extract distribution point for certificate.", e);
            throw new RuntimeException(e);
        }
    }

    return url;
}

From source file:edu.nps.moves.mmowgli.CACManager.java

License:Open Source License

private static void parseCert(String cert, CACData data) {
    cert = cert.replace(' ', '\r');
    cert = cert.replace("BEGIN\rCERTIFICATE", "BEGIN CERTIFICATE");
    cert = cert.replace("END\rCERTIFICATE", "END CERTIFICATE");
    PEMParser pr = new PEMParser(new StringReader(cert));
    try {//from w w w  .  jav a  2s .c  om
        Object o = pr.readObject();
        pr.close();
        if (o instanceof X509CertificateHolder) {
            X509CertificateHolder x509 = (X509CertificateHolder) o;
            X500Name x500name = x509.getSubject();
            RDN cnRdns[] = x500name.getRDNs(BCStyle.CN);

            String cn = IETFUtils.valueToString(cnRdns[0].getFirst().getValue());
            parseCN(cn, data);

            GeneralNames gns = GeneralNames.fromExtensions(x509.getExtensions(),
                    Extension.subjectAlternativeName);
            if (gns != null) {
                GeneralName[] subjectAltNames = gns.getNames();
                for (GeneralName gn : subjectAltNames) {
                    if (gn.getTagNo() == GeneralName.rfc822Name) { // check for email
                        String s = DERIA5String.getInstance(gn.getName()).getString();
                        if (s.contains("@")) {
                            data.userEmail = s;
                            break;
                        }
                    }
                }
            }

            // Create the unique card identifier (issuer+serial) which when hashed goes into the database for quick login
            String uniqueCertId = x509.getIssuer().toString() + " " + x509.getSerialNumber().toString();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(uniqueCertId.getBytes("UTF-8")); // or UTF-16
            byte[] digest = md.digest();
            data.cacId = Hex.encodeHexString(digest);

            /* Alternatively, this will do a salted hash, but the output is not the same for the same input; better security
             * but the login performance would be bad since the user list has to be polled instead of indexed
             try {
               data.cacId = PasswordHash.createHash(uniqueCertId);
             }
             catch(Exception ex) {
               MSysOut.println(MmowgliConstants.SYSTEM_LOGS,"Program error, could not create CAC hash; auto-login disabled");
               data.cacId = null;
             }
             System.out.println("data cacId: "+data.cacId); */

        }
    } catch (IOException | NoSuchAlgorithmException ex) {
        MSysOut.println(MmowgliConstants.SYSTEM_LOGS,
                ex.getClass().getSimpleName() + ": Program error, could not parse CAC");
        data.cacId = null;
        data.isCACPresent = false;
    }

    // Some informational stuff
    /* this gives same info as the x509 methods below  
         RDN rdns[] = x500name.getRDNs();
         for(RDN rdn : rdns) {
            AttributeTypeAndValue[] tandV = rdn.getTypesAndValues();
            for(AttributeTypeAndValue tv : tandV) {
     System.out.println(tv.getType());
     System.out.println(IETFUtils.valueToString(tv.getType()));
     System.out.println(tv.getValue());
     System.out.println(IETFUtils.valueToString(tv.getValue()));
            }
         }
         */
    /*
    System.out.println("X509 version: "+x509.getVersionNumber());
    System.out.println("X509 Serial num: "+x509.getSerialNumber());
    System.out.println("X509 Sig algo: "+x509.getSignatureAlgorithm().getAlgorithm().toASN1Primitive());
    System.out.println("X509 Issuer: "+x509.getIssuer());
    System.out.println("X509 Not before: "+x509.getNotBefore());
    System.out.println("X509 Not after: "+x509.getNotAfter());
    System.out.println("X509 Subject: "+x509.getSubject());
    System.out.println("X509 Subject Public Key Info: "+x509.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm());
    */
    /* 
     System.out.println("CriticalExtensionOIDs: ");
     Set<?> set = x509.getCriticalExtensionOIDs();
     Iterator<?> itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
               
     System.out.println("NonCriticalExtensionOIDs: ");
     set = x509.getNonCriticalExtensionOIDs();
     itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
             
     System.out.println("Other api: getExtensionOIDs");
     List<?> lis = x509.getExtensionOIDs();
     itr = lis.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
            
     System.out.println("From the extensions \"block\"");
     Extensions exts = x509.getExtensions();
     ASN1ObjectIdentifier[] ids = exts.getExtensionOIDs();
     for(ASN1ObjectIdentifier oid : ids) {
       org.bouncycastle.asn1.x509.Extension ext = exts.getExtension(oid);
       System.out.println(oid.toString()+": "+IETFUtils.valueToString(ext.getParsedValue()));
     }
    //     */
}

From source file:edu.washington.iam.tools.IamCertificateHelper.java

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {/*w w w. jav  a 2 s .co  m*/
        PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest));
        PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();
        if (request == null)
            throw new IamCertificateException("invalid CSR (request)");
        CertificationRequestInfo info = request.getCertificationRequestInfo();
        if (info == null)
            throw new IamCertificateException("invalid CSR (info)");

        X509Name dn = info.getSubject();
        if (dn == null)
            throw new IamCertificateException("invalid CSR (dn)");
        log.debug("dn=" + dn.toString());
        cert.dn = dn.toString();
        try {
            List cns = dn.getValues(X509Name.CN);
            cert.cn = (String) (cns.get(0));
            log.debug("cn=" + cert.cn);
            cert.names.add(cert.cn); // first entry for names is always cn
            cns = dn.getValues(X509Name.C);
            cert.dnC = (String) (cns.get(0));
            cns = dn.getValues(X509Name.ST);
            cert.dnST = (String) (cns.get(0));
        } catch (Exception e) {
            log.debug("get cn error: " + e);
            throw new IamCertificateException("invalid CSR");
        }

        // see if we've got alt names (in extensions)

        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            for (int a = 0; a < attrs.size(); a++) {
                Attribute attr = Attribute.getInstance(attrs.getObjectAt(a));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {

                    // is the extension
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

                    // get the subAltName extension
                    DERObjectIdentifier sanoid = new DERObjectIdentifier(
                            X509Extensions.SubjectAlternativeName.getId());
                    X509Extension xext = extensions.getExtension(sanoid);
                    if (xext != null) {
                        log.debug("processing altname extensions");
                        ASN1Object asn1 = X509Extension.convertValueToObject(xext);
                        Enumeration dit = DERSequence.getInstance(asn1).getObjects();
                        while (dit.hasMoreElements()) {
                            GeneralName gn = GeneralName.getInstance(dit.nextElement());
                            log.debug("altname tag=" + gn.getTagNo());
                            log.debug("altname name=" + gn.getName().toString());
                            if (gn.getTagNo() == GeneralName.dNSName)
                                cert.names.add(gn.getName().toString());
                        }
                    }

                }
            }
        }

        // check key size
        PublicKey pk = request.getPublicKey();
        log.debug("key alg = " + pk.getAlgorithm());
        log.debug("key fmt = " + pk.getFormat());
        if (pk.getAlgorithm().equals("RSA")) {
            RSAPublicKey rpk = (RSAPublicKey) pk;
            cert.keySize = rpk.getModulus().bitLength();
            log.debug("key size = " + cert.keySize);
        }

    } catch (IOException e) {
        log.debug("ioerror: " + e);
        throw new IamCertificateException("invalid CSR " + e.getMessage());
    } catch (Exception e) {
        log.debug("excp: " + e);
        throw new IamCertificateException("invalid CSR");
    }
    return 1;
}

From source file:ee.ria.xroad.common.util.CertUtils.java

License:Open Source License

/**
 * @param subject certificate from which to get the OCSP responder URI
 * @return OCSP responder URI from given certificate.
 * @throws IOException if an I/O error occurred
 *//*from  ww w. java 2s  . c o m*/
public static String getOcspResponderUriFromCert(X509Certificate subject) throws IOException {
    final byte[] extensionValue = subject.getExtensionValue(Extension.authorityInfoAccess.toString());

    if (extensionValue != null) {
        ASN1Primitive derObject = toDERObject(extensionValue);

        if (derObject instanceof DEROctetString) {
            DEROctetString derOctetString = (DEROctetString) derObject;
            derObject = toDERObject(derOctetString.getOctets());

            AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                    .getInstance(derObject);
            AccessDescription[] descriptions = authorityInformationAccess.getAccessDescriptions();

            for (AccessDescription desc : descriptions) {
                if (desc.getAccessMethod().equals(AccessDescription.id_ad_ocsp)) {
                    GeneralName generalName = desc.getAccessLocation();

                    return generalName.getName().toString();
                }
            }
        }
    }

    return null;
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Generates a string array of IP address spaces from a list of
 * GeneralSubtrees./* ww  w.j av  a 2 s  .  c  o m*/
 * 
 * @param subtrees The list of GeneralSubtrees to parse. Null as input
 *                will return null.
 * @return the array of IP address spaces.
 */
private static byte[][] subtreesIntoArray(List<GeneralSubtree> subtrees) {
    if (subtrees == null)
        return null;

    List<byte[]> ips = new ArrayList<byte[]>();
    Iterator<GeneralSubtree> enumGeneralNames = subtrees.iterator();
    while (enumGeneralNames.hasNext()) {
        GeneralName item = enumGeneralNames.next().getBase();
        if (item.getTagNo() == GeneralName.iPAddress) {
            ASN1OctetString octets = (ASN1OctetString) item.getName();
            byte[] bytes = octets.getOctets();
            ips.add(bytes);
        }
    }
    return ips.toArray(new byte[ips.size()][]);
}