List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest getCertificationRequestInfo
public CertificationRequestInfo getCertificationRequestInfo()
From source file:chapter6.PKCS10CertCreateExample.java
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") == false) { System.out.println("Request failed to verify!!"); System.exit(1);/* w w w . ja v a2 s . com*/ } // 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(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); 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:com.ah.be.cloudauth.HmCloudAuthCertMgmtImpl.java
@SuppressWarnings("rawtypes") private void verifyCSRContent(BeRadSecCertCreationResultEvent result, String commonName) throws HmCloudAuthException { String methodName = "verifyCSRContent"; if (result.isCreateError()) { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_CREATE_ERR); }/* w w w . j a v a2 s. c o m*/ if (result.isNeedCreate()) { byte[] csrContent = result.getCsrContent(); final List pemItems = org.apache.commons.ssl.PEMUtil.decode(csrContent); if (pemItems.isEmpty()) { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR); } final PEMItem csrPemItem = (PEMItem) pemItems.get(0); if (csrPemItem.pemType.startsWith(CERTIFICATE_REQUEST)) { final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrPemItem.getDerBytes()); CertificationRequestInfo requestInfo = csr.getCertificationRequestInfo(); X509Name subject = requestInfo.getSubject(); Vector commondNameVector = subject.getValues(X509Name.CN); Vector countryVector = subject.getValues(X509Name.C); Vector organizationVector = subject.getValues(X509Name.O); if (commondNameVector.isEmpty() || countryVector.isEmpty() || organizationVector.isEmpty()) { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_FORMAT_ERR); } if (!commonName.equalsIgnoreCase(commondNameVector.get(0).toString()) || !ORGANIZATION.equals(organizationVector.get(0).toString()) || !COUNTRY.equals(countryVector.get(0).toString())) { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_VERIFY_ERR); } } else { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR); } } else { throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_STATUS_ERR); } return; }
From source file:edu.washington.iam.tools.IamCertificateHelper.java
License:Apache License
public static int parseCsr(IamCertificate cert) throws IamCertificateException { try {/*ww w .j a va 2 s.co m*/ PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest)); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); if (request == null) throw new IamCertificateException("invalid CSR (request)"); CertificationRequestInfo info = request.getCertificationRequestInfo(); if (info == null) throw new IamCertificateException("invalid CSR (info)"); X509Name dn = info.getSubject(); if (dn == null) throw new IamCertificateException("invalid CSR (dn)"); log.debug("dn=" + dn.toString()); cert.dn = dn.toString(); try { List cns = dn.getValues(X509Name.CN); cert.cn = (String) (cns.get(0)); log.debug("cn=" + cert.cn); cert.names.add(cert.cn); // first entry for names is always cn cns = dn.getValues(X509Name.C); cert.dnC = (String) (cns.get(0)); cns = dn.getValues(X509Name.ST); cert.dnST = (String) (cns.get(0)); } catch (Exception e) { log.debug("get cn error: " + e); throw new IamCertificateException("invalid CSR"); } // see if we've got alt names (in extensions) ASN1Set attrs = info.getAttributes(); if (attrs != null) { for (int a = 0; a < attrs.size(); a++) { Attribute attr = Attribute.getInstance(attrs.getObjectAt(a)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // is the extension X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); // get the subAltName extension DERObjectIdentifier sanoid = new DERObjectIdentifier( X509Extensions.SubjectAlternativeName.getId()); X509Extension xext = extensions.getExtension(sanoid); if (xext != null) { log.debug("processing altname extensions"); ASN1Object asn1 = X509Extension.convertValueToObject(xext); Enumeration dit = DERSequence.getInstance(asn1).getObjects(); while (dit.hasMoreElements()) { GeneralName gn = GeneralName.getInstance(dit.nextElement()); log.debug("altname tag=" + gn.getTagNo()); log.debug("altname name=" + gn.getName().toString()); if (gn.getTagNo() == GeneralName.dNSName) cert.names.add(gn.getName().toString()); } } } } } // check key size PublicKey pk = request.getPublicKey(); log.debug("key alg = " + pk.getAlgorithm()); log.debug("key fmt = " + pk.getFormat()); if (pk.getAlgorithm().equals("RSA")) { RSAPublicKey rpk = (RSAPublicKey) pk; cert.keySize = rpk.getModulus().bitLength(); log.debug("key size = " + cert.keySize); } } catch (IOException e) { log.debug("ioerror: " + e); throw new IamCertificateException("invalid CSR " + e.getMessage()); } catch (Exception e) { log.debug("excp: " + e); throw new IamCertificateException("invalid CSR"); } return 1; }
From source file:eu.optimis.ics.Credentials.CertificateGenerator.java
License:Open Source License
public static X509CertificateHolder genServerCertificate(PKCS10CertificationRequest certRequest, String credPath) {// w w w. j a v a 2 s. c o m X509v3CertificateBuilder v3CertBuilder = null; ContentSigner sigGen = null; try { PEMReader r = new PEMReader(new FileReader(credPath + "ca.crt")); X509Certificate rootCert = (X509Certificate) r.readObject(); r.close(); BigInteger serial = BigInteger.ONE; Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo .getInstance(certRequest.getPublicKey().getEncoded()); X500Name issuer = new X500Name(rootCert.getSubjectDN().toString()); System.out.println(issuer.toString()); @SuppressWarnings("deprecation") X500Name subject = new X500Name(certRequest.getCertificationRequestInfo().getSubject().toString()); v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo); v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(publicKeyInfo)); v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); v3CertBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); v3CertBuilder.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(loadCAPrivateKey(credPath)); } catch (IOException ioe) { ioe.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (OperatorCreationException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (CertificateParsingException e) { e.printStackTrace(); } return v3CertBuilder.build(sigGen); }
From source file:eu.optimis.ics.Credentials.CertificateGenerator.java
License:Open Source License
public static X509CertificateHolder genClientCertificate(PKCS10CertificationRequest certRequest, String credPath) throws Exception { PEMReader r = new PEMReader(new FileReader(credPath + "ca.crt")); X509Certificate rootCert = (X509Certificate) r.readObject(); r.close();/*from w ww . ja va2 s . c om*/ BigInteger serial = BigInteger.valueOf(2).abs(); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo .getInstance(certRequest.getPublicKey().getEncoded()); X500Name issuer = new X500Name(rootCert.getSubjectDN().toString()); @SuppressWarnings("deprecation") X500Name subject = new X500Name(certRequest.getCertificationRequestInfo().getSubject().toString()); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo); v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(publicKeyInfo)); v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); v3CertBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); v3CertBuilder.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature)); ContentSigner sigGen = null; try { sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(loadCAPrivateKey(credPath)); } catch (OperatorCreationException e) { e.printStackTrace(); } return v3CertBuilder.build(sigGen); }
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 w w. j av a 2 s . co 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.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 . j a v a2 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:me.it_result.ca.bouncycastle.BouncyCA.java
License:Open Source License
@Override public synchronized X509Certificate signCertificate(byte[] csrBytes) throws CAException { ensureInitialized();//from www . j av a 2 s .c o m try { PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrBytes); if (!csr.verify()) throw new CAException("CSR verification failed!"); X509Name sn = csr.getCertificationRequestInfo().getSubject(); PublicKey publicKey = csr.getPublicKey(); KeyStore keyStore = loadKeystore(); PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(CA_ALIAS, keystorePassword.toCharArray()); PublicKey caPublicKey = keyStore.getCertificate(CA_ALIAS).getPublicKey(); BigInteger serialNumber = nextSerialNumber(); assembleCertificate(publicKey, caPublicKey, sn.toString(), issuer, serialNumber, false, validityDays); ASN1Set csrAttributes = csr.getCertificationRequestInfo().getAttributes(); Profile profile = selectProfile(csrAttributes); profile.generateCertificateExtensions(csrAttributes, certGen); X509Certificate cert = certGen.generate(caPrivateKey); String alias = Utils.generateAlias(sn); keyStore.setCertificateEntry(alias, cert); saveKeystore(keyStore); incrementSerialNumber(serialNumber); return cert; } catch (Exception e) { throw new CAException(e); } finally { certGen.reset(); } }
From source file:me.it_result.ca.bouncycastle.BouncyCAClientTest.java
License:Open Source License
@Test public void testGenerateCSR() throws CertificateException, Exception { // Given CSR was never generated for 'CN=test,UID=test@test' subject name assertNull(client.getKeypair(SUBJECT_NAME)); // When generateCSR('CN=test,UID=test@test') is invoked Date minBeforeDate = new Date(); byte[] csr = client.generateCSR(CERT_PARAMS); Date maxBeforeDate = new Date(); // Then CSR is generated for the subject name PKCS10CertificationRequest parsedCsr = new PKCS10CertificationRequest(csr); assertEquals(new X509Principal(SUBJECT_NAME), parsedCsr.getCertificationRequestInfo().getSubject()); // And a newly generated keypair is generated assertNotNull(client.getKeypair(SUBJECT_NAME)); // And a self-signed certificate is generated X509Certificate selfSignedCert = client.getCertificate(SUBJECT_NAME); assertNotNull(selfSignedCert);//www .j a va 2 s. c o m new X509Assertions(selfSignedCert).caCertificate(false).issuedBy(selfSignedCert) .serialNumber(new BigInteger("1")).signatureAlgrithm(jdkSignatureAlgorithm) .subjectName(SUBJECT_NAME).type("X.509").version(3) .validDuring(VALIDITY_DAYS, minBeforeDate, maxBeforeDate) .keyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment).containsAKI().containsSKI() .noMoreExtensions(); }
From source file:me.it_result.ca.CAClientTest.java
License:Open Source License
private void assertDuplicateCsrInvocation(byte[] csr, KeyPair keypair, X509Certificate certificate) throws Exception { // When generateCSR('CN=test,UID=test@test') is invoked byte[] newCsr = client().generateCSR(CERT_PARAMS); // Then a new CSR is generated for the subject name using the keypair generated earlier PKCS10CertificationRequest parsedCsr = new PKCS10CertificationRequest(csr); PKCS10CertificationRequest newParsedCsr = new PKCS10CertificationRequest(newCsr); assertEquals(parsedCsr.getCertificationRequestInfo().getSubject(), newParsedCsr.getCertificationRequestInfo().getSubject()); assertEquals(keypair.getPublic(), parsedCsr.getPublicKey()); // And keypair is not modified KeyPair newKeypair = client().getKeypair(SUBJECT_NAME); assertEquals(keypair.getPrivate(), newKeypair.getPrivate()); assertEquals(keypair.getPublic(), newKeypair.getPublic()); // And a self-signed certificate is not modified X509Certificate newCertificate = client().getCertificate(SUBJECT_NAME); assertEquals(certificate, newCertificate); }