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

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

Introduction

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

Prototype

public GeneralName(int tag, String name) 

Source Link

Document

Create a GeneralName for the given tag from the passed in String.

Usage

From source file:org.italiangrid.voms.asn1.VOMSACGenerator.java

License:Apache License

private GeneralName buildPolicyAuthorityInfo(String voName, String host, int port) {

    return new GeneralName(GeneralName.uniformResourceIdentifier, buildVOURI(voName, host, port));
}

From source file:org.italiangrid.voms.asn1.VOMSACGenerator.java

License:Apache License

private ASN1Encodable buildTargetsExtensionContent(EnumSet<ACGenerationProperties> properties,
        List<String> targets) {

    ASN1EncodableVector targetSeq = new ASN1EncodableVector();

    for (String s : targets) {

        DERTaggedObject encodedTarget = new DERTaggedObject(0,
                new GeneralName(GeneralName.uniformResourceIdentifier, s));

        // We wrap the target in another sequence as the old VOMS does
        targetSeq.add(new DERSequence(encodedTarget));
    }//w w  w  .  j a v a 2s  .  c o m

    DERSequence targetExtensionContent = new DERSequence(new DERSequence(targetSeq));
    return targetExtensionContent;
}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Creates an X509 version3 certificate.
 *
 * @param kp           KeyPair that keeps the public and private keys for the new certificate.
 * @param months       time to live/*w  ww  .  j  a va 2s .  c om*/
 * @param issuerDN     Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
 * @param subjectDN    Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
 * @param domain       Domain of the server.
 * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
 * @return X509 V3 Certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN,
        String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(serial);
    certGenerator.setIssuerDN(new X509Name(issuerDN));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    // Generate the subject alternative name
    boolean critical = subjectDN == null || "".equals(subjectDN.trim());
    ASN1Sequence othernameSequence = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                    new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    // Add subject alternative name extension
    certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames);

    X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom());
    cert.checkValidity(new Date());
    cert.verify(pubKey);

    return cert;
}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException {
    if (valuex.startsWith(DNS_)) {
        final String dns = valuex.substring(DNS_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }//from   w  w w. jav a2 s. c  om
    if (valuex.startsWith(DNS_Name_)) {
        final String dns = valuex.substring(DNS_Name_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }
    if (valuex.startsWith(URI_)) {
        final String uri = valuex.substring(URI_.length());
        return new GeneralName(GeneralName.uniformResourceIdentifier, uri);
    }
    if (valuex.startsWith(RID_)) {
        final String rid = valuex.substring(RID_.length());
        return new GeneralName(GeneralName.registeredID, rid);
    }
    if (valuex.startsWith(email_)) {
        final String mail = valuex.substring(email_.length());
        return new GeneralName(GeneralName.rfc822Name, mail);
    }
    if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) {
        final int idx = valuex.charAt(2) == ':' ? 3 : 11;
        String[] vals = valuex.substring(idx).split("\\.|::");
        final byte[] ip = new byte[vals.length];
        for (int i = 0; i < vals.length; i++) {
            ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff);
        }
        return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip));
    }
    if (valuex.startsWith("other")) { // otherName || othername
        final String other = valuex.substring(otherName_.length());
        return new GeneralName(GeneralName.otherName, other);
    }
    if (valuex.startsWith("dir")) { // dirName || dirname
        final String dir = valuex.substring(dirName_.length());
        return new GeneralName(GeneralName.directoryName, dir);
    }

    throw new IOException("could not parse SubjectAltName: " + valuex);

}

From source file:org.kontalk.certgen.X509Bridge.java

License:Open Source License

/**
 * Creates a self-signed certificate from a public and private key. The
 * (critical) key-usage extension is set up with: digital signature,
 * non-repudiation, key-encipherment, key-agreement and certificate-signing.
 * The (non-critical) Netscape extension is set up with: SSL client and
 * S/MIME. A URI subjectAltName may also be set up.
 *
 * @param pubKey/*from  w w  w  . ja v  a2s  .c  o m*/
 *            public key
 * @param privKey
 *            private key
 * @param subject
 *            subject (and issuer) DN for this certificate, RFC 2253 format
 *            preferred.
 * @param startDate
 *            date from which the certificate will be valid
 *            (defaults to current date and time if null)
 * @param endDate
 *            date until which the certificate will be valid
 *            (defaults to start date and time if null)
 * @param subjectAltName
 *            URI to be placed in subjectAltName
 * @return self-signed certificate
 */
private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject,
        Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData)
        throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException,
        CertificateException, NoSuchProviderException, IOException, OperatorCreationException {

    /*
     * Sets the signature algorithm.
     */
    BcContentSignerBuilder signerBuilder;
    String pubKeyAlgorithm = pubKey.getAlgorithm();
    if (pubKeyAlgorithm.equals("DSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
    } else if (pubKeyAlgorithm.equals("RSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("SHA1WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    }
    /*
    else if (pubKeyAlgorithm.equals("ECDSA")) {
    // TODO is this even legal?
    certGenerator.setSignatureAlgorithm("SHA1WithECDSA");
    }
    */
    else {
        throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm);
    }

    AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer = signerBuilder.build(keyp);

    /*
     * Sets up the validity dates.
     */
    if (startDate == null) {
        startDate = new Date(System.currentTimeMillis());
    }
    if (endDate == null) {
        endDate = startDate;
    }

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            /*
             * Sets up the subject distinguished name.
             * Since it's a self-signed certificate, issuer and subject are the
             * same.
             */
            subject,
            /*
             * The serial-number of this certificate is 1. It makes sense
             * because it's self-signed.
             */
            BigInteger.ONE, startDate, endDate, subject,
            /*
             * Sets the public-key to embed in this certificate.
             */
            SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject()));

    /*
     * Adds the Basic Constraint (CA: true) extension.
     */
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    /*
     * Adds the Key Usage extension.
     */
    certBuilder.addExtension(Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
                    | KeyUsage.keyAgreement | KeyUsage.keyCertSign));

    /*
     * Adds the Netscape certificate type extension.
     */
    certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    /*
     * Adds the subject key identifier extension.
     */
    SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);

    /*
     * Adds the authority key identifier extension.
     */
    AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

    /*
     * Adds the subject alternative-name extension.
     */
    if (subjectAltName != null) {
        GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }

    /*
     * Adds the PGP public key block extension.
     */
    SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData);
    certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension);

    /*
     * Creates and sign this certificate with the private key
     * corresponding to the public key of the certificate
     * (hence the name "self-signed certificate").
     */
    X509CertificateHolder holder = certBuilder.build(signer);

    /*
     * Checks that this certificate has indeed been correctly signed.
     */
    X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder);
    cert.verify(pubKey);

    return cert;
}

From source file:org.krakenapps.ca.util.CertificateBuilder.java

License:Apache License

public static X509Certificate createCertificate(CertificateRequest req) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    X509Principal subject = parseDn(req.getSubjectDn());
    X509Principal issuer = parseDn(req.getIssuerDn());

    certGen.setSerialNumber(req.getSerial());
    certGen.setIssuerDN(issuer);//from  w  ww  .  jav a 2s  .c  om
    certGen.setSubjectDN(subject);
    certGen.setNotBefore(req.getNotBefore());
    certGen.setNotAfter(req.getNotAfter());
    certGen.setPublicKey(req.getKeyPair().getPublic());
    certGen.setSignatureAlgorithm(req.getSignatureAlgorithm());

    if (req.getCrlUrl() != null) {
        GeneralName gn = new GeneralName(6, new DERIA5String(req.getCrlUrl().toString()));

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);

        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);

        List<DistributionPoint> l = new ArrayList<DistributionPoint>();
        l.add(new DistributionPoint(dpn, null, null));

        CRLDistPoint crlDp = new CRLDistPoint(l.toArray(new DistributionPoint[0]));

        certGen.addExtension(new DERObjectIdentifier("2.5.29.31"), false, crlDp);
    }

    return certGen.generate(req.getIssuerKey(), "BC");
}

From source file:org.kse.gui.dialogs.extensions.DAuthorityKeyIdentifier.java

License:Open Source License

private void prepopulateWithAuthorityCertDetails(X500Name authorityCertName,
        BigInteger authorityCertSerialNumber) {
    if (authorityCertName != null) {
        try {//from w ww  .  j  a va2  s . c  o m
            GeneralName generalName = new GeneralName(GeneralName.directoryName, authorityCertName);
            GeneralNames generalNames = new GeneralNames(generalName);

            jgnAuthorityCertIssuer.setGeneralNames(generalNames);
        } catch (Exception ex) {
            DError dError = new DError(this, ex);
            dError.setLocationRelativeTo(this);
            dError.setVisible(true);
            return;
        }
    }

    if (authorityCertSerialNumber != null) {
        jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.toString());
        jtfAuthorityCertSerialNumber.setCaretPosition(0);
    }
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

private DistributionPoint[] createCrlDistributionPoints() {
    List<DistributionPoint> list = new ArrayList<>();
    Set<String> keys = getArrayKeys(PROPERTY_PREFIX_CRL_DISTRIBUTION_POINT);
    for (String dpPrefix : keys) {
        final String uriKey = dpPrefix + ".uri";
        String uri = getMandatoryProperty(uriKey);

        DistributionPointName dpName = new DistributionPointName(
                new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, uri)));
        list.add(new DistributionPoint(dpName, null, null));
    }/* w ww.j  a  v a  2s . co m*/
    if (list.isEmpty())
        return null;
    return list.toArray(new DistributionPoint[list.size()]);
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

private AccessDescription[] createAccessDescriptions() {
    List<AccessDescription> list = new ArrayList<>();
    Set<String> keys = getArrayKeys(PROPERTY_PREFIX_AUTHORITY_INFORMATION_ACCESS);
    for (String dpPrefix : keys) {
        final String typeKey = dpPrefix + ".type";
        final String type = getMandatoryProperty(typeKey);

        final String uriKey = dpPrefix + ".uri";
        final String uri = getMandatoryProperty(uriKey);

        ASN1ObjectIdentifier aiaId = null;
        switch (type) {
        case "ocsp":
            aiaId = AccessDescription.id_ad_ocsp;
            break;
        case "issuer":
            aiaId = AccessDescription.id_ad_caIssuers;
            break;
        default:/*from  w  w w. j  a  v  a  2s .c  o  m*/
            throw new IllegalArgumentException(
                    String.format("Value '%s' not supported for '%s'. Supported values are 'ocsp' or 'issuer'.",
                            type, typeKey));
        }

        AccessDescription accessDescription = new AccessDescription(aiaId,
                new GeneralName(GeneralName.uniformResourceIdentifier, uri));

        list.add(accessDescription);
    }

    if (list.isEmpty())
        return null;
    return list.toArray(new AccessDescription[list.size()]);
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

protected List<ASN1Encodable> extractAlternativeNames(String prefix) {
    List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    for (Object key : componentProperties.keySet()) {
        final String attributeKey = String.valueOf(key);
        if (attributeKey.startsWith(prefix)) {
            String nameTypeString = attributeKey.substring(attributeKey.lastIndexOf(".") + 1);
            String nameValue = getProperty(attributeKey);
            int nameType = 0;
            switch (nameTypeString) {
            case NAME_DNS:
                nameType = GeneralName.dNSName;
                break;
            case NAME_DIRECTORY:
                nameType = GeneralName.directoryName;
                break;
            case NAME_IP:
                nameType = GeneralName.iPAddress;
                break;
            case NAME_OTHER:
                nameType = GeneralName.otherName;
                break;
            default:
                throw new IllegalArgumentException(
                        String.format("Alternative name '%s' not supported.", nameTypeString));
            }/*  w  ww .j a v  a  2  s .co m*/

            if (StringUtils.isNotBlank(nameValue)) {
                subjectAlternativeNames.add(new GeneralName(nameType, nameValue));
            }
        }
    }

    return subjectAlternativeNames;
}