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

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

Introduction

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

Prototype

ASN1ObjectIdentifier O

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

Click Source Link

Document

organization - StringType(SIZE(1..64))

Usage

From source file:ClientOCSPDriver.java

License:Open Source License

/**
     * Apply ASN1 coversion for the given value depending on the oid
     * and the character range of the value.
     */*  www. ja v a 2  s . c  om*/
     * This code was taken and modified from X509DefaultEntryConverter.java file 
     * of BouncyCastle. Modify this code to match the ASN1 type for your requestor subject DN
     * Refer Bouncycastle X509DefaultEntryConverter.java source for implementation of methods
     * such as convertHexEncoded, canBePrintable and canBeUTF8 
     * 
     * @param oid the object identifier for the DN entry
     * @param value the value associated with it
     * @return the ASN.1 equivalent for the string value.
     *      
     */
public DERObject getConvertedValue(DERObjectIdentifier oid, String value) {
    if (oid.equals(X509Name.O) || oid.equals(X509Name.OU)) {
        return new DERT61String(value);
    } else /*if (canBePrintable(value))  */
    {
        return new DERPrintableString(value);
    }
}

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);
    }/*  w  w  w.ja v a2 s.  co  m*/
    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  ww.  jav a 2s.c o  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
 *
 */// w w  w . j a  v  a2 s  .com
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:org.glite.security.delegation.GrDPX509Util.java

License:Apache License

/**
 * Create an X509 Certificate DN/*  www .java  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/*from www . java 2  s  .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);/* ww w . jav  a2  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.sufficientlysecure.keychain.pgp.PgpToX509.java

License:Open Source License

/**
 * Creates a self-signed certificate from a PGP Secret Key.
 *
 * @param pgpSecKey      PGP Secret Key (from which one can extract the public and private
 *                       keys and other attributes).
 * @param pgpPrivKey     PGP Private Key corresponding to the Secret Key (password callbacks
 *                       should be done before calling this method)
 * @param subjAltNameURI optional URI to embed in the subject alternative-name
 * @return self-signed certificate/*  ww  w.j  a va2 s.  c o m*/
 * @throws PGPException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 * @throws CertificateException
 * @author Bruno Harbulot
 */
public static X509Certificate createSelfSignedCert(PGPSecretKey pgpSecKey, PGPPrivateKey pgpPrivKey,
        String subjAltNameURI) throws PGPException, NoSuchProviderException, InvalidKeyException,
        NoSuchAlgorithmException, SignatureException, CertificateException {
    // get public key from secret key
    PGPPublicKey pgpPubKey = pgpSecKey.getPublicKey();

    // LOGGER.info("Key ID: " + Long.toHexString(pgpPubKey.getKeyID() & 0xffffffffL));

    /*
     * The X.509 Name to be the subject DN is prepared. The CN is extracted from the Secret Key
     * user ID.
     */
    Vector<DERObjectIdentifier> x509NameOids = new Vector<DERObjectIdentifier>();
    Vector<String> x509NameValues = new Vector<String>();

    x509NameOids.add(X509Name.O);
    x509NameValues.add(DN_COMMON_PART_O);

    x509NameOids.add(X509Name.OU);
    x509NameValues.add(DN_COMMON_PART_OU);

    for (@SuppressWarnings("unchecked")
    Iterator<Object> it = (Iterator<Object>) pgpSecKey.getUserIDs(); it.hasNext();) {
        Object attrib = it.next();
        x509NameOids.add(X509Name.CN);
        x509NameValues.add("CryptoCall");
        // x509NameValues.add(attrib.toString());
    }

    /*
     * Currently unused.
     */
    Log.d(Constants.TAG, "User attributes: ");
    for (@SuppressWarnings("unchecked")
    Iterator<Object> it = (Iterator<Object>) pgpSecKey.getUserAttributes(); it.hasNext();) {
        Object attrib = it.next();
        Log.d(Constants.TAG, " - " + attrib + " -- " + attrib.getClass());
    }

    X509Name x509name = new X509Name(x509NameOids, x509NameValues);

    Log.d(Constants.TAG, "Subject DN: " + x509name);

    /*
     * To check the signature from the certificate on the recipient side, the creation time
     * needs to be embedded in the certificate. It seems natural to make this creation time be
     * the "not-before" date of the X.509 certificate. Unlimited PGP keys have a validity of 0
     * second. In this case, the "not-after" date will be the same as the not-before date. This
     * is something that needs to be checked by the service receiving this certificate.
     */
    Date creationTime = pgpPubKey.getCreationTime();
    Log.d(Constants.TAG, "pgp pub key creation time=" + DateFormat.getDateInstance().format(creationTime));
    Log.d(Constants.TAG, "pgp valid seconds=" + pgpPubKey.getValidSeconds());
    Date validTo = null;
    if (pgpPubKey.getValidSeconds() > 0) {
        validTo = new Date(creationTime.getTime() + 1000L * pgpPubKey.getValidSeconds());
    }

    X509Certificate selfSignedCert = createSelfSignedCert(
            pgpPubKey.getKey(Constants.BOUNCY_CASTLE_PROVIDER_NAME), pgpPrivKey.getKey(), x509name,
            creationTime, validTo, subjAltNameURI);

    return selfSignedCert;
}

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 w w.  j a v  a 2 s . c o 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);
    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());
}