Example usage for org.bouncycastle.asn1.x509 X509Name C

List of usage examples for org.bouncycastle.asn1.x509 X509Name C

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Name C.

Prototype

ASN1ObjectIdentifier C

To view the source code for org.bouncycastle.asn1.x509 X509Name C.

Click Source Link

Document

country code - StringType(SIZE(2))

Usage

From source file:com.ah.be.cloudauth.HmCloudAuthCertMgmtImpl.java

@SuppressWarnings("rawtypes")
private void verifyCSRContent(BeRadSecCertCreationResultEvent result, String commonName)
        throws HmCloudAuthException {
    String methodName = "verifyCSRContent";
    if (result.isCreateError()) {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_CREATE_ERR);
    }/*  ww w  .  j  a v a  2s.c  om*/
    if (result.isNeedCreate()) {
        byte[] csrContent = result.getCsrContent();
        final List pemItems = org.apache.commons.ssl.PEMUtil.decode(csrContent);
        if (pemItems.isEmpty()) {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }

        final PEMItem csrPemItem = (PEMItem) pemItems.get(0);
        if (csrPemItem.pemType.startsWith(CERTIFICATE_REQUEST)) {
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrPemItem.getDerBytes());
            CertificationRequestInfo requestInfo = csr.getCertificationRequestInfo();
            X509Name subject = requestInfo.getSubject();

            Vector commondNameVector = subject.getValues(X509Name.CN);
            Vector countryVector = subject.getValues(X509Name.C);
            Vector organizationVector = subject.getValues(X509Name.O);
            if (commondNameVector.isEmpty() || countryVector.isEmpty() || organizationVector.isEmpty()) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_FORMAT_ERR);
            }
            if (!commonName.equalsIgnoreCase(commondNameVector.get(0).toString())
                    || !ORGANIZATION.equals(organizationVector.get(0).toString())
                    || !COUNTRY.equals(countryVector.get(0).toString())) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_VERIFY_ERR);
            }
        } else {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }
    } else {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_STATUS_ERR);
    }
    return;
}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java

License:Open Source License

/**
* @param _TbsC //w w  w .  ja va2 s. co m
 * @return
*/
private boolean isIssuerIdOk(TBSCertificateStructure _TbsC) {
    //check if issuer element has both organizationName and countryName
    boolean isOk = false;
    //the CNIPA requirement are identical to
    //ETSI 102 280 and ETSI 101 862 requirements
    Vector<DERObjectIdentifier> oidv = _TbsC.getIssuer().getOIDs();
    if (oidv.contains(X509Name.O) && //organizationName
            oidv.contains(X509Name.C)) //countryName
        isOk = true;
    return isOk;
}

From source file:de.mendelson.util.security.keygeneration.KeyGenerator.java

/**
 * Generates a self-signed X509 Version 3 certificate
 *
 *//* ww  w  . ja v a  2 s . c o  m*/
private X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey,
        KeyGenerationValues generationValues) throws Exception {
    //Stores certificate attributes
    Hashtable<ASN1ObjectIdentifier, String> attributes = new Hashtable<ASN1ObjectIdentifier, String>();
    Vector<ASN1ObjectIdentifier> order = new Vector<ASN1ObjectIdentifier>();
    attributes.put(X509Name.CN, generationValues.getCommonName());
    order.add(0, X509Name.CN);
    attributes.put(X509Name.OU, generationValues.getOrganisationUnit());
    order.add(0, X509Name.OU);
    attributes.put(X509Name.O, generationValues.getOrganisationName());
    order.add(0, X509Name.O);
    attributes.put(X509Name.L, generationValues.getLocalityName());
    order.add(0, X509Name.L);
    attributes.put(X509Name.ST, generationValues.getStateName());
    order.add(0, X509Name.ST);
    attributes.put(X509Name.C, generationValues.getCountryCode());
    order.add(0, X509Name.C);
    attributes.put(X509Name.E, generationValues.getEmailAddress());
    order.add(0, X509Name.E);
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    // Set the issuer distinguished name
    certificateGenerator.setIssuerDN(new X509Principal(order, attributes));
    //add a key extension if this is requested
    if (generationValues.getKeyExtension() != null) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, generationValues.getKeyExtension());
    }
    //add a extended key extension if this is requested
    if (generationValues.getExtendedKeyExtension() != null) {
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false,
                generationValues.getExtendedKeyExtension());
    }
    // Valid before and after dates now to iValidity days in the future
    Date startDate = new Date(System.currentTimeMillis());
    long duration = TimeUnit.DAYS.toMillis(generationValues.getKeyValidInDays());
    Date endDate = new Date(startDate.getTime() + duration);
    certificateGenerator.setNotBefore(startDate);
    certificateGenerator.setNotAfter(endDate);
    certificateGenerator.setSubjectDN(new X509Principal(order, attributes));
    certificateGenerator.setPublicKey(publicKey);
    certificateGenerator.setSignatureAlgorithm(generationValues.getSignatureAlgorithm());
    BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis() / 1000));
    certificateGenerator.setSerialNumber(serialNumber);
    // Generate an X.509 certificate, based on the current issuer and subject
    X509Certificate cert = certificateGenerator.generate(privateKey, "BC");
    // Return the certificate
    return cert;
}

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

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {//w  ww  .  ja va 2s  .c  om
        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:org.glite.security.delegation.GrDPX509Util.java

License:Apache License

/**
 * Create an X509 Certificate DN//w  w  w.j  a v a  2 s  .c o  m
 * @param organization Organization
 * @param orgUnit Organization Unit
 * @param commonName X509 Common Name
 * @param country Country
 * @param email Email address
 * @return X509Name of generated DN
 * @deprecated Use org.glite.security.util.proxy.ProxyCertificateGenerator
 */
public static X509Name makeGridCertDN(String organization, String orgUnit, String commonName, String country,
        String email) {
    Hashtable attrs = new Hashtable();
    attrs.put(X509Name.O, organization);
    attrs.put(X509Name.OU, orgUnit);
    attrs.put(X509Name.C, country);
    attrs.put(X509Name.EmailAddress, email);
    attrs.put(X509Name.CN, commonName);

    X509Name x509Name = new X509Name(attrs);

    LOGGER.debug("GrDPX509Util : " + x509Name.toString());

    return x509Name;
}

From source file:org.glite.voms.PKIUtils.java

License:Open Source License

/**
 * Gets an OpenSSL-style representation of a principal.
 *
 * @param principal the principal//  w  ww . j  a v a2  s.  co  m
 *
 * @return a String representing the principal.
 */
public static String getOpenSSLFormatPrincipal(Principal principal) {
    X509Name name = new X509Name(principal.getName());

    Vector oids = name.getOIDs();
    Vector values = name.getValues();

    ListIterator oids_iter = oids.listIterator();
    ListIterator values_iter = values.listIterator();
    String result = new String();

    while (oids_iter.hasNext()) {
        DERObjectIdentifier oid = (DERObjectIdentifier) oids_iter.next();
        String value = (String) values_iter.next();
        if (oid.equals(X509Name.C))
            result += "/C=" + value;
        else if (oid.equals(X509Name.CN))
            result += "/CN=" + value;
        else if (oid.equals(X509Name.DC))
            result += "/DC=" + value;
        else if (oid.equals(X509Name.E))
            result += "/E=" + value;
        else if (oid.equals(X509Name.EmailAddress))
            result += "/Email=" + value;
        else if (oid.equals(X509Name.L))
            result += "/L=" + value;
        else if (oid.equals(X509Name.O))
            result += "/O=" + value;
        else if (oid.equals(X509Name.OU))
            result += "/OU=" + value;
        else if (oid.equals(X509Name.ST))
            result += "/ST=" + value;
        else if (oid.equals(X509Name.UID))
            result += "/UID=" + value;
        else
            result += "/" + oid.toString() + "=" + value;
    }

    logger.debug("SSLFormat: " + result);
    return result;
}

From source file:org.sonatype.nexus.ssl.CertificateUtil.java

License:Open Source License

public static X509Certificate generateCertificate(final PublicKey publicKey, final PrivateKey privateKey,
        final String algorithm, final int validDays, final String commonName, final String orgUnit,
        final String organization, final String locality, final String state, final String country)
        throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, CertificateEncodingException {
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    Vector<ASN1ObjectIdentifier> order = new Vector<>();
    Hashtable<ASN1ObjectIdentifier, String> attributeMap = new Hashtable<>();

    if (commonName != null) {
        attributeMap.put(X509Name.CN, commonName);
        order.add(X509Name.CN);/*from w w w . j a  va  2 s .c o m*/
    }

    if (orgUnit != null) {
        attributeMap.put(X509Name.OU, orgUnit);
        order.add(X509Name.OU);
    }

    if (organization != null) {
        attributeMap.put(X509Name.O, organization);
        order.add(X509Name.O);
    }

    if (locality != null) {
        attributeMap.put(X509Name.L, locality);
        order.add(X509Name.L);
    }

    if (state != null) {
        attributeMap.put(X509Name.ST, state);
        order.add(X509Name.ST);
    }

    if (country != null) {
        attributeMap.put(X509Name.C, country);
        order.add(X509Name.C);
    }

    X509Name issuerDN = new X509Name(order, attributeMap);

    // validity
    long now = System.currentTimeMillis();
    long expire = now + (long) validDays * 24 * 60 * 60 * 1000;

    certificateGenerator.setNotBefore(new Date(now));
    certificateGenerator.setNotAfter(new Date(expire));
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(issuerDN);
    certificateGenerator.setPublicKey(publicKey);
    certificateGenerator.setSignatureAlgorithm(algorithm);
    certificateGenerator.setSerialNumber(BigInteger.valueOf(now));

    // make certificate
    return certificateGenerator.generate(privateKey);
}

From source file:org.tolven.config.model.CredentialManager.java

License:Open Source License

private X500Principal getX500Principal(CertificateGroupDetail certGroupDetail) {
    return new X500Principal(X509Name.EmailAddress + "=" + certGroupDetail.getEmail() + "," + X509Name.CN + "="
            + certGroupDetail.getCommonName() + "," + X509Name.OU + "="
            + certGroupDetail.getOrganizationUnitName() + "," + X509Name.O + "="
            + certGroupDetail.getOrganizationName() + "," + X509Name.ST + "="
            + certGroupDetail.getStateOrProvince() + "," + X509Name.C + "=" + certGroupDetail.getCountryName());
}

From source file:org.tolven.security.CertificateHelper.java

License:Open Source License

public static X500Principal getX500Principal(String email, String commonName, String organizationUnitName,
        String organizationName, String stateOrProvince, String countryName) {
    if (null == email || null == commonName || null == organizationUnitName || null == organizationName
            || null == stateOrProvince || null == countryName) {
        throw new RuntimeException(
                "Certificate requires EmailAddress, Common Name, organizationUnitName, organizationName, stateOrProvince, and countryName");
    }//  ww  w .j a v a  2  s  .co  m
    Attributes attributes = new BasicAttributes();
    attributes.put(X509Name.EmailAddress.toString(), email);
    attributes.put(X509Name.CN.toString(), commonName);
    attributes.put(X509Name.OU.toString(), organizationUnitName);
    attributes.put(X509Name.O.toString(), organizationName);
    attributes.put(X509Name.ST.toString(), stateOrProvince);
    attributes.put(X509Name.C.toString(), countryName);
    Rdn rdn;
    try {
        rdn = new Rdn(attributes);
    } catch (InvalidNameException ex) {
        throw new RuntimeException("Failed to obtain a Relative Distinguised Name", ex);
    }
    return new X500Principal(rdn.toString());
}