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

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

Introduction

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

Prototype

ASN1ObjectIdentifier ST

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

Click Source Link

Document

state, or province name - StringType(SIZE(1..64))

Usage

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

/**
 * Generates a self-signed X509 Version 3 certificate
 *
 *//*from   w  w  w.  ja  v  a2 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 {/*from w ww .  ja va2 s  .c o  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:org.glite.voms.PKIUtils.java

License:Open Source License

/**
 * Gets an OpenSSL-style representation of a principal.
 *
 * @param principal the principal/*from www  .j ava 2s .  c o  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);//w w w  .  j av  a  2 s  . c om
    }

    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.gatekeeper.CertificateHelper.java

License:Open Source License

public static X500Principal getX500Principal(String email, String commonName, String organizationUnitName,
        String organizationName, String stateOrProvince) {
    if (null == email || null == commonName || null == organizationUnitName || null == organizationName
            || null == stateOrProvince) {
        throw new RuntimeException(
                "Certificate requires EmailAddress, Common Name, organizationUnitName, organizationName, stateOrProvince");
    }/*from  w  ww  .j a v  a2s.  com*/
    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);
    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());
}

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");
    }/*from  w  w w .j a v a 2 s  . c  om*/
    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());
}