List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest getCertificationRequestInfo
public CertificationRequestInfo getCertificationRequestInfo()
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();/*from w w w .ja v a 2 s . co m*/ X509Certificate rootCert = (X509Certificate) store.getCertificate(alias); if (rootCert == null) { System.out .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:net.jxta.impl.shell.bin.pse.signcsr.java
License:Open Source License
/** * {@inheritDoc}// ww w .j a va 2s .co m */ public int startApp(String[] argv) { ShellEnv env = getEnv(); String issuerEnvName; String duration; String csrEnvName; GetOpt options = new GetOpt(argv, 0, ""); while (true) { int option; try { option = options.getNextOption(); } catch (IllegalArgumentException badopt) { consoleMessage("Illegal argument :" + badopt); return syntaxError(); } if (-1 == option) { break; } switch (option) { default: consoleMessage("Unrecognized option"); return syntaxError(); } } issuerEnvName = options.getNextParameter(); if (null == issuerEnvName) { consoleMessage("Missing <issuer> parameter"); return syntaxError(); } duration = options.getNextParameter(); if (null == duration) { consoleMessage("Missing <duration> parameter"); return syntaxError(); } csrEnvName = options.getNextParameter(); if (null == csrEnvName) { consoleMessage("Missing <csr> parameter"); return syntaxError(); } if (null != options.getNextParameter()) { consoleMessage("Unsupported parameter"); return syntaxError(); } MembershipService membership = getGroup().getMembershipService(); if (!(membership instanceof PSEMembershipService)) { ModuleImplAdvertisement mia = (ModuleImplAdvertisement) membership.getImplAdvertisement(); consoleMessage("Group membership service is not PSE. (" + mia.getDescription() + ")"); return ShellApp.appMiscError; } PSEMembershipService pse = (PSEMembershipService) membership; if (null == pse.getDefaultCredential()) { consoleMessage("Key store has not been opened."); return ShellApp.appMiscError; } PSEUtils.IssuerInfo issuer; X509Certificate[] issuerChain; ShellObject issuerEnv = env.get(issuerEnvName); if (null == issuerEnv) { consoleMessage("Issuer environment variable '" + issuerEnvName + "' not found."); return ShellApp.appMiscError; } if (!PSECredential.class.isAssignableFrom(issuerEnv.getObjectClass())) { consoleMessage("'" + issuerEnvName + "' is not a is not a PSE credential."); return ShellApp.appMiscError; } PSECredential cred = (PSECredential) issuerEnv.getObject(); issuerChain = cred.getCertificateChain(); PrivateKey issuerKey = null; try { issuerKey = cred.getPrivateKey(); } catch (IllegalStateException notLocal) { //ignored } if (null == issuerKey) { consoleMessage("Credential is not a local login credential."); return ShellApp.appMiscError; } issuer = new PSEUtils.IssuerInfo(); issuer.cert = issuerChain[0]; issuer.subjectPkey = issuerKey; ShellObject csrEnv = env.get(csrEnvName); if (null == csrEnv) { consoleMessage("CSR environment variable not found."); return ShellApp.appMiscError; } if (!StructuredDocument.class.isAssignableFrom(csrEnv.getObjectClass())) { consoleMessage("'" + csrEnvName + "' is not a Certificate Signing Request."); return ShellApp.appMiscError; } net.jxta.impl.protocol.CertificateSigningRequest csr_msg = new net.jxta.impl.protocol.CertificateSigningRequest( (Element) csrEnv.getObject()); org.bouncycastle.jce.PKCS10CertificationRequest csr = csr_msg.getCSR(); // set validity 10 years from today Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.DATE, Integer.parseInt(duration)); Date until = cal.getTime(); // generate cert try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(new X509Principal(true, issuer.cert.getSubjectX500Principal().getName())); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(today); certGen.setNotAfter(until); certGen.setPublicKey(csr.getPublicKey()); //certGen.setSignatureAlgorithm("SHA1withDSA"); certGen.setSignatureAlgorithm("SHA1withRSA"); // FIXME bondolo 20040317 needs fixing. certGen.setSerialNumber(BigInteger.valueOf(1)); // return issuer info for generating service cert // the cert X509Certificate newCert = certGen.generateX509Certificate(issuer.subjectPkey); net.jxta.impl.protocol.Certificate cert_msg = new net.jxta.impl.protocol.Certificate(); List<X509Certificate> newChain = new ArrayList<X509Certificate>(Arrays.asList(issuerChain)); newChain.add(0, newCert); cert_msg.setCertificates(newChain); XMLDocument asXML = (XMLDocument) cert_msg.getDocument(MimeMediaType.XMLUTF8); ShellObject<XMLDocument> newObj = new ShellObject<XMLDocument>("Certificate", asXML); env.add(getReturnVariable(), newObj); } catch (Exception failed) { printStackTrace("Failed to generate certificate", failed); } return ShellApp.appNoError; }
From source file:net.link.util.common.KeyUtils.java
License:Open Source License
public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, PrivateKey issuerPrivateKey, X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, String inSignatureAlgorithm, boolean caCert, boolean timeStampingPurpose, URI ocspUri) throws InvalidKeyException, NoSuchAlgorithmException { try {//from w ww . jav a 2 s.c o m return generateCertificate(csr.getPublicKey(), csr.getCertificationRequestInfo().getSubject().toString(), issuerPrivateKey, issuerCert, notBefore, notAfter, inSignatureAlgorithm, caCert, timeStampingPurpose, ocspUri); } catch (NoSuchProviderException e) { throw new InternalInconsistencyException(e); } }
From source file:org.apache.cloudstack.ca.provider.RootCAProvider.java
License:Apache License
private Certificate generateCertificateUsingCsr(final String csr, final List<String> domainNames, final List<String> ipAddresses, final int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException, SignatureException, IOException, OperatorCreationException { PemObject pemObject = null;//from ww w . j ava2 s. co m try { final PemReader pemReader = new PemReader(new StringReader(csr)); pemObject = pemReader.readPemObject(); } catch (IOException e) { LOG.error("Failed to read provided CSR string as a PEM object", e); } if (pemObject == null) { throw new CloudRuntimeException("Unable to read/process CSR: " + csr); } final PKCS10CertificationRequest request = new PKCS10CertificationRequest(pemObject.getContent()); final String subject = request.getCertificationRequestInfo().getSubject().toString(); final X509Certificate clientCertificate = CertUtils.generateV3Certificate(caCertificate, caKeyPair, request.getPublicKey(), subject, CAManager.CertSignatureAlgorithm.value(), validityDays, domainNames, ipAddresses); return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate)); }
From source file:org.deviceconnect.android.ssl.CertificateAuthority.java
License:MIT License
/** * ???? Subject Alternative Names (SANs) ??. * * @param request ???// w w w.ja v a 2s.c o m * @return SubjectAlternativeNames? {@link GeneralNames} * @throws IOException ????? */ private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException { List<ASN1Encodable> generalNames = new ArrayList<>(); CertificationRequestInfo info = request.getCertificationRequestInfo(); ASN1Set attributes = info.getAttributes(); for (int i = 0; i < attributes.size(); i++) { DEREncodable extensionRequestObj = attributes.getObjectAt(i); if (!(extensionRequestObj instanceof DERSequence)) { continue; } DERSequence extensionRequest = (DERSequence) extensionRequestObj; if (extensionRequest.size() != 2) { continue; } DEREncodable idObj = extensionRequest.getObjectAt(0); DEREncodable contentObj = extensionRequest.getObjectAt(1); if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) { continue; } ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj; DERSet content = (DERSet) contentObj; if (!id.getId().equals("1.2.840.113549.1.9.14")) { continue; } if (content.size() < 1) { continue; } DEREncodable extensionsObj = content.getObjectAt(0); if (!(extensionsObj instanceof DERSequence)) { continue; } DERSequence extensions = (DERSequence) extensionsObj; for (int k = 0; k < extensions.size(); k++) { DEREncodable extensionObj = extensions.getObjectAt(k); if (!(extensionObj instanceof DERSequence)) { continue; } DERSequence extension = (DERSequence) extensionObj; if (extension.size() != 2) { continue; } DEREncodable extensionIdObj = extension.getObjectAt(0); DEREncodable extensionContentObj = extension.getObjectAt(1); if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) { continue; } ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj; if (extensionId.getId().equals("2.5.29.17")) { DEROctetString san = (DEROctetString) extensionContentObj; ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream()); DEREncodable namesObj = sanParser.readObject().getDERObject(); if (namesObj instanceof DERSequence) { DERSequence names = (DERSequence) namesObj; for (int m = 0; m < names.size(); m++) { DEREncodable nameObj = names.getObjectAt(m); if (nameObj instanceof DERTaggedObject) { DERTaggedObject name = (DERTaggedObject) nameObj; switch (name.getTagNo()) { case GeneralName.dNSName: generalNames.add(new GeneralName(GeneralName.dNSName, DERIA5String.getInstance(name, false))); break; case GeneralName.iPAddress: generalNames.add(new GeneralName(GeneralName.iPAddress, DEROctetString.getInstance(name, true))); break; } } } } } } } if (generalNames.size() > 0) { return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[generalNames.size()]))); } return null; }
From source file:org.ejbca.util.CertToolsTest.java
License:Open Source License
@SuppressWarnings("unchecked") public void test19getAltNameStringFromExtension() throws Exception { PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(p10ReqWithAltNames); CertificationRequestInfo info = p10.getCertificationRequestInfo(); ASN1Set set = info.getAttributes(); // The set of attributes contains a sequence of with type oid // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest Enumeration<Object> en = set.getObjects(); boolean found = false; while (en.hasMoreElements()) { ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement()); DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0); if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // The object at position 1 is a SET of x509extensions DERSet s = (DERSet) seq.getObjectAt(1); X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0)); X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName); if (ext != null) { found = true;//from w ww. j a va 2 s .c o m String altNames = CertTools.getAltNameStringFromExtension(ext); assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames); } } } assertTrue(found); p10 = new PKCS10CertificationRequest(p10ReqWithAltNames2); info = p10.getCertificationRequestInfo(); set = info.getAttributes(); // The set of attributes contains a sequence of with type oid // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest en = set.getObjects(); found = false; while (en.hasMoreElements()) { ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement()); DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0); if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // The object at position 1 is a SET of x509extensions DERSet s = (DERSet) seq.getObjectAt(1); X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0)); X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName); if (ext != null) { found = true; String altNames = CertTools.getAltNameStringFromExtension(ext); assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames); } } } assertTrue(found); }
From source file:org.glite.security.util.proxy.ProxyCertificateGenerator.java
License:Apache License
/** * Create a new proxy cert generator based on certification request and a certificate chain. Used for example when * creating a proxy certificate on the client side from certificate request coming from a service. * /*from ww w . j a va2 s . c o m*/ * @param parentCertChain The parent cert chain of the proxy. * @param certReq The certification request to generate the certificate from. * @throws InvalidKeyException Thrown if the public key in the request is invalid. * @throws NoSuchAlgorithmException Thrown if the request uses unsupported algorithm. * @throws NoSuchProviderException Thrown if the bouncycastle provider was not found. */ public ProxyCertificateGenerator(X509Certificate[] parentCertChain, PKCS10CertificationRequest certReq) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { this(parentCertChain); // m_certReq = certReq; m_publicKey = certReq.getPublicKey(); m_newDN = certReq.getCertificationRequestInfo().getSubject(); /* * // test for DN violation, the new DN must be composed of the parentDN // and and additional CN component. DN * baseDN = DNHandler.getSubject(m_parentCert); DN reqSubject = DNHandler.getDN(m_newDN); try{ * ProxyCertUtil.checkProxyDN(baseDN, reqSubject); } catch(IllegalArgumentException e){ throw new * IllegalArgumentException("Got an invalid proxy request subject, '" + reqSubject + * "' is not a valid proxy subject for '" + baseDN + "', error was: " + e.getMessage()); } */ // in case the parent was unknown type, deduce the type from the cert // req. in case it's not legacy and not set later, use default in generate(). if (m_type == ProxyCertificateInfo.UNKNOWN_PROXY_TYPE) { if (ProxyCertificateInfo.isLegacyDN(m_newDN)) { m_type = ProxyCertificateInfo.LEGACY_PROXY; } } // if the proxy is not legacy proxy, try to figure out the serial number from the DN of the request. if (m_type != ProxyCertificateInfo.LEGACY_PROXY) { BigInteger sn = ProxyCertUtil.getSN(m_newDN); if (sn != null) { m_serialNumber = sn; } } m_certGen = new X509V3CertificateGenerator(); }
From source file:org.glite.slcs.caclient.impl.CMPRequest.java
License:eu-egee.org license
private static CertTemplate makeCertTemplate(CertificateRequest certRequest, String issuerDN) { PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(certRequest.getDEREncoded()); CertificationRequestInfo pkcs10info = pkcs10.getCertificationRequestInfo(); log.debug("Constructing CMP CertTemplate..."); CertTemplate certTemplate = new CertTemplate(); certTemplate.setPublicKey(pkcs10info.getSubjectPublicKeyInfo()); certTemplate.setSubject(pkcs10info.getSubject()); certTemplate.setIssuer(new X509Name(issuerDN)); // validity//from w w w .j a va2 s . com OptionalValidity validity = new OptionalValidity(); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // five minutes extra to before/after date.add(Calendar.MINUTE, -5); Time notBefore = new Time(date.getTime()); date.add(Calendar.MINUTE, 5); // TODO: lifetime fixed to 1 mio seconds, should be possible to configure by user date.add(Calendar.SECOND, 1000000); Time notAfter = new Time(date.getTime()); validity.setNotBefore(notBefore); validity.setNotAfter(notAfter); certTemplate.setValidity(validity); log.debug("Constructed " + certTemplate.toString()); return certTemplate; }
From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java
License:Mozilla Public License
/** * Handles the nitty gritty of signing a CSR * * @param rootCert The certificate of the root authority who will vouch for the entity * @param rootPrivKey The private key of the root authority who will vouch for the entity * @param csr The entitie's CSR/*from w ww. j a v a2s . c om*/ * @param keyType The type of the key, e.g. "RSA", "DSA" * @return A certificate chain as an array of X509Certificate instances or null if an * error occurred */ private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey, PKCS10CertificationRequest csr, String keyType) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); try { Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(validFrom); certGen.setNotAfter(validTo); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(csr.getPublicKey("BC")); if (keyType.toLowerCase().equals("rsa")) certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); if (keyType.toLowerCase().equals("dsa")) certGen.setSignatureAlgorithm("DSAWithSHA1"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.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_clientAuth)); X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC"); return new X509Certificate[] { issuedCert, rootCert }; } catch (Exception e) { logger.error(e); return null; } }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException { X509Certificate cert;//from w ww.j av a2s . c o m try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal()); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(getCertStartDate()); certGen.setNotAfter(getCertEndDate()); certGen.setPublicKey(csr.getPublicKey("BC")); certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(getRootCertificate())); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); @SuppressWarnings("rawtypes") 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()); } } } KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(), rootService.getRootCertificateAlias(), rootService.getRootKeyPassword()); cert = certGen.generate(rootKeyPair.getPrivate(), "BC"); } catch (CertificateParsingException e) { throw new CertException(e); } catch (CertificateEncodingException e) { throw new CertException(e); } catch (InvalidKeyException e) { throw new CertException(e); } catch (IllegalStateException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } LOG.debug("Certificate generated for subject: " + cert.getSubjectDN()); return cert; }