List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator addExtension
public void addExtension(ASN1ObjectIdentifier oid, boolean critical, byte[] value)
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. jav a 2 s . c o m * @param keypair the keypair * @param months the validity length in months * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param domain domain of the server to store in the subject alternative name extension * @param signAlgorithm the signing algorithm to use * @return the generated X509 certificate */ public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN, String domain, String signAlgorithm) { try { // calendar for date calculations GregorianCalendar cal = new GregorianCalendar(); // extract keypair components PublicKey pubKey = keypair.getPublic(); PrivateKey privKey = keypair.getPrivate(); // generate a random serial number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); byte[] serialNo = new byte[8]; random.nextBytes(serialNo); BigInteger serial = new BigInteger(serialNo).abs(); // create the certificate generator X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.reset(); // set certificate attributes certGen.setSerialNumber(serial); cal.setTimeInMillis(System.currentTimeMillis()); certGen.setNotBefore(cal.getTime()); cal.add(GregorianCalendar.MONTH, months); certGen.setNotAfter(cal.getTime()); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(signAlgorithm); certGen.setIssuerDN(new X509Name(issuerDN)); certGen.setSubjectDN(new X509Name(subjectDN)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // create subject alternative name boolean isCritical = subjectDN == null || "".equals(subjectDN.trim()); DERSequence othernameSeq = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq); GeneralNames subjectAlternatives = new GeneralNames(othernameGen); certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives); // finally generate the certificate X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(), new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; } catch (NoSuchAlgorithmException ex) { throw new KeystoreFault(ex); } catch (CertificateException ex) { throw new KeystoreFault(ex); } catch (SignatureException ex) { throw new KeystoreFault(ex); } catch (NoSuchProviderException ex) { throw new KeystoreFault(ex); } catch (InvalidKeyException ex) { throw new KeystoreFault(ex); } }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);//w ww .j ava2 s.c o m } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); 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)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:io.aos.crypto.spl06.X509V3CreateExample.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an intermediate CA certificate *//* w w w .j a v a2s. c om*/ public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an end entity certificate *//*from www . j a v a 2 s.c om*/ public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl08.CertReqSolution.java
License:Apache License
public static void main(String... args) throws Exception { // create the CA certificates X500PrivateCredential rootCredential = Utils.createRootCredential(); X500PrivateCredential interCredential = Utils.createIntermediateCredential(rootCredential.getPrivateKey(), rootCredential.getCertificate()); // parse the request PEMReader pRd = new PEMReader(new InputStreamReader(new FileInputStream("pkcs10.req"))); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); // get our validation certificate X509Certificate caCert = interCredential.getCertificate(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // provide some basic extensions and mark the certificate as appropriate for signing and encipherment certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); // create the chain List chain = Arrays/*from w ww . java 2 s . c o m*/ .asList(new Certificate[] { certGen.generateX509Certificate(interCredential.getPrivateKey(), "BC"), interCredential.getCertificate(), rootCredential.getCertificate() }); // create the CertPath CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath path = fact.generateCertPath(chain); // write it out FileOutputStream fOut = new FileOutputStream("pkcs7.pth"); fOut.write(path.getEncoded("PKCS7")); fOut.close(); }
From source file:krypto.KryptoService.java
License:Apache License
/** * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist. * @return/* ww w. j a va2 s. c om*/ * @throws Exception */ public static X509Certificate generateCertificate(String algorithm) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); KeyPair pair = null; try { pair = generateKeyPair(algorithm, 1024); } catch (Exception e) { try { pair = generateKeyPair(algorithm, 512); } catch (Exception e2) { System.out.println(e2.getMessage()); } } long day = 24 * 60 * 60 * 1000; // 1 Tag gltig certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + day)); certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate cert = null; try { cert = certGen.generate(pair.getPrivate(), "BC"); } catch (CertificateEncodingException e) { System.out.println("CertificateEncodingException"); } catch (InvalidKeyException e2) { System.out.println("InvalidKeyException: " + e2.getMessage()); } catch (Exception e3) { // do nothing } return cert; }
From source file:lt.bsprendimai.ddesk.servlets.CertGenerator.java
License:Apache License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request/*from ww 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:me.it_result.ca.bouncycastle.StandardProfile.java
License:Open Source License
@Override public void generateCertificateExtensions(ASN1Set csrAttributes, X509V3CertificateGenerator certificateGenerator) { // EKU/*w w w. j av a 2s. c o m*/ ExtendedKeyUsage extendedKeyUsage; if (isServerProfile(csrAttributes)) extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth); else extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth); certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsage); }
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert) throws Exception { Date validFrom, validTo;//from www .ja v a2 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(); }