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

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

Introduction

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

Prototype

private GeneralNames(ASN1Sequence seq) 

Source Link

Usage

From source file:org.glite.security.util.proxy.ProxyTracingExtension.java

License:Apache License

/**
 * Parses the information in the byte array (GeneralNames ASN1 sequence of GeneralName) into a proxy tracing
 * extension object.//w  w w  .ja v a 2s . c  o  m
 * 
 * @param bytes The bytes of ASN1 encoded proxy tracing extension.
 * @throws IOException In case the byte array does not contain a valid ASN1 encoded proxy tracing extension.
 */
public ProxyTracingExtension(byte[] bytes) throws IOException {
    m_names = new GeneralNames((ASN1Sequence) ASN1Object.fromByteArray(bytes));
    m_name = m_names.getNames()[0];
}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a RFC882 Subject Alternative Name: email:johndoe@example.com
 * extension./*from w w  w  .  j a va 2 s  .  c o m*/
 * 
 * @param emailAddress
 *            The email address to be included as alternative name.
 * @return The subject alternative name CertificateExtension.
 */
static protected CertificateExtension createSubjectAltNameExtension(String emailAddress) {
    GeneralName subjectAltName = new GeneralName(GeneralName.rfc822Name, emailAddress);
    GeneralNames subjectAltNames = new GeneralNames(subjectAltName);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(subjectAltNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, emailAddress);

}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * //w  ww. j a v  a2s. c o m
 * @param prefixedAltNames
 * @param values
 * @return
 */
static protected CertificateExtension createSubjectAltNameExtension(Vector prefixedAltNames, String values) {
    ASN1EncodableVector altNames = new ASN1EncodableVector();
    Enumeration typeAndNames = prefixedAltNames.elements();
    while (typeAndNames.hasMoreElements()) {
        String typeAndName = (String) typeAndNames.nextElement();
        typeAndName = typeAndName.trim();
        if (typeAndName.startsWith("email:")) {
            String emailAddress = typeAndName.substring("email:".length());
            GeneralName altName = new GeneralName(GeneralName.rfc822Name, emailAddress);
            altNames.add(altName);

        } else if (typeAndName.startsWith("dns:")) {
            String hostname = typeAndName.substring("dns:".length());
            GeneralName altName = new GeneralName(GeneralName.dNSName, hostname);
            altNames.add(altName);
        } else {
            LOG.error("Unsupported subjectAltName: " + typeAndName);
        }
    }
    DERSequence subjectAltNames = new DERSequence(altNames);
    GeneralNames generalNames = new GeneralNames(subjectAltNames);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(generalNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, values);

}

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

License:Apache License

private ASN1Encodable buildGAExtensionContent(EnumSet<ACGenerationProperties> properties,
        List<VOMSGenericAttribute> gas, GeneralName policyAuthorityInfo) {

    ASN1EncodableVector tagContainer = new ASN1EncodableVector();
    ASN1EncodableVector tagSequences = new ASN1EncodableVector();

    for (VOMSGenericAttribute a : gas)
        tagSequences.add(buildTagSequence(a));

    tagContainer.add(new GeneralNames(policyAuthorityInfo));
    tagContainer.add(new DERSequence(tagSequences));

    DERSequence finalSequence;//from   w  ww . j a  v  a  2s  . co m

    // We wrap this three times as VOMS core does, even if I think this
    // is a bug
    finalSequence = new DERSequence(new DERSequence(new DERSequence(tagContainer)));

    return finalSequence;
}

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// ww  w.jav  a2s  .  c  o m
 * @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.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/* ww  w  . j  a 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.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns the <code>AuthorityKeyIdentifier</code> corresponding
 * to a given <code>PublicKey</code>
 * @param publicKey the given public key
 * @param issuer the certificate issuer//from   w  ww .  j  a  v a2  s . com
 * @param serial the certificate serial number
 * @return the authority key identifier of the public key
 * @throws IOException
 */
private AuthorityKeyIdentifier getAuthorityKeyIdentifier(PublicKey publicKey, String issuer, BigInteger serial)
        throws IOException {
    InputStream input;
    SubjectPublicKeyInfo keyInfo;
    ASN1EncodableVector vector;

    input = new ByteArrayInputStream(publicKey.getEncoded());
    keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(input).readObject());
    vector = new ASN1EncodableVector();
    vector.add(new GeneralName(new X509Name(issuer)));

    return new AuthorityKeyIdentifier(keyInfo, new GeneralNames(new DERSequence(vector)), serial);
}

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);// w w  w. j a  v a 2s.  co m
    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  w  w. j ava  2s. 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.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a CA Root certificate./*from  w  w w  .  j a va 2 s.c  o  m*/
 */
private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN));
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(
            new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation));
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning));

    return certGen.generate(pair.getPrivate(), "BC");
}