List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator addExtension
public void addExtension(ASN1ObjectIdentifier oid, boolean critical, byte[] value)
From source file:org.openmaji.implementation.server.security.auth.CoreAdminHelper.java
License:Open Source License
private static void userAdd(String userID, char[] userPass, String userName, String emailAddress, Date expiryDate) throws Exception { if (!userID.toLowerCase().equals(userID)) { throw new IllegalArgumentException("username's cannot have mixed case - must be lower case only."); }// w w w . j a v a 2 s. c o m String keyStorePasswd = System.getProperty(MeemCoreRootAuthority.KEYSTORE_PASSWD); if (keyStorePasswd == null) { throw new RuntimeException("unable to find property for key store password."); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); MajiKeyStore keyStore = MeemCoreRootAuthority.getMajiKeyStore(); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA"); kpGen.initialize(1024); // get "server" key PrivateKey signingKey = (PrivateKey) keyStore.getKey(MeemCoreRootAuthority.KEY_ID, keyStorePasswd.toCharArray()); Certificate[] certs = keyStore.getCertificateChain(MeemCoreRootAuthority.KEY_ID); X509Certificate signingCert = (X509Certificate) certs[0]; KeyPair userKey = kpGen.generateKeyPair(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(signingCert)); certGen.setNotBefore(new Date()); certGen.setNotAfter(expiryDate); certGen.setPublicKey(userKey.getPublic()); if (emailAddress != null) { certGen.setSubjectDN(new X509Principal(new X500Principal("CN=" + userName + ", T=" + userID + ", EMAILADDRESS=" + emailAddress + ", OU=Maji, O=Majitek, C=AU").getEncoded())); } else { certGen.setSubjectDN(new X509Principal( new X500Principal("CN=" + userName + ", T=" + userID + ", OU=Maji, O=Majitek, C=AU") .getEncoded())); } certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(userKey.getPublic())); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(certs[0].getPublicKey(), PrincipalUtil.getSubjectX509Principal(signingCert), signingCert.getSerialNumber())); X509Certificate newCert = certGen.generateX509Certificate(signingKey); Certificate[] chain = new Certificate[certs.length + 1]; chain[0] = newCert; System.arraycopy(certs, 0, chain, 1, certs.length); // // having set up the chain add the user. // MajiKeyStore userKeyStore = MeemCoreRootAuthority.getUserKeyStore(); try { Certificate[] testCerts = userKeyStore.getCertificateChain(userID); if (testCerts != null) { logger.log(Level.WARNING, "User, \"" + userID + "\" already exists. The certificate chain might not be updated"); } } catch (KeyStoreException e) { } userKeyStore.setKeyEntry(userID, userKey.getPrivate(), userPass, chain); logger.log(Level.INFO, "User, \"" + userID + "\" added."); userKeyStore.store(); // // store the encrypted password // byte[] userPassBytes = new byte[userPass.length]; for (int i = 0; i != userPass.length; i++) { userPassBytes[i] = (byte) userPass[i]; } Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey()); MeemCoreRootAuthority.getUserPasswordFile().setPassword(userID, cipher.doFinal(userPassBytes)); }
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 www. j a va 2 s .c om*/ 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// www . ja va 2 s . 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
private static void addCACertificateExtensions(X509V3CertificateGenerator certGen) throws IOException { // Basic Constraints certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); }
From source file:org.owasp.proxy.util.BouncyCastleCertificateUtils.java
License:Open Source License
private static void addCertificateExtensions(PublicKey pubKey, PublicKey caPubKey, X509V3CertificateGenerator certGen) throws IOException, InvalidKeyException { // CertificateExtensions ext = new CertificateExtensions(); ////from www. j a v a 2s .c o m // ext.set(SubjectKeyIdentifierExtension.NAME, // new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey) // .getIdentifier())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // // ext.set(AuthorityKeyIdentifierExtension.NAME, // new AuthorityKeyIdentifierExtension( // new KeyIdentifier(caPubKey), null, null)); // certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caPubKey)); // // Basic Constraints // ext.set(BasicConstraintsExtension.NAME, new // BasicConstraintsExtension( // /* isCritical */true, /* isCA */false, /* pathLen */5)); // certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // Netscape Cert Type Extension // boolean[] ncteOk = new boolean[8]; // ncteOk[0] = true; // SSL_CLIENT // ncteOk[1] = true; // SSL_SERVER // NetscapeCertTypeExtension ncte = new // NetscapeCertTypeExtension(ncteOk); // ncte = new NetscapeCertTypeExtension(false, // ncte.getExtensionValue()); // ext.set(NetscapeCertTypeExtension.NAME, ncte); // Key Usage Extension // boolean[] kueOk = new boolean[9]; // kueOk[0] = true; // kueOk[2] = true; // "digitalSignature", // (0), // "nonRepudiation", // (1) // "keyEncipherment", // (2), // "dataEncipherment", // (3), // "keyAgreement", // (4), // "keyCertSign", // (5), // "cRLSign", // (6), // "encipherOnly", // (7), // "decipherOnly", // (8) // "contentCommitment" // also (1) // KeyUsageExtension kue = new KeyUsageExtension(kueOk); // ext.set(KeyUsageExtension.NAME, kue); certGen.addExtension(X509Extensions.KeyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature + X509KeyUsage.keyEncipherment)); // Extended Key Usage Extension // int[] serverAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 1 }; // ObjectIdentifier serverAuthOid = new // ObjectIdentifier(serverAuthOidData); // int[] clientAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 2 }; // ObjectIdentifier clientAuthOid = new // ObjectIdentifier(clientAuthOidData); // Vector<ObjectIdentifier> v = new Vector<ObjectIdentifier>(); // v.add(serverAuthOid); // v.add(clientAuthOid); // ExtendedKeyUsageExtension ekue = new ExtendedKeyUsageExtension(false, // v); // ext.set(ExtendedKeyUsageExtension.NAME, ekue); // ExtendedKeyUsage extendedKeyUsage = new // ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage); Vector<KeyPurposeId> usages = new Vector<KeyPurposeId>(); usages.add(KeyPurposeId.id_kp_serverAuth); usages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(usages)); }
From source file:org.pidome.server.services.provider.CertGen.java
License:Apache License
private void gen() throws CertGenException { try {//from w w w . j a v a2s . c om 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 {// ww w. ja va2s . c o 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.validationservice.server.ValidationTestUtils.java
License:Open Source License
public static X509Certificate genCert(String dn, String issuerdn, PrivateKey privKey, PublicKey pubKey, Date startDate, Date endDate, boolean isCA, int keyUsage, CRLDistPoint crlDistPoint) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException { X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno);/*from w w w.j ava 2 s. c o m*/ certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(startDate); certgen.setNotAfter(endDate); certgen.setSignatureAlgorithm("SHA1WithRSA"); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(issuerdn)); certgen.setPublicKey(pubKey); // CRL Distribution point if (crlDistPoint != null) { certgen.addExtension(X509Extensions.CRLDistributionPoints, false, crlDistPoint); } // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (keyUsage == 0) { if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } } else { X509KeyUsage ku = new X509KeyUsage(keyUsage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } X509Certificate cert = certgen.generate(privKey); return cert; }
From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.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 public key//from w ww. j a v a 2 s. c om * @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 current date and time * if null) * * @param subjAltNameURI URI to be placed in subjectAltName * @return self-signed certificate * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IllegalStateException * @throws NoSuchProviderException * @throws CertificateException * @throws Exception * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, X509Name subject, Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException { X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); /* * Sets up the subject distinguished name. Since it's a self-signed certificate, issuer and * subject are the same. */ certGenerator.setIssuerDN(subject); certGenerator.setSubjectDN(subject); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } certGenerator.setNotBefore(startDate); if (endDate == null) { endDate = new Date(startDate.getTime() + (365L * 24L * 60L * 60L * 1000L)); Log.d(Constants.TAG, "end date is=" + DateFormat.getDateInstance().format(endDate)); } certGenerator.setNotAfter(endDate); /* * The serial-number of this certificate is 1. It makes sense because it's self-signed. */ certGenerator.setSerialNumber(BigInteger.ONE); /* * Sets the public-key to embed in this certificate. */ certGenerator.setPublicKey(pubKey); /* * Sets the signature algorithm. */ String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { certGenerator.setSignatureAlgorithm("SHA1WithDSA"); } else if (pubKeyAlgorithm.equals("RSA")) { certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption"); } else { RuntimeException re = new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); Log.e(Constants.TAG, re.getMessage(), re); throw re; } /* * Adds the Basic Constraint (CA: true) extension. */ certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjAltNameURI != null) { GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.uniformResourceIdentifier, subjAltNameURI)); certGenerator.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltNames); } /* * Creates and sign this certificate with the private key corresponding to the public key of * the certificate (hence the name "self-signed certificate"). */ X509Certificate cert = certGenerator.generate(privKey); /* * Checks that this certificate has indeed been correctly signed. */ cert.verify(pubKey); return cert; }
From source file:org.tramaci.onionmail.LibSTLS.java
License:Open Source License
public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info, String[] AltName) throws Exception { //OK byte[] bi = Stdio.md5(onion.getBytes()); byte[] bx = new byte[bi.length + 9]; System.arraycopy(bi, 0, bx, 1, bi.length); bx[0] = 0x7C;//from w w w. j a v a2s . c om byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4); int bp = 17; for (int ax = 0; ax < 8; ax++) bx[bp++] = tmp[ax]; Date startDate = new Date(Dfrom); // time from which certificate is valid Date expiryDate = new Date(Dto); // time after which certificate is not valid BigInteger serialNumber = new BigInteger(bx); // serial number for certificate KeyPair keyPair = KP; // EC public/private key pair X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); if (info != null && info.length() > 0) info = ", " + info; else info = ""; X500Principal dnName = new X500Principal("CN=" + onion + info); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setPublicKey(KP.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); if (AltName != null) { int cx = AltName.length; for (int ax = 0; ax < cx; ax++) try { GeneralName generalName = new GeneralName(GeneralName.dNSName, new DERIA5String(AltName[ax].toLowerCase().trim())); GeneralNames subjectAltNames = new GeneralNames(generalName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new DEROctetString(subjectAltNames)); } catch (Exception EI) { Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n"); } } X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC"); return cert; }