Example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName

Introduction

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

Prototype

ASN1ObjectIdentifier SubjectAlternativeName

To view the source code for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName.

Click Source Link

Document

Subject Alternative Name

Usage

From source file:g4mfs.impl.org.peertrust.security.credentials.CryptTools.java

License:Open Source License

/**
 * Generate a Certificate that holds a Credential as a critical Extension in it.
 * @param pubKey the public key of the subject of the credential. This
 * is needed to create a valid X509Certificate and might be usefull to
 * improve security, when a public key infrastructure is used in this
 * prototype environment./*from  w w  w  .  j  av a 2  s  .  c  o m*/
 * @param subject the distinguished name of the subject of this 
 * credential. Important: There exists a certain format for distinguished 
 * names. For example "CN=alice" is a valid DN.
 * @param credential the String Representation of the credential
 * @param issuer the name of the signer of the credential. This should
 * be the person the caPrivKey belongs to.
 * @param caPrivKey the key that is used to sign the credential
 * @return A X.509Certificate 
 */
public static X509Certificate createCert(String subject, String credential, PublicKey pubKey, String issuer,
        PrivateKey caPrivKey) throws Exception {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // create the certificate - version 3 (only v3 allows usage of extensions)
    v3CertGen.reset();
    // TODO: Eindeutige Serialno
    v3CertGen.setSerialNumber(java.math.BigInteger.valueOf(3));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setSubjectDN(new X509Principal(subject));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    // add the extensions
    // - the credential as an extension
    //   - try to create a "SubjectAlternativeName" Extension in the othername field
    //     - create an OtherName (there is no OtherName class, so I have to improvise)
    int tag = 2; // Tag-Class 'Universal', BIT STRING: 2(works fine), OCTET STRING: 3
    DERObject derO = new DERPrintableString(credential);

    //     - create a GeneralName
    GeneralName gn = new GeneralName(derO, tag);

    //     - create a GeneralNames set of it:
    DERSequence ders = new DERSequence(gn);
    GeneralNames gns = new GeneralNames(ders);

    v3CertGen.addExtension(X509Extensions.SubjectAlternativeName, true, gns);

    // generate the cert
    X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey);

    // Testing:
    cert.checkValidity(new Date());

    return cert;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws ProxyPathValidatorException, IOException {

    logger.debug("enter: checkProxyConstraints");

    X509Extensions extensions;//from   w  w w  . j ava  2s  . c o m
    DERObjectIdentifier oid;
    X509Extension ext;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.SubjectAlternativeName)
                    || oid.equals(X509Extensions.IssuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy,
                        "Proxy certificate cannot contain subject or issuer alternative name extension");
            } else if (oid.equals(X509Extensions.BasicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext);
                if (basicExt.isCA()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "Proxy certificate cannot have BasicConstraint CA=true");
                }
            } else if (oid.equals(X509Extensions.KeyUsage)) {
                proxyKeyUsage = ext;

                boolean[] keyUsage = BouncyCastleUtil.getKeyUsage(ext);
                // these must not be asserted
                if (keyUsage[1] || keyUsage[5]) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy,
                            "The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate");
                }
                boolean[] issuerKeyUsage = getKeyUsage(issuer);
                if (issuerKeyUsage != null) {
                    for (int i = 0; i < 9; i++) {
                        if (i == 1 || i == 5) {
                            continue;
                        }
                        if (!issuerKeyUsage[i] && keyUsage[i]) {
                            throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                                    checkedProxy, "Bad KeyUsage in Proxy Certificate");
                        }
                    }
                }
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.KeyUsage)) {
                // If issuer has it then proxy must have it also
                if (proxyKeyUsage == null) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension missing in Proxy Certificate");
                }
                // If issuer has it as critical so does the proxy
                if (ext.isCritical() && !proxyKeyUsage.isCritical()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension in Proxy Certificate is not critical");
                }
            }
        }
    }

    logger.debug("exit: checkProxyConstraints");
}

From source file:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Generate a X509 certificate for the given keypair.
 * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode
 * use backslash to escape a comma//from  w  ww .ja v a2 s  . co  m
 * @param keypair the keypair
 * @param months the validity length in months
 * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param domain domain of the server to store in the subject alternative name extension
 * @param signAlgorithm the signing algorithm to use
 * @return the generated X509 certificate
 */
public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN,
        String domain, String signAlgorithm) {
    try {
        // calendar for date calculations
        GregorianCalendar cal = new GregorianCalendar();

        // extract keypair components
        PublicKey pubKey = keypair.getPublic();
        PrivateKey privKey = keypair.getPrivate();

        // generate a random serial number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte[] serialNo = new byte[8];
        random.nextBytes(serialNo);
        BigInteger serial = new BigInteger(serialNo).abs();

        // create the certificate generator
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.reset();

        // set certificate attributes
        certGen.setSerialNumber(serial);
        cal.setTimeInMillis(System.currentTimeMillis());
        certGen.setNotBefore(cal.getTime());
        cal.add(GregorianCalendar.MONTH, months);
        certGen.setNotAfter(cal.getTime());
        certGen.setPublicKey(pubKey);
        certGen.setSignatureAlgorithm(signAlgorithm);
        certGen.setIssuerDN(new X509Name(issuerDN));
        certGen.setSubjectDN(new X509Name(subjectDN));

        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));

        // create subject alternative name
        boolean isCritical = subjectDN == null || "".equals(subjectDN.trim());
        DERSequence othernameSeq = new DERSequence(
                new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                        new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
        GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq);
        GeneralNames subjectAlternatives = new GeneralNames(othernameGen);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives);

        // finally generate the certificate
        X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(),
                new SecureRandom());
        cert.checkValidity(new Date());
        cert.verify(pubKey);

        return cert;
    } catch (NoSuchAlgorithmException ex) {
        throw new KeystoreFault(ex);
    } catch (CertificateException ex) {
        throw new KeystoreFault(ex);
    } catch (SignatureException ex) {
        throw new KeystoreFault(ex);
    } catch (NoSuchProviderException ex) {
        throw new KeystoreFault(ex);
    } catch (InvalidKeyException ex) {
        throw new KeystoreFault(ex);
    }
}

From source file:io.aos.crypto.spl06.PKCS10ExtensionExample.java

License:Apache License

public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception {
    // create a SubjectAlternativeName extension value
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"));

    // create the extensions object and add it as an attribute
    Vector oids = new Vector();
    Vector values = new Vector();

    oids.add(X509Extensions.SubjectAlternativeName);
    values.add(new X509Extension(false, new DEROctetString(subjectAltNames)));

    X509Extensions extensions = new X509Extensions(oids, values);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));

    return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"),
            pair.getPublic(), new DERSet(attribute), pair.getPrivate());
}

From source file:io.aos.crypto.spl06.X509V3CreateExample.java

License:Apache License

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    // generate the certificate
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

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

From source file:io.spikex.core.Main.java

License:Apache License

private void createKeyStore(final YamlDocument conf) {

    YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE);
    boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE);

    if (generate) {

        Path keyStorePath = Paths
                .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString()))
                .toAbsolutePath().normalize();

        if (!Files.exists(keyStorePath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }/*from   w  w w. j  av a 2 s. c  o m*/

            String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD);
            String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName());
            List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList());

            try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) {

                m_logger.info("Generating keystore: {}", keyStorePath);

                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                        BouncyCastleProvider.PROVIDER_NAME);

                SecureRandom rnd = new SecureRandom();
                generator.initialize(2048, rnd);
                KeyPair pair = generator.generateKeyPair();

                // DN
                X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
                nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU"));
                nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate");
                nameBuilder.addRDN(BCStyle.OU, "For testing purposes only");
                nameBuilder.addRDN(BCStyle.O, "Spike.x");
                nameBuilder.addRDN(BCStyle.CN, hostFqdn);

                long oneDay = 24 * 60 * 60 * 1000;
                Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday
                Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years

                BigInteger serialNum = BigInteger.valueOf(rnd.nextLong());
                X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
                        serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic());

                //
                // Extensions
                //
                x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                x509v3Builder.addExtension(X509Extensions.KeyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

                GeneralName[] dnsNames = new GeneralName[subjAltNames.size()];
                for (int i = 0; i < subjAltNames.size(); i++) {
                    String name = subjAltNames.get(i);
                    m_logger.info("Adding subject alt name: {}", name);
                    dnsNames[i] = new GeneralName(GeneralName.dNSName, name);
                }
                x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new GeneralNames(dnsNames));

                ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate());

                X509Certificate cert = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate(x509v3Builder.build(signer));

                // Validate
                cert.checkValidity(new Date());
                cert.verify(cert.getPublicKey());

                // Save in keystore
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert });

                m_logger.info("Created self-signed certificate: {}", hostFqdn);
                ks.store(out, password.toCharArray());

            } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
                    | NoSuchProviderException | OperatorCreationException | InvalidKeyException
                    | SignatureException e) {
                throw new RuntimeException("Failed to create keystore: " + keyStorePath, e);
            }
        }
    }
}

From source file:krypto.KryptoService.java

License:Apache License

/**
 * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist.
 * @return/*  w  w  w .  j  ava 2  s .c  o m*/
 * @throws Exception
 */
public static X509Certificate generateCertificate(String algorithm) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    KeyPair pair = null;

    try {
        pair = generateKeyPair(algorithm, 1024);
    } catch (Exception e) {
        try {
            pair = generateKeyPair(algorithm, 512);
        } catch (Exception e2) {
            System.out.println(e2.getMessage());
        }
    }

    long day = 24 * 60 * 60 * 1000; // 1 Tag gltig

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + day));
    certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    X509Certificate cert = null;
    try {
        cert = certGen.generate(pair.getPrivate(), "BC");
    } catch (CertificateEncodingException e) {
        System.out.println("CertificateEncodingException");
    } catch (InvalidKeyException e2) {
        System.out.println("InvalidKeyException: " + e2.getMessage());
    } catch (Exception e3) {
        // do nothing
    }

    return cert;

}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert)
        throws Exception {
    Date validFrom, validTo;//from w  w w.  jav a  2s.c  o m

    // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider 
    // make the range before 1950 and after 2050. The BD-J spec recommends
    // using the default validity period used below
    Calendar calendar = Calendar.getInstance();
    calendar.set(0000, 1, 1);
    validFrom = calendar.getTime();
    calendar.clear();
    calendar.set(9999, 1, 1);
    validTo = calendar.getTime();

    // Generate a new keypair for this certificate
    KeyPair keyPair = generateKeyPair();

    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();
    X509Name name = new X509Name(issuer, new X509BDJEntryConverter());

    // Generate Serial Number
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    BigInteger serNo = new BigInteger(32, prng);
    cg.setSerialNumber(serNo);
    if (!isRootCert) {
        appCertSerNo = serNo;
    }
    cg.setIssuerDN(name);
    cg.setNotBefore(validFrom);
    cg.setNotAfter(validTo);
    cg.setSubjectDN(name);
    cg.setPublicKey(keyPair.getPublic());
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    if (isRootCert) {
        // Need to add root cert extensions.
        if (isBindingUnitCert) {
            // This certificate is used only for signing
            cg.addExtension(X509Extensions.KeyUsage.getId(), true,
                    new X509KeyUsage(X509KeyUsage.digitalSignature));
        } else {
            int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign;
            cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage));
        }
        cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName));
        cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true));
    }
    // For an app cert, most of the extensions will be added when generating
    // a certificate in response to the certificate request file.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    Certificate cert = cg.generate(keyPair.getPrivate());
    store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert });
    FileOutputStream fos = new FileOutputStream(keystoreFile);
    store.store(fos, keystorePassword.toCharArray());
    fos.close();
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception {
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile));
    String subject = csr.getCertificationRequestInfo().getSubject().toString();

    // Generate the app certificate
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();//  ww  w.j a va 2  s  . c o  m
    X509Certificate rootCert = (X509Certificate) store.getCertificate(alias);
    if (rootCert == null) {
        System.out
                .println("ERROR: Aborting application certificate creation." + " No root certificate to sign.");
        cleanup(); // removes the self signed certificate from the keystore
        System.exit(1);
    }
    cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter()));
    cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter()));
    cg.setNotBefore(rootCert.getNotBefore());
    cg.setNotAfter(rootCert.getNotAfter());
    cg.setPublicKey(csr.getPublicKey());
    cg.setSerialNumber(appCertSerNo);

    // BD-J mandates using SHA1WithRSA as a signature Algorithm
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature));

    // FIXME: Ideally this should be pulled out from the original app cert's
    // extension. Email on X500Name is not encoded with UTF8String.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    // Assuming that the root certificate was generated using our tool,
    // the certificate should have IssuerAlternativeNames as an extension.
    if (rootCert.getIssuerAlternativeNames() == null) {
        System.out.println("ERROR: the root certificate must have an alternate name");
        System.exit(1);
    }
    List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next();
    cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false,
            getRfc822Name((String) issuerName.get(1)));
    PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray());
    X509Certificate cert = cg.generate(privateKey);

    // Now, write leaf certificate
    System.out.println("Writing cert to " + certfile + ".");
    FileOutputStream str = new FileOutputStream(certfile);
    str.write(cert.getEncoded());
    str.close();
}

From source file:net.laubenberger.bogatyr.service.crypto.CertificateProviderImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final KeyPair pair, final String issuerDN, final String subjectDN,
        final String generalName, final Date start, final Date end)
        throws NoSuchAlgorithmException, IllegalStateException, CertificateEncodingException,
        InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException { //$JUnit$
    if (null == pair) {
        throw new RuntimeExceptionIsNull("pair"); //$NON-NLS-1$
    }// w w w  . ja  va2 s  .com
    if (null == issuerDN) {
        throw new RuntimeExceptionIsNull("issuerDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(issuerDN)) {
        throw new RuntimeExceptionIsEmpty("issuerDN"); //$NON-NLS-1$
    }
    if (null == subjectDN) {
        throw new RuntimeExceptionIsNull("subjectDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(subjectDN)) {
        throw new RuntimeExceptionIsEmpty("subjectDN"); //$NON-NLS-1$
    }
    if (null == generalName) {
        throw new RuntimeExceptionIsNull("generalName"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(generalName)) {
        throw new RuntimeExceptionIsEmpty("generalName"); //$NON-NLS-1$
    }
    if (null == start) {
        throw new RuntimeExceptionIsNull("start"); //$NON-NLS-1$
    }
    if (null == end) {
        throw new RuntimeExceptionIsNull("end"); //$NON-NLS-1$
    }
    if (start.after(end)) {
        throw new RuntimeExceptionMustBeBefore("start", start, end); //$NON-NLS-1$
    }

    // generate the certificate
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal(issuerDN));
    certGen.setNotBefore(start);
    certGen.setNotAfter(end);
    certGen.setSubjectDN(new X500Principal(subjectDN));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //$NON-NLS-1$

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, generalName)));

    return certGen.generate(pair.getPrivate(), provider.getName());
}