Example usage for org.bouncycastle.x509 X509V3CertificateGenerator generate

List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate

Introduction

In this page you can find the example usage for org.bouncycastle.x509 X509V3CertificateGenerator generate.

Prototype

public X509Certificate generate(PrivateKey key, String provider)
        throws CertificateEncodingException, IllegalStateException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException 

Source Link

Document

generate an X509 certificate, based on the current issuer and subject, using the passed in provider for the signing.

Usage

From source file:org.objectweb.proactive.extensions.ssl.CertificateGenerator.java

License:Open Source License

/**
 * Create a random, self signed, one time certificate
 *
 * A such certificate can be used to take advantage of the SSL/TLS encryption
 * feature without requiring any action from the user.
 *
 * A self signed certificate, valid for the next 10 year is issued.
 *
 * @return/*from  w ww .  ja v a  2  s  . c o m*/
 */
public X509Certificate generateCertificate(String subjectDN, KeyPair pair) throws SslException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Auto-generated certificate, use a default principal
    X500Principal defaultPrincipal;
    defaultPrincipal = new X500Principal(subjectDN);
    certGen.setIssuerDN(defaultPrincipal);
    certGen.setSubjectDN(defaultPrincipal);

    // Valid for the next few years
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + (10 * 365 * 24 * 60)));

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

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

    // Not certified by a CA
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // SSL requires signiture & encipherment
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
    certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage);

    // Allow client and server authentication
    Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>();
    extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsageV));

    try {
        X509Certificate cert = certGen.generate(pair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME);
        try {
            cert.checkValidity();
            cert.verify(pair.getPublic());
        } catch (GeneralSecurityException e) {
            throw new SslException("Generated certificate is not valid", e);
        }

        return cert;
    } catch (GeneralSecurityException e) {
        throw new SslException("Failed to generate certificate", e);
    }
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * /*  w w  w.j a  va2 s .  c  o  m*/
 * @param commonName - Common Name (CN) for generated certificate
 * @param organisation - Organisation (O) for generated certificate
 * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null
 * @param validityTime - the time that the certificate is valid (in days)
 * @return
 * @throws IOException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws CertificateParsingException
 */
public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate(
        String commonName, String organisation, String applicationUri, int validityTime) throws IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException,
        IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException {
    if (applicationUri == null)
        throw new NullPointerException("applicationUri must not be null");
    //Add provider for generator
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    //Initializes generator 
    SecureRandom srForCert = new SecureRandom();
    RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator();

    //Used for generating prime
    Random r = new Random(System.currentTimeMillis());
    int random = -1;

    while (random < 3) {
        random = r.nextInt(32);
    }
    //calculate(generate) possible value for public modulus
    //used method is "monte carlo -algorithm", so we calculate it as long as it generates value.
    BigInteger value = null;
    while (value == null) {
        value = BigInteger.probablePrime(random, new SecureRandom());
    }

    //Generate (Java) keypair
    genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80));
    AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair();

    //Extract the keys from parameters
    logger.debug("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic();
    RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(),
            clientPublicKey.getExponent());
    logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent="
            + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus());

    // JCE format needed for the certificate - because getEncoded() is necessary...
    PublicKey certPubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent()));
    // and this one for the KeyStore
    PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate(
            new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(),
                    clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(),
                    clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv()));

    //The data for the certificate..
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.add(Calendar.DAY_OF_YEAR, validityTime);

    X509Name certificateX509Name = new X509Name(
            "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country"));

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    certGen.setSerialNumber(serial);
    //Issuer and subject must be the same (because this is self signed)
    certGen.setIssuerDN(certificateX509Name);
    certGen.setSubjectDN(certificateX509Name);

    //expiry & start time for this certificate
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks)
    certGen.setNotAfter(expiryTime.getTime());

    certGen.setPublicKey(certPubKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //******* X.509 V3 Extensions *****************

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject());
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki);

    /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
    new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey)));
        */
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
    certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation
                            | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    BasicConstraints b = new BasicConstraints(false);

    Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage(
                    extendedKeyUsages));

    // create the extension value
    ASN1EncodableVector names = new ASN1EncodableVector();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    //      GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri);
    //      names.add(dnsName);
    final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

    // AuthorityKeyIdentifier

    final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name));
    AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
    //***** generate certificate ***********/
    X509Certificate cert = certGen.generate(certPrivKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert certificate = new Cert(cert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) certPrivKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey);
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

@Deprecated //Use createApplicationInstanceCertificate instead of this...all the x.509 cert fields are not fulfilled in this
public static org.opcfoundation.ua.transport.security.KeyPair generateKeyPair(String CN) throws Exception {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALG, PROV);
    keyGenerator.initialize(KEY_SIZE);//from   w  w w . j  a v a 2 s  .co m
    KeyPair key = keyGenerator.generateKeyPair();
    PublicKey publicKey = key.getPublic();
    PrivateKey privateKey = key.getPrivate();

    //Keystore not needed in this function (at the moment)
    ///KeyStore keyStore = null;

    ////keyStore = KeyStore.getInstance(STORE_TYPE);
    ///keyStore.load(null,STORE_PASSWD.toCharArray());

    //Use BouncyCastle as Security provider
    new CryptoUtil();
    //////X509Certificate[] chain = new X509Certificate[1];

    //Generates new certificate..add the information needed for the generator
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal("CN=" + CN);
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    //X509Certificate caCert=null;
    certGen.setIssuerDN(subjectName);
    Date notBefore = new Date();
    Date notAfter = new Date();
    notBefore.setTime(notBefore.getTime() - 1000 * 60 * 60);
    notAfter.setTime(notAfter.getTime() + 1000 * 60 * 60 * 24 * 365);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //X.509 V3 Extensions...these are just examples

    //certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,new AuthorityKeyIdentifierStructure(caCert));
    ///7certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
    ////      new SubjectKeyIdentifierStructure(key.getPublic()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new DEROctetString(new SubjectKeyIdentifierStructure(key.getPublic())));

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

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /////chain[0]= certGen.generate(privateKey, "BC"); // note: private key of CA
    //Generate
    X509Certificate caCert = certGen.generate(privateKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert cert = new Cert(caCert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) privateKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(cert, UAkey);
    /*keyStore.setEntry(ALIAS,new KeyStore.PrivateKeyEntry(privateKey, chain),
    new KeyStore.PasswordProtection(KEY_PASSWD.toCharArray())
    );
            
    // Write out the keystore
    FileOutputStream keyStoreOutputStream = new FileOutputStream(keystorePath);
    keyStore.store(keyStoreOutputStream, "123456".toCharArray());
    keyStoreOutputStream.close();*/

}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

private static X509Certificate generateRootCertificate(KeyPair pair)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException {
    // generate root certificate
    X509V3CertificateGenerator certGenRoot = new X509V3CertificateGenerator();
    certGenRoot.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGenRoot.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGenRoot.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGenRoot.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGenRoot.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGenRoot.setPublicKey(pair.getPublic());
    certGenRoot.setSignatureAlgorithm("SHA1WithRSAEncryption");
    return certGenRoot.generate(pair.getPrivate(), "BC");
}

From source file:org.opensc.test.pkcs11.SaveCertificateTest.java

License:Open Source License

public void testX509CertificateGeneration() throws KeyStoreException, NoSuchProviderException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, IllegalStateException, SignatureException, InvalidKeySpecException {
    KeyStore ks = KeyStore.getInstance("PKCS11", "OpenSC-PKCS11");

    PKCS11LoadStoreParameter params = new PKCS11LoadStoreParameter();

    PINEntry pe = new PINEntry();

    params.setWaitForSlot(true);/*from ww w.  ja va2 s .  c  o m*/
    params.setProtectionCallback(pe);
    params.setSOProtectionCallback(pe);
    params.setWriteEnabled(true);
    params.setEventHandler(pe);

    ks.load(params);

    // well, find a private key.
    Enumeration<String> aliases = ks.aliases();

    String alias = null;

    while (aliases.hasMoreElements()) {
        String s = aliases.nextElement();
        if (ks.isKeyEntry(s)) {
            alias = s;
            break;
        }
    }

    assertNotNull(alias);

    PKCS11PrivateKey privKey = (PKCS11PrivateKey) ks.getKey(alias, null);
    PKCS11PublicKey pubKey = privKey.getPublicKey();

    KeyFactory kf = KeyFactory.getInstance(pubKey.getAlgorithm());

    PublicKey dup = (PublicKey) kf.translateKey(pubKey);

    PKCS11Id enc1 = new PKCS11Id(pubKey.getEncoded());
    PKCS11Id enc2 = new PKCS11Id(dup.getEncoded());

    System.out.println("enc1=" + enc1);
    System.out.println("enc2=" + enc2);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    long now = System.currentTimeMillis();

    certGen.setSerialNumber(BigInteger.valueOf(now));

    X509Principal subject = new X509Principal("CN=PKCS11 Test CA,DC=opensc-project,DC=org");

    certGen.setIssuerDN(subject);
    certGen.setSubjectDN(subject);

    Date from_date = new Date(now);
    certGen.setNotBefore(from_date);
    Calendar cal = new GregorianCalendar();
    cal.setTime(from_date);
    cal.add(Calendar.YEAR, 4);
    Date to_date = cal.getTime();
    certGen.setNotAfter(to_date);

    certGen.setPublicKey(dup);
    certGen.setSignatureAlgorithm("SHA256withRSA");
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    X509Certificate x509 = certGen.generate(privKey, "OpenSC-PKCS11");

    ks.setCertificateEntry(alias, x509);
}

From source file:org.overlord.commons.karaf.commands.saml.GenerateSamlKeystoreUtil.java

License:Apache License

/**
 * Creates a new key pair and self-signed certificate.
 *
 * @param alias/*from   ww w  .  j  av a2s.c om*/
 *            the alias
 * @param dname
 *            the dname
 * @param keyAlgName
 *            the key alg name
 * @param keysize
 *            the keysize
 * @param sigAlgName
 *            the sig alg name
 * @throws Exception
 *             the exception
 */
private void doGenKeyPair(String alias, String dname, String keyAlgName, int keysize, String sigAlgName)
        throws Exception {

    if (keysize == -1) {
        if ("EC".equalsIgnoreCase(keyAlgName)) { //$NON-NLS-1$
            keysize = 256;
        } else if ("RSA".equalsIgnoreCase(keyAlgName)) { //$NON-NLS-1$
            keysize = 2048;
        } else {
            keysize = 1024;
        }
    }

    if (keyStore.containsAlias(alias)) {
        throw new Exception(Messages.getString("Key.pair.not.generated.alias.alias.already.exists")); //$NON-NLS-1$
    }

    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(keyAlgName);
    }

    KeyPairGenerator generator = KeyPairGenerator.getInstance(keyAlgName);
    generator.initialize(keysize);
    KeyPair keypair = generator.generateKeyPair();
    PrivateKey privKey = keypair.getPrivate();

    X509Certificate[] chain = new X509Certificate[1];

    Date date = getStartDate(startDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date); // Configuramos la fecha que se recibe
    calendar.add(Calendar.DAY_OF_YEAR, validity);
    // time from which certificate is valid
    Date expiryDate = calendar.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger("10"); // serial number for certificate //$NON-NLS-1$
    // private key of the certifying authority (ca) certificate

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal(dname);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(subjectName);
    certGen.setNotBefore(date);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(keypair.getPublic());
    certGen.setSignatureAlgorithm("SHA256withRSA"); //$NON-NLS-1$

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

    X509Certificate cert = certGen.generate(keypair.getPrivate(), providerName);
    chain[0] = cert;

    keyStore.setKeyEntry(alias, privKey, keyPass, chain);
}

From source file:org.owasp.proxy.util.BouncyCastleCertificateUtils.java

License:Open Source License

public static X509Certificate sign(X500Principal subject, PublicKey pubKey, X500Principal issuer,
        PublicKey caPubKey, PrivateKey caKey, Date begin, Date ends, BigInteger serialNo)
        throws GeneralSecurityException {

    try {/* w  w w .  j av  a2 s  .co  m*/
        // X500Name issuerName = new X500Name(issuer.getName());
        // X500Name subjectName = new X500Name(subject.getName());
        // AlgorithmIdentifier algId = new
        // AlgorithmIdentifier(pubKey.getAlgorithm());
        // SubjectPublicKeyInfo publicKeyInfo = new
        // SubjectPublicKeyInfo(algId, pubKey.getEncoded());
        //
        // X509v1CertificateBuilder certBuilder = new
        // X509v1CertificateBuilder(issuerName, serialNo, begin, ends,
        // subjectName, publicKeyInfo);
        // ContentSigner cs = new
        // JcaContentSignerBuilder(SIGALG).setProvider("BC").build(caKey);
        // X509CertificateHolder holder = certBuilder.build(cs);
        // Certificate bcCert = holder.toASN1Structure();
        // bcCert.get
        // X509V1CertificateGenerator certGen = new
        // X509V1CertificateGenerator();
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

        certGen.setSerialNumber(serialNo);
        certGen.setIssuerDN(issuer);
        certGen.setNotBefore(begin);
        certGen.setNotAfter(ends);
        certGen.setSubjectDN(subject);
        certGen.setPublicKey(pubKey);

        certGen.setSignatureAlgorithm(SIGALG);

        // add Extensions
        if (subject == issuer) {
            addCACertificateExtensions(certGen);
        } else {
            addCertificateExtensions(pubKey, caPubKey, certGen);
        }

        X509Certificate cert = certGen.generate(caKey, "BC"); // note:
                                                              // private
                                                              // key of CA

        return cert;
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateEncodingException("generate: " + e.getMessage(), e);
    }
}

From source file:org.pidome.server.services.provider.CertGen.java

License:Apache License

private void gen() throws CertGenException {
    try {/*from ww  w .j  a v  a 2 s  .co m*/
        File store = new File(SystemConfig.getProperty("system", "server.keystore"));
        store.getParentFile().mkdirs();
        if (store.exists()) {
            store.delete();
        }
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setSubjectDN(new X500Principal("CN=" + curHost));
        certGen.setIssuerDN(new X500Principal("CN=PiDome Server at " + curHost));
        certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        certGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        certGen.setPublicKey(KPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

        GeneralName altName = new GeneralName(GeneralName.iPAddress,
                Network.getIpAddressProperty().get().getHostAddress());
        GeneralNames subjectAltName = new GeneralNames(altName);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

        X509Certificate cert = certGen.generate(KPair.getPrivate(), "BC");

        /// Always, but always create a new keystore. a new keystore pass has is always created.
        privateKS = KeyStore.getInstance("JKS");
        privateKS.load(null, null);

        String storePass = MessageDigest.getInstance("MD5").toString();

        privateKS.setKeyEntry("PiDome.Default", KPair.getPrivate(), storePass.toCharArray(),
                new java.security.cert.Certificate[] { cert });

        store.createNewFile();

        privateKS.store(new FileOutputStream(store), storePass.toCharArray());

        System.setProperty("javax.net.ssl.keyStore", SystemConfig.getProperty("system", "server.keystore"));
        System.setProperty("javax.net.ssl.keyStorePassword", storePass);

        available = true;

        LOG.info("Certificate(s) generated.");

    } catch (CertificateEncodingException ex) {
        throw new CertGenException("Could not encode certificate, can not continue: " + ex.getMessage());
    } catch (IllegalStateException ex) {
        throw new CertGenException("Illegal state, can not continue: " + ex.getMessage());
    } catch (NoSuchProviderException ex) {
        throw new CertGenException("No known provider, can not continue: " + ex.getMessage());
    } catch (NoSuchAlgorithmException ex) {
        throw new CertGenException("No such algorithm, can not continue: " + ex.getMessage());
    } catch (SignatureException ex) {
        throw new CertGenException("Signature problem, can not continue: " + ex.getMessage());
    } catch (InvalidKeyException ex) {
        throw new CertGenException("Invalid key used, can not continue: " + ex.getMessage());
    } catch (KeyStoreException ex) {
        throw new CertGenException("KeyStore problem, can not continue: " + ex.getMessage());
    } catch (IOException ex) {
        throw new CertGenException("KeyStore can not be opened, can not continue: " + ex.getMessage());
    } catch (CertificateException ex) {
        throw new CertGenException("KeyStore certificate problem, can not continue: " + ex.getMessage());
    } catch (ConfigPropertiesException ex) {
        throw new CertGenException(
                "KeyStore location configuration problem, can not continue: " + ex.getMessage());
    }
}

From source file:org.qipki.crypto.x509.X509GeneratorImpl.java

License:Open Source License

@Override
public X509Certificate generateX509Certificate(PrivateKey privateKey, DistinguishedName issuerDN,
        BigInteger serialNumber, DistinguishedName subjectDN, PublicKey publicKey, Duration validity,
        List<X509ExtensionHolder> x509Extensions) {
    try {/*from  w ww.  java2s.co m*/

        X509V3CertificateGenerator x509v3Generator = new X509V3CertificateGenerator();

        DateTime now = new DateTime();

        x509v3Generator.setSerialNumber(serialNumber);
        x509v3Generator.setSubjectDN(subjectDN.toX500Principal());
        x509v3Generator.setIssuerDN(issuerDN.toX500Principal());
        x509v3Generator.setNotBefore(now.minus(Time.CLOCK_SKEW).toDate());
        x509v3Generator.setNotAfter(now.plus(validity).minus(Time.CLOCK_SKEW).toDate());
        x509v3Generator.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString());
        x509v3Generator.setPublicKey(publicKey);

        for (X509ExtensionHolder eachExtensionHolder : x509Extensions) {
            x509v3Generator.addExtension(eachExtensionHolder.getDerOID(), eachExtensionHolder.isCritical(),
                    eachExtensionHolder.getValue());
        }

        return x509v3Generator.generate(privateKey, cryptoContext.providerName());

    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to generate X509Certificate", ex);
    } catch (IllegalStateException ex) {
        throw new CryptoFailure("Unable to generate X509Certificate", ex);
    }
}

From source file:org.signserver.module.renewal.worker.MockCA.java

License:Open Source License

private static X509Certificate createCertificate(String subject, String issuer, long validity, String sigAlg,
        PublicKey pubKey, PrivateKey caPrivateKey) throws Exception {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    // Add all mandatory attributes
    cg.setSerialNumber(BigInteger.valueOf(firstDate.getTime()));
    LOG.debug("keystore signing algorithm " + sigAlg);
    cg.setSignatureAlgorithm(sigAlg);//from  ww  w  .j ava2 s .  c  om
    cg.setSubjectDN(new X500Principal(subject));

    if (pubKey == null) {
        throw new Exception("Public key is null");
    }
    cg.setPublicKey(pubKey);
    cg.setNotBefore(firstDate);
    cg.setNotAfter(lastDate);
    cg.setIssuerDN(new X500Principal(issuer));
    return cg.generate(caPrivateKey, "BC");
}