List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate
public X509Certificate generate(PrivateKey key, String provider) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
From source file:lt.bsprendimai.ddesk.servlets.CertGenerator.java
License:Apache License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request// ww w .ja v a2 s.c o m * servlet request * @param response * servlet response */ @SuppressWarnings("unchecked") protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { UserHandler uh = (UserHandler) request.getSession().getAttribute("userHandler"); ClientAccessor ca = (ClientAccessor) request.getSession().getAttribute("clientAccessor"); if (uh == null || !uh.isLoggedIn() || uh.getUser().getCompany() != 0 || uh.getUser().getLoginLevel() != 0) { response.sendRedirect(request.getContextPath()); return; } if (request.getParameter("X509Principal.PWD") == null) { request.setAttribute("T", ca.getPerson().getName()); request.setAttribute("USER", ca.getPerson().getLoginCode()); request.setAttribute("EMAIL", ca.getPerson().getEmail()); RequestDispatcher rd = request.getRequestDispatcher("/intranet/generation.jsp"); rd.forward(request, response); return; } Security.addProvider(new BouncyCastleProvider()); Hashtable attrs = new Hashtable(); Vector order = new Vector(); InputStreamReader rd = new InputStreamReader(CertGenerator.class.getResourceAsStream("/desk.pem")); PEMReader reader = new PEMReader(rd); Object oo = (KeyPair) reader.readObject(); KeyPair myKey = (KeyPair) oo; reader.close(); rd = new InputStreamReader(CertGenerator.class.getResourceAsStream("/desk.crt")); reader = new PEMReader(rd); X509Certificate root = (X509Certificate) reader.readObject(); reader.close(); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); PublicKey users = kp.getPublic(); String issuer = root.getSubjectDN().getName(); attrs.put(X509Principal.T, request.getParameter("X509Principal.T")); attrs.put(X509Principal.C, request.getParameter("X509Principal.C")); attrs.put(X509Principal.O, request.getParameter("X509Principal.O")); attrs.put(X509Principal.OU, request.getParameter("X509Principal.OU")); attrs.put(X509Principal.L, request.getParameter("X509Principal.L")); attrs.put(X509Principal.CN, request.getParameter("X509Principal.CN")); attrs.put(X509Principal.EmailAddress, request.getParameter("X509Principal.EmailAddress")); order.addElement(X509Principal.T); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.OU); order.addElement(X509Principal.L); order.addElement(X509Principal.CN); order.addElement(X509Principal.EmailAddress); X509Principal subjectDn = new X509Principal(order, attrs); Session sess = SessionHolder.currentSession().getSess(); CertificateEntry ce = new CertificateEntry(); ce.setCert(""); ce.setMd5Key(""); ce.setName(subjectDn.getName()); ce.setPerson(null); ce.setValid(false); sess.save(ce); sess.flush(); X509V3CertificateGenerator v3c = new X509V3CertificateGenerator(); v3c.reset(); v3c.setSerialNumber(BigInteger.valueOf(ce.getId())); v3c.setIssuerDN(new X509Principal(issuer)); v3c.setNotBefore(new Date()); v3c.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3c.setSubjectDN(subjectDn); v3c.setPublicKey(users); v3c.setSignatureAlgorithm("MD5WithRSAEncryption"); // // add the extensions // v3c.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.objectSigning)); X509Certificate cert = v3c.generate(myKey.getPrivate(), "BC"); cert.getSignature(); cert.checkValidity(new Date()); cert.verify(myKey.getPublic()); KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); store.setKeyEntry(request.getParameter("X509Principal.T"), kp.getPrivate(), null, new Certificate[] { cert, root }); StringWriter sr = new StringWriter(); sr.write("-----BEGIN CERTIFICATE-----\n"); sr.write(new String(Base64.encode(cert.getEncoded()))); sr.write("\n"); sr.write("-----END CERTIFICATE-----"); byte[] pwdMD5 = Hex.encode(MessageDigest.getInstance("MD5").digest(cert.getEncoded())); String code = new String(pwdMD5); if (code.length() < 32) { for (int i = (32 - code.length()); i > 0; i--) { code = "0" + code; } } List<CertificateEntry> lce = (List<CertificateEntry>) sess .createQuery("FROM " + CertificateEntry.class.getName() + " WHERE person = ? AND valid = true ") .setInteger(0, ca.getPersonId()).list(); for (CertificateEntry cea : lce) { ce.setValid(false); sess.update(cea); sess.flush(); } ce.setCert(sr.toString().trim()); ce.setMd5Key(code.trim()); ce.setPerson(ca.getPersonId()); ce.setValid(true); sess.update(ce); sess.flush(); SessionHolder.closeSession(); System.out.println("Writing certificate"); response.setContentType("application/pkcs-12"); response.setHeader("Content-disposition", "inline;filename=" + request.getParameter("X509Principal.T").trim() + ".p12"); OutputStream out = response.getOutputStream(); store.store(out, request.getParameter("X509Principal.PWD").trim().toCharArray()); out.close(); } catch (Exception ex) { try { SessionHolder.endSession(); } catch (Exception ejx) { } ex.printStackTrace(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Error</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Error: "); out.println(ex.getMessage()); out.println("</h1>"); out.println("<br/>"); out.println("</body>"); out.println("</html>"); out.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$ }//from w ww. j av a 2 s .c o m 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()); }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * Utility method for generating a "standard" server certificate. Recognized by most * browsers as valid for SSL/TLS. These certificates are generated de novo, not from * a template, so they will not retain the structure of the original certificate and may * not be suitable for applications that require Extended Validation/High Assurance SSL * or other distinct extensions or EKU.//from w w w . j a v a 2 s . c om * * @param newPubKey * @param caCert * @param caPrivateKey * @param hostname * @return * @throws CertificateParsingException * @throws SignatureException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ @SuppressWarnings({ "deprecation", "unused" }) public static X509Certificate generateStdSSLServerCertificate(final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, final String subject) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(new X500Principal(subject)); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); v3CertGen.setPublicKey(newPubKey); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 30L * 60 * 60 * 24 * 30 * 12)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30 * 12)); v3CertGen.setIssuerDN(caCert.getSubjectX500Principal()); // Firefox actually tracks serial numbers within a CA and refuses to validate if it sees duplicates // This is not a secure serial number generator, (duh!) but it's good enough for our purposes. v3CertGen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis()))); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey())); // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care. // v3CertGen.addExtension( // X509Extensions.KeyUsage, // false, // new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature ) ); DEREncodableVector typicalSSLServerExtendedKeyUsages = new DEREncodableVector(); typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth)); typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.clientAuth)); typicalSSLServerExtendedKeyUsages .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.netscapeServerGatedCrypto)); typicalSSLServerExtendedKeyUsages .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.msServerGatedCrypto)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalSSLServerExtendedKeyUsages)); // Disabled by default. Left in comments in case this is desired. // // v3CertGen.addExtension( // X509Extensions.AuthorityInfoAccess, // false, // new AuthorityInformationAccess(new DERObjectIdentifier(OID_ID_AD_CAISSUERS), // new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + subject + "/aia"))); // v3CertGen.addExtension( // X509Extensions.CRLDistributionPoints, // false, // new CRLDistPoint(new DistributionPoint[] {})); X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC"); return cert; }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * This method creates an X509v3 certificate based on an an existing certificate. * It attempts to create as faithful a copy of the existing certificate as possible * by duplicating all certificate extensions. * * If you are testing an application that makes use of additional certificate * extensions (e.g. logotype, S/MIME capabilities) this method will preserve those * fields./* w w w.j ava 2 s . c o m*/ * * You may optionally include a set of OIDs not to copy from the original certificate. * The most common reason to do this would be to remove fields that would cause inconsistency, * such as Authority Info Access or Issuer Alternative Name where these are not defined for * the MITM authority certificate. * * OIDs 2.5.29.14 : Subject Key Identifier and 2.5.29.35 : Authority Key Identifier, * are never copied, but generated directly based on the input keys and certificates. * * You may also optionally include maps of custom extensions which will be added to or replace * extensions with the same OID on the original certificate for the the MITM certificate. * * FUTURE WORK: JDK 1.5 is very strict in parsing extensions. In particular, known extensions * that include URIs must parse to valid URIs (including URL encoding all non-valid URI characters) * or the extension will be rejected and not available to copy to the MITM certificate. Will need * to directly extract these as ASN.1 fields and re-insert (hopefully BouncyCastle will handle them) * * * @param originalCert The original certificate to duplicate. * @param newPubKey The new public key for the MITM certificate. * @param caCert The certificate of the signing authority fot the MITM certificate. * @param caPrivateKey The private key of the signing authority. * @param extensionOidsNotToCopy An optional list of certificate extension OIDs not to copy to the MITM certificate. * @return The new MITM certificate. * @throws CertificateParsingException * @throws SignatureException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert, final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, Set<String> extensionOidsNotToCopy) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { if (extensionOidsNotToCopy == null) { extensionOidsNotToCopy = new HashSet<String>(); } X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(originalCert.getSubjectX500Principal()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // needs to be the same as the signing cert, not the copied cert v3CertGen.setPublicKey(newPubKey); v3CertGen.setNotAfter(originalCert.getNotAfter()); v3CertGen.setNotBefore(originalCert.getNotBefore()); v3CertGen.setIssuerDN(caCert.getSubjectX500Principal()); v3CertGen.setSerialNumber(originalCert.getSerialNumber()); // copy other extensions: Set<String> critExts = originalCert.getCriticalExtensionOIDs(); // get extensions returns null, not an empty set! if (critExts != null) { for (String oid : critExts) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), true, originalCert); } } } Set<String> nonCritExs = originalCert.getNonCriticalExtensionOIDs(); if (nonCritExs != null) { for (String oid : nonCritExs) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), false, originalCert); } } } v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey())); X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC"); // For debugging purposes. //cert.checkValidity(new Date()); //cert.verify(caCert.getPublicKey()); return cert; }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * Creates a typical Certification Authority (CA) certificate. * @param keyPair/* w w w .j a v a 2s . c om*/ * @throws SecurityException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ @SuppressWarnings("deprecation") public static X509Certificate createTypicalMasterCert(final KeyPair keyPair) throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); X509Principal issuer = new X509Principal( "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US"); // Create v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(issuer); v3CertGen.setSubjectDN(issuer); //Set validity period v3CertGen .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30))); v3CertGen .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30))); //Set signature algorithm & public key v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // Add typical extensions for signing cert v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector(); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages)); X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC"); cert.checkValidity(new Date()); cert.verify(keyPair.getPublic()); return cert; }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
License:Open Source License
/** * Generate an X509 cert for use as the keystore cert chain * //w w w .j av a 2s . co m * @param keyPair * @return */ private X509Certificate generateCertificate(KeyPair keyPair, NodeRef person) { X509Certificate cert = null; int validDuration = Integer .parseInt(config.getProperty(RepositoryManagedSignatureProviderFactory.VALID_DURATION)); // get user's first and last name Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(person); String firstName = String.valueOf(props.get(ContentModel.PROP_FIRSTNAME)); String lastName = String.valueOf(props.get(ContentModel.PROP_LASTNAME)); // backdate the start date by a day Calendar start = Calendar.getInstance(); start.add(Calendar.DATE, -1); java.util.Date startDate = start.getTime(); // what is the end date for this cert's validity? Calendar end = Calendar.getInstance(); end.add(Calendar.DATE, validDuration); java.util.Date endDate = end.getTime(); try { // This code works with newer versions of the BouncyCastle libraries, but not // the (severely outdated) version that ships with Alfresco /*X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder( new X500Principal("CN=" + firstName + " " + lastName), BigInteger.ONE, startDate, cal.getTime(), new X500Principal("CN=" + firstName + " " + lastName), keyPair.getPublic()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParam); X509CertificateHolder certHolder = certBuilder.build(sigGen); // now lets convert this thing back to a regular old java cert CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certIs = new ByteArrayInputStream(certHolder.getEncoded()); cert = (X509Certificate) cf.generateCertificate(certIs); certIs.close();*/ X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal subjectName = new X500Principal("CN=" + firstName + " " + lastName); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setNotBefore(startDate); certGen.setNotAfter(endDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // if we are actually generating a trusted cert, the action is a little different boolean generateTrusted = Boolean.parseBoolean( config.getProperty(RepositoryManagedSignatureProviderFactory.ENABLE_TRUSTED_CERTS)); if (generateTrusted) { KeyStore trustedKs = getTrustedKeyStore(); PrivateKey caKey = getCaKey(trustedKs); X509Certificate caCert = getCaCert(trustedKs); // set the issuer of the generated cert to the subject of the ca cert X500Principal caSubject = caCert.getSubjectX500Principal(); certGen.setIssuerDN(caSubject); //add the required extensions for the new cert certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); cert = certGen.generate(caKey, "BC"); //verify the cert cert.verify(caCert.getPublicKey()); } else { certGen.setIssuerDN(subjectName); cert = certGen.generate(keyPair.getPrivate(), "BC"); } } catch (CertificateException ce) { logger.error("CertificateException creating or validating X509 certificate for user: " + ce); throw new AlfrescoRuntimeException(ce.getMessage()); } catch (Exception ex) { logger.error("Unknown exception creating or validating X509 certificate for user : " + ex); ex.printStackTrace(); } return cert; }
From source file:org.apache.brooklyn.util.core.crypto.FluentKeySigner.java
License:Apache License
@SuppressWarnings("deprecation") public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) { try {//from ww w . j a v a 2s . co m org.bouncycastle.x509.X509V3CertificateGenerator v3CertGen = new org.bouncycastle.x509.X509V3CertificateGenerator(); v3CertGen.setSerialNumber(serialNumber != null ? serialNumber : // must be positive BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE)); v3CertGen.setIssuerDN(issuerPrincipal); v3CertGen.setNotBefore(validityStartDate); v3CertGen.setNotAfter(validityEndDate); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); v3CertGen.setSubjectDN(subject); v3CertGen.setPublicKey(keyToCertify); v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false, new org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure(keyToCertify)); if (authorityKeyIdentifier != null) v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC"); return pkCertificate; } catch (Exception e) { throw Exceptions.propagate(e); } }
From source file:org.atticfs.key.KeyUtils.java
License:Apache License
public static X509Certificate createSignedCertificate(KeyPair keyPair, PrivateKey caKey, X509Certificate caCert, String dn, int days) throws Exception { Date startDate = new Date(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, days); Date expiryDate = cal.getTime(); BigInteger serialNumber = randomHexInteger(64); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal subjectName = new X500Principal(dn); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(startDate);/*from w w w .j av a 2s . c o m*/ certGen.setNotAfter(expiryDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); X509Certificate cert = certGen.generate(caKey, providerName); // note: private key of CA return cert; }
From source file:org.browsermob.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * This method creates an X509v3 certificate based on an an existing certificate. * It attempts to create as faithful a copy of the existing certificate as possible * by duplicating all certificate extensions. * * If you are testing an application that makes use of additional certificate * extensions (e.g. logotype, S/MIME capabilities) this method will preserve those * fields./* w w w . ja v a 2s .c om*/ * * You may optionally include a set of OIDs not to copy from the original certificate. * The most common reason to do this would be to remove fields that would cause inconsistency, * such as Authority Info Access or Issuer Alternative Name where these are not defined for * the MITM authority certificate. * * OIDs 2.5.29.14 : Subject Key Identifier and 2.5.29.35 : Authority Key Identifier, * are never copied, but generated directly based on the input keys and certificates. * * You may also optionally include maps of custom extensions which will be added to or replace * extensions with the same OID on the original certificate for the the MITM certificate. * * FUTURE WORK: JDK 1.5 is very strict in parsing extensions. In particular, known extensions * that include URIs must parse to valid URIs (including URL encoding all non-valid URI characters) * or the extension will be rejected and not available to copy to the MITM certificate. Will need * to directly extract these as ASN.1 fields and re-insert (hopefully BouncyCastle will handle them) * * * @param originalCert The original certificate to duplicate. * @param newPubKey The new public key for the MITM certificate. * @param caCert The certificate of the signing authority fot the MITM certificate. * @param caPrivateKey The private key of the signing authority. * @param extensionOidsNotToCopy An optional list of certificate extension OIDs not to copy to the MITM certificate. * @param criticalCustomExtensions An optional map of critical extension OIDs to add/replace on the MITM certificate. * @param noncriticalCustomExtensions An optional map of non-critical extension OIDs to add/replace on the MITM certificate. * @return The new MITM certificate. * @throws CertificateParsingException * @throws SignatureException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert, final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, Set<String> extensionOidsNotToCopy, Map<String, DEREncodable> criticalCustomExtensions, Map<String, DEREncodable> noncriticalCustomExtensions) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { if (extensionOidsNotToCopy == null) { extensionOidsNotToCopy = new HashSet<String>(); } if (noncriticalCustomExtensions == null) { noncriticalCustomExtensions = new HashMap<String, DEREncodable>(); } if (criticalCustomExtensions == null) { criticalCustomExtensions = new HashMap<String, DEREncodable>(); } X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(originalCert.getSubjectX500Principal()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // needs to be the same as the signing cert, not the copied cert v3CertGen.setPublicKey(newPubKey); v3CertGen.setNotAfter(originalCert.getNotAfter()); v3CertGen.setNotBefore(originalCert.getNotBefore()); v3CertGen.setIssuerDN(caCert.getSubjectX500Principal()); v3CertGen.setSerialNumber(originalCert.getSerialNumber()); // copy other extensions: Set<String> critExts = originalCert.getCriticalExtensionOIDs(); // get extensions returns null, not an empty set! if (critExts != null) { for (String oid : critExts) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid) && !criticalCustomExtensions.containsKey(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), true, originalCert); } } } Set<String> nonCritExs = originalCert.getNonCriticalExtensionOIDs(); if (nonCritExs != null) { for (String oid : nonCritExs) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid) && !noncriticalCustomExtensions.containsKey(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), false, originalCert); } } } for (Map.Entry<String, DEREncodable> customExtension : criticalCustomExtensions.entrySet()) { v3CertGen.addExtension(customExtension.getKey(), true, customExtension.getValue()); } for (Map.Entry<String, DEREncodable> customExtension : noncriticalCustomExtensions.entrySet()) { v3CertGen.addExtension(customExtension.getKey(), false, customExtension.getValue()); } v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey())); X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC"); // For debugging purposes. //cert.checkValidity(new Date()); //cert.verify(caCert.getPublicKey()); return cert; }
From source file:org.browsermob.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * Creates a typical Certification Authority (CA) certificate. * @param keyPair//from w w w. j ava 2s .c o m * @throws SecurityException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ @SuppressWarnings("deprecation") public static X509Certificate createTypicalMasterCert(final KeyPair keyPair) throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); X509Principal issuer = new X509Principal( "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US"); // Create v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(issuer); v3CertGen.setSubjectDN(issuer); //Set validity period v3CertGen .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30))); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 48 /* months */ * (1000L * 60 * 60 * 24 * 30))); //Set signature algorithm & public key v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // Add typical extensions for signing cert v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector(); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages)); X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC"); cert.checkValidity(new Date()); cert.verify(keyPair.getPublic()); return cert; }