List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator reset
public void reset()
From source file:com.vmware.demo.SamlUtils.java
License:Open Source License
/** * Generate a public x509 cert, based on a key. * * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed. * @param issuer If generating an SSL Cert, issuer needs to match hostname * @return/*ww w .j av a2s. c o m*/ * @throws SamlException */ public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException { X509Certificate binCert; try { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years v3CertGen.setSubjectDN(new X509Principal(issuer)); v3CertGen.setPublicKey(key.getPublic()); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false, new BasicConstraints(true)); // generate the actual cert binCert = v3CertGen.generate(key.getPrivate()); // check the cert binCert.checkValidity(new Date()); binCert.verify(key.getPublic()); } catch (Exception e) { throw new SamlException("Failed to generate certificate.", e); } return binCert; }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
License:Open Source License
private X509V3CertificateGenerator buildX509V3CertificateGenerator(PublicKey publicKey, X509Certificate caCert, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays) throws CertificateEncodingException, CertificateParsingException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // Calculate Expiration Date Calendar notBeforeCal = Calendar.getInstance(); Date notBeforeDate = notBeforeCal.getTime(); Calendar notAfterCal = Calendar.getInstance(); notAfterCal.add(Calendar.DAY_OF_YEAR, validDays); Date notAfterDate = notAfterCal.getTime(); ///*w w w . j a v a 2 s . c om*/ // create the certificate - version 3 // v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(serialNumber)); v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); v3CertGen.setNotBefore(notBeforeDate); v3CertGen.setNotAfter(notAfterDate); v3CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName))); v3CertGen.setPublicKey(publicKey); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // // extensions // v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); return v3CertGen; }
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// w w w.ja v a 2 s . com * @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:lt.bsprendimai.ddesk.servlets.CertGenerator.java
License:Apache License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request/*w w w .j a v a 2 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.java.bd.tools.security.OnlineKeytool.java
License:Open Source License
/** * Creates a self signed certificate using the public key * from the "online.crt" file. See BD-ROM specification part 3.2, * version 2.2 Annex DD./*from w ww .j a va2 s.co m*/ * The certificate fields other than the key pair do not matter. * The certificate is just a place holder in the keystore. * The private key is created from the BDA binary file. * <p> * @throws java.lang.Exception */ public void createSelfSignedCert() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(crtFile)); String typeIndicator = SecurityUtil.readISO646String(dis, 4); if (!typeIndicator.equals("OCRT")) { throw new RuntimeException("Invalid TypeIndicator: " + typeIndicator + " in " + crtFile); } String versionNo = SecurityUtil.readISO646String(dis, 4); if (!versionNo.equals("0200")) { throw new RuntimeException("Invalid Version No:" + versionNo + " in " + crtFile); } // reserved bytes dis.skipBytes(32); int certVerNo = dis.readInt(); if (certVerNo != 0) { throw new RuntimeException("Invalid Certificate Version No:" + certVerNo); } int contentOwnerId = dis.readInt(); if (debug) { System.out.println("Content owner ID:" + contentOwnerId); } // reserved bytes dis.skipBytes(32); String contentOwnerName = SecurityUtil.readISO646String(dis, 256); if (debug) { System.out.println("Content owner Name:" + contentOwnerName); } String dn = "cn=" + contentOwnerName; // used in cert // read the public key modulus 'n' byte[] buf = new byte[256]; int read = dis.read(buf); if (read == -1) { throw new IOException("Reached end of file before finished reading the file:" + crtFile); } BigInteger modulus = new BigInteger(1, buf); /*HexDumpEncoder hexDump = null; if (debug) { System.out.println("public modulus:"); hexDump = new HexDumpEncoder(); System.out.println(hexDump.encodeBuffer(modulus.toByteArray())); }*/ BigInteger exponent = BigInteger.valueOf(65537); RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); KeyFactory factory = KeyFactory.getInstance("RSA"); PublicKey publicKey = factory.generatePublic(spec); // create a self signed cert for importing into the keystore. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset(); Calendar calendar = Calendar.getInstance(); calendar.set(0000, 1, 1); Date validFrom = calendar.getTime(); calendar.clear(); calendar.set(9999, 1, 1); Date validTo = calendar.getTime(); cg.setNotBefore(validFrom); cg.setNotAfter(validTo); cg.setPublicKey(publicKey); cg.setSignatureAlgorithm("SHA1WITHRSA"); cg.setSubjectDN(new X509Name(dn)); cg.setIssuerDN(new X509Name(dn)); SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); BigInteger serNo = new BigInteger(32, prng); cg.setSerialNumber(serNo); this.cert = cg.generate(this.privateKey); // read the BDA signature; not currently used //int read = dis.read(buf); //if (read == -1) { // throw new IOException("Reached end of file before finished reading the file:" + // crtFile); //} dis.close(); }
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;/* ww w. j ava2 s . co 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(); X509Certificate rootCert = (X509Certificate) store.getCertificate(alias); if (rootCert == null) { System.out//from w w w.j ava 2s. c o m .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:org.jivesoftware.util.CertificateManager.java
License:Open Source License
/** * Creates an X509 version3 certificate. * * @param kp KeyPair that keeps the public and private keys for the new certificate. * @param months time to live//from w ww. ja v a2 s. com * @param issuerDN Issuer string e.g "O=Grid,OU=OGSA,CN=ACME" * @param subjectDN Subject string e.g "O=Grid,OU=OGSA,CN=John Doe" * @param domain Domain of the server. * @param signAlgoritm Signature algorithm. This can be either a name or an OID. * @return X509 V3 Certificate * @throws GeneralSecurityException * @throws IOException */ private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN, String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException { PublicKey pubKey = kp.getPublic(); PrivateKey privKey = kp.getPrivate(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger serial = (new java.math.BigInteger(serno)).abs(); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); certGenerator.setSerialNumber(serial); certGenerator.setIssuerDN(new X509Name(issuerDN)); certGenerator.setNotBefore(new Date(System.currentTimeMillis())); certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30))); certGenerator.setSubjectDN(new X509Name(subjectDN)); certGenerator.setPublicKey(pubKey); certGenerator.setSignatureAlgorithm(signAlgoritm); // Generate the subject alternative name boolean critical = subjectDN == null || "".equals(subjectDN.trim()); ASN1Sequence othernameSequence = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence); GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN }); // Add subject alternative name extension certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames); X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; }
From source file:org.silvertunnel.netlib.layer.tor.util.PrivateKeyHandler.java
License:Open Source License
public java.security.cert.X509Certificate[] getCertificateChain(String alias) { try {/* w ww .ja v a 2 s .com*/ org.bouncycastle.x509.X509V3CertificateGenerator generator = new org.bouncycastle.x509.X509V3CertificateGenerator(); generator.reset(); generator.setSerialNumber(BigInteger.valueOf(42)); generator.setNotBefore(new Date(System.currentTimeMillis() - 24L * 3600 * 1000)); generator.setNotAfter(new Date(System.currentTimeMillis() + 365L * 24 * 3600 * 1000)); generator.setIssuerDN(new org.bouncycastle.asn1.x509.X509Name("CN=" + Util.MYNAME)); generator.setSubjectDN(new org.bouncycastle.asn1.x509.X509Name("CN=" + Util.MYNAME)); generator.setPublicKey(keypair.getPublic()); generator.setSignatureAlgorithm("SHA1WITHRSA"); java.security.cert.X509Certificate x509 = generator.generate(keypair.getPrivate(), "BC"); java.security.cert.X509Certificate[] x509s = new java.security.cert.X509Certificate[2]; // send the same certificate twice works fine with the default implementation of tor! // myself: x509s[0] = x509; // a certificate for myself: x509s[1] = x509; return x509s; } catch (Exception e) { log.severe("Caught exception: " + e.getMessage()); } return null; }
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/* w w w . j av a2 s . com*/ * @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; }