List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest PKCS10CertificationRequest
public PKCS10CertificationRequest(byte[] encoded) throws IOException
From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java
License:Open Source License
@Test public void testDNOverride() throws Exception { // Create a good certificate profile (good enough), using QC statement certificateProfileSession.removeCertificateProfile(internalAdmin, "TESTDNOVERRIDE"); final CertificateProfile certprof = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Default profile does not allow DN override certprof.setValidity(298);//from www . java 2s . com certificateProfileSession.addCertificateProfile(internalAdmin, "TESTDNOVERRIDE", certprof); int cprofile = certificateProfileSession.getCertificateProfileId("TESTDNOVERRIDE"); // Create a good end entity profile (good enough), allowing multiple UPN // names endEntityProfileSession.removeEndEntityProfile(internalAdmin, "TESTDNOVERRIDE"); EndEntityProfile profile = new EndEntityProfile(); profile.addField(DnComponents.COUNTRY); profile.addField(DnComponents.COMMONNAME); profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS)); profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile)); endEntityProfileSession.addEndEntityProfile(internalAdmin, "TESTDNOVERRIDE", profile); int eeprofile = endEntityProfileSession.getEndEntityProfileId("TESTDNOVERRIDE"); int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId(); final String dnOverrideEndEntityName = "DnOverride"; createEndEntity(dnOverrideEndEntityName, eeprofile, cprofile, rsacaid); try { EndEntityInformation user = new EndEntityInformation(dnOverrideEndEntityName, "C=SE,CN=dnoverride", rsacaid, null, "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); user.setStatus(EndEntityConstants.STATUS_NEW); // Change a user that we know... endEntityManagementSession.changeUser(internalAdmin, user, false); // Create a P10 with strange order DN PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", new X500Name("CN=foo,C=SE,NAME=AnaTom,O=My org"), rsakeys.getPublic(), new DERSet(), rsakeys.getPrivate(), null); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(req.toASN1Structure()); dOut.close(); PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray()); ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic()); boolean verify = req2.isSignatureValid(verifier); log.debug("Verify returned " + verify); assertTrue(verify); log.debug("CertificationRequest generated successfully."); byte[] bcp10 = bOut.toByteArray(); PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10); p10.setUsername(dnOverrideEndEntityName); p10.setPassword("foo123"); ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null); X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage()); assertNotNull("Failed to create certificate", cert); assertEquals("CN=dnoverride,C=SE", cert.getSubjectDN().getName()); // Change so that we allow override of validity time CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile); prof.setAllowDNOverride(true); certificateProfileSession.changeCertificateProfile(internalAdmin, "TESTDNOVERRIDE", prof); endEntityManagementSession.changeUser(internalAdmin, user, false); resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null); cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage()); assertNotNull("Failed to create certificate", cert); assertEquals("CN=foo,C=SE,Name=AnaTom,O=My org", cert.getSubjectDN().getName()); } finally { endEntityManagementSession.deleteUser(internalAdmin, dnOverrideEndEntityName); } }
From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java
License:Open Source License
@Test public void testBCPKCS10DSAWithRSACA() throws Exception { log.trace(">test24TestBCPKCS10DSAWithRSACA()"); endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW); log.debug("Reset status of 'foo' to NEW"); // Create certificate request KeyPair dsakeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_DSA); PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithDSA", CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), dsakeys.getPublic(), new DERSet(), dsakeys.getPrivate(), null); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(req.toASN1Structure()); dOut.close();/*from w w w . j a va 2s . c om*/ PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray()); ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(dsakeys.getPublic()); boolean verify = req2.isSignatureValid(verifier); log.debug("Verify returned " + verify); assertTrue(verify); log.debug("CertificationRequest generated successfully."); byte[] bcp10 = bOut.toByteArray(); PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10); p10.setUsername(RSA_USERNAME); p10.setPassword("foo123"); ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null); Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage()); assertNotNull("Failed to create certificate", cert); log.debug("Cert=" + cert.toString()); PublicKey pk = cert.getPublicKey(); if (pk instanceof DSAPublicKey) { DSAPublicKey dsapk = (DSAPublicKey) pk; assertEquals(dsapk.getAlgorithm(), "DSA"); } else { fail("Public key is not DSA"); } try { X509Certificate rsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, getTestCAName()) .getCertificateChain().toArray()[0]; cert.verify(rsacacert.getPublicKey()); } catch (Exception e) { fail("Verify failed: " + e.getMessage()); } log.trace("<test24TestBCPKCS10DSAWithRSACA()"); }
From source file:org.ejbca.ui.cli.ca.BaseCaAdminCommand.java
License:Open Source License
protected void makeCertRequest(String dn, KeyPair rsaKeys, String reqfile) throws NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException, PKCSException { log.trace(">makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'."); PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name(dn), rsaKeys.getPublic(), new DERSet(), rsaKeys.getPrivate(), null); /*//from ww w. j av a 2 s . com * We don't use these unnecessary attributes DERConstructedSequence kName * = new DERConstructedSequence(); DERConstructedSet kSeq = new * DERConstructedSet(); * kName.addObject(PKCSObjectIdentifiers.pkcs_9_at_emailAddress); * kSeq.addObject(new DERIA5String("foo@bar.se")); * kName.addObject(kSeq); req.setAttributes(kName); */ ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(req.toASN1Structure()); dOut.close(); PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray()); ContentVerifierProvider contentVerifier = CertTools.genContentVerifierProvider(rsaKeys.getPublic()); boolean verify = req2.isSignatureValid(contentVerifier); //req2.verify(); log.info("Verify returned " + verify); if (verify == false) { log.info("Aborting!"); return; } FileOutputStream os1 = new FileOutputStream(reqfile); os1.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes()); os1.write(Base64.encode(bOut.toByteArray())); os1.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes()); os1.close(); log.info("CertificationRequest '" + reqfile + "' generated successfully."); log.trace("<makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'."); }
From source file:org.ejbca.ui.web.pub.inspect.CertAndRequestDumpBean.java
License:Open Source License
/** Dumps contents, and updates "type" variable as side-effect. * /*from w w w.j a va2s. c o m*/ * @return String containing raw text output or null of input is null, or error message if input invalid. */ public String getDump() { String ret = null; if (bytes == null) { return null; } final byte[] requestBytes = RequestMessageUtils.getDecodedBytes(bytes); ret = getCvcDump(false); if ((ret == null) && (requestBytes != null) && (requestBytes.length > 0)) { // Not a CVC request, perhaps a PKCS10 request try { final PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(requestBytes); // ret = pkcs10.toString(); final ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(pkcs10.getEncoded())); final ASN1Primitive obj = ais.readObject(); ais.close(); ret = ASN1Dump.dumpAsString(obj); type = "PKCS#10"; } catch (IOException e1) { // ignore, move on to certificate decoding } catch (IllegalArgumentException e1) { // ignore, move on to certificate decoding } catch (ClassCastException e2) { // ignore, move on to certificate decoding } } else if (ret != null) { type = "CVC"; } if (ret == null) { // Not a CVC object or PKCS10 request message, perhaps a X.509 certificate? try { final Certificate cert = getCert(bytes); ret = CertTools.dumpCertificateAsString(cert); type = "X.509"; } catch (Exception e) { // Not a X.509 certificate either...try to simply decode asn.1 try { final ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(bytes)); final ASN1Primitive obj = ais.readObject(); ais.close(); if (obj != null) { ret = ASN1Dump.dumpAsString(obj); type = "ASN.1"; } } catch (IOException e1) { // Last stop, say what the error is ret = e1.getMessage(); } } } return ret; }
From source file:org.iotivity.cloud.accountserver.x509.cert.CSRParser.java
License:Open Source License
/** * Creates CSRParser instance with specified csrDer byte array. * * @param csrDer specified byte array./* w ww.ja va 2 s.c om*/ */ public CSRParser(byte[] csrDer) throws IOException { mCsr = new PKCS10CertificationRequest(csrDer); subject = mCsr.getSubject(); }
From source file:org.jruby.ext.openssl.impl.PKCS10Request.java
License:LGPL
public PKCS10Request(CertificationRequest req) { subject = req.getCertificationRequestInfo().getSubject(); publicKeyInfo = req.getCertificationRequestInfo().getSubjectPublicKeyInfo(); signedRequest = new PKCS10CertificationRequest(req); valid = true;//from ww w .j a v a 2 s .com }
From source file:org.opendaylight.snbi.southplugin.CertificateMgmt.java
License:Open Source License
public static X509Certificate signCSR(CertificationRequest inputCSR, PrivateKey caPrivate, KeyPair pair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, IOException, OperatorCreationException, CertException { PKCS10CertificationRequest pk10Holder = new PKCS10CertificationRequest(inputCSR); X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); // builder.addRDN(BCStyle.C, defaults.get("COUNTRY")); // builder.addRDN(BCStyle.O, defaults.get("ORGANIZATION")); //builder.addRDN(BCStyle.ST, defaults.get("STATE")); // builder.addRDN(BCStyle.T, defaults.get("TITLE")); builder.addRDN(BCStyle.CN, inputCSR.getSignature()); Calendar now = Calendar.getInstance(); Date notBefore = now.getTime(); now.add(Calendar.YEAR, 3);/*from www .ja v a 2 s . co m*/ Date notAfter = now.getTime(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder( CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString()).setProvider(CertManagerConstants.BC) .build(pair.getPrivate()); X509CertificateHolder holder = certGen.build(sigGen); Certificate eeX509CertificateStructure = holder.toASN1Structure(); CertificateFactory cf = null; try { cf = CertificateFactory.getInstance(CertManagerConstants.CERT_TYPE.X509.toString(), CertManagerConstants.BC); } catch (CertificateException e) { e.printStackTrace(); } // Read Certificate InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded()); X509Certificate theCert = null; try { theCert = (X509Certificate) cf.generateCertificate(is1); } catch (CertificateException e) { e.printStackTrace(); } is1.close(); return theCert; }
From source file:org.opendaylight.snbi.southplugin.SnbiPkt.java
License:Open Source License
public PKCS10CertificationRequest getPKCS10CSRTLV() { short protocolValue = this.protocolType.getValue(); if (protocolValue != SnbiProtocolType.SNBI_PROTOCOL_BOOTSTRAP.getValue()) { log.error("Cannot get pkc10 req for protocol type " + this.protocolType); return null; }//from w w w . j a v a 2 s . c om TLV tlv = getTLV(SnbiBsTlvType.SNBI_BS_TLV_TYPE_CERT_REQ.getValue()); try { PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(tlv.getValue()); return pkcs10; } catch (IOException e) { log.error("Failed to obtain PKCS10 from packet"); e.printStackTrace(); return null; } }
From source file:org.signserver.server.cryptotokens.CryptoTokenTestBase.java
License:Open Source License
protected void importCertificateChainHelper(final String existingKey) throws NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException, IOException, CertificateException, CryptoTokenOfflineException, IllegalArgumentException, CertificateEncodingException, OperationUnsupportedException, InvalidWorkerIdException, SignServerException { final String additionalAlias = "additionalKey"; try {//from w ww .j ava2 s . co m final ISignerCertReqInfo req = new PKCS10CertReqInfo("SHA1WithRSA", "CN=imported", null); Base64SignerCertReqData reqData = (Base64SignerCertReqData) genCertificateRequest(req, false, existingKey); // Issue certificate PKCS10CertificationRequest csr = new PKCS10CertificationRequest( Base64.decode(reqData.getBase64CertReq())); KeyPair issuerKeyPair = CryptoUtils.generateRSA(512); final X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=Test Issuer"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(), csr.getSubjectPublicKeyInfo()) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); // import certficate chain importCertificateChain(Arrays.asList(CertTools.getCertfromByteArray(cert.getEncoded())), existingKey); List<Certificate> chain = getCertificateChain(existingKey); assertEquals("Number of certs", 1, chain.size()); Certificate foundCert = chain.get(0); assertTrue("Imported cert", Arrays.equals(foundCert.getEncoded(), cert.getEncoded())); generateKey("RSA", "1024", additionalAlias); // Isse additional certificate reqData = (Base64SignerCertReqData) genCertificateRequest(req, false, additionalAlias); csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq())); issuerKeyPair = CryptoUtils.generateRSA(512); final X509CertificateHolder newCert = new X509v3CertificateBuilder(new X500Name("CN=Test Issuer2"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(), csr.getSubjectPublicKeyInfo()) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); // import certficate chain importCertificateChain(Arrays.asList(CertTools.getCertfromByteArray(newCert.getEncoded())), additionalAlias); // check that previously imported cert chain is un-affected chain = getCertificateChain(existingKey); assertEquals("Number of certs", 1, chain.size()); foundCert = chain.get(0); assertTrue("Imported cert", Arrays.equals(foundCert.getEncoded(), cert.getEncoded())); // Test that it is not allowed to import a certificate for // an other key try { final List<Certificate> chainForExistingKey = chain; final String aliasForAnOtherKey = additionalAlias; importCertificateChain(chainForExistingKey, aliasForAnOtherKey); fail("Should have thrown exception about the key not matching"); } catch (CryptoTokenOfflineException expected) { assertTrue("ex: " + expected.getMessage(), expected.getMessage().contains("does not match")); } } finally { try { destroyKey(additionalAlias); } catch (KeyStoreException ex) { LOG.error("Failed to remove additional key"); } } }
From source file:org.signserver.server.cryptotokens.CryptoTokenTestBase.java
License:Open Source License
/** * Tests export of certificate chain. First imports a generate certificate * chain and then checks that it can be read back. Then imports an other * chain and checks again./*from w w w .j a v a 2 s .c om*/ * @param existingKey entry to use */ protected void exportCertificatesHelper(final String existingKey) throws CryptoTokenOfflineException, KeyStoreException, InvalidWorkerIdException, SignServerException, IllegalArgumentException, CertificateException, CertificateEncodingException, OperationUnsupportedException, NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException, IOException, QueryException, OperationUnsupportedException, AuthorizationDeniedException, InvalidAlgorithmParameterException, UnsupportedCryptoTokenParameter { final ISignerCertReqInfo req = new PKCS10CertReqInfo("SHA1WithRSA", "CN=imported", null); final Base64SignerCertReqData reqData = (Base64SignerCertReqData) genCertificateRequest(req, false, existingKey); // Generate a certificate chain that we will try to import and later export KeyPair issuerKeyPair = CryptoUtils.generateRSA(512); final X509CertificateHolder issuerCert = new JcaX509v3CertificateBuilder( new X500Name("CN=Test Import/Export CA"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650)), new X500Name("CN=Test Import/Export CA"), issuerKeyPair.getPublic()) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq())); final X509CertificateHolder subjectCert1 = new X509v3CertificateBuilder( new X500Name("CN=Test Import/Export CA"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), new X500Name("CN=Test Import/Export 1"), csr.getSubjectPublicKeyInfo()) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); final X509CertificateHolder subjectCert2 = new X509v3CertificateBuilder( new X500Name("CN=Test Import/Export CA"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), new X500Name("CN=Test Import/Export 2"), csr.getSubjectPublicKeyInfo()) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); // Import certficate chain 1 importCertificateChain(Arrays.asList(CertTools.getCertfromByteArray(subjectCert1.getEncoded()), CertTools.getCertfromByteArray(issuerCert.getEncoded())), existingKey); // Find the entry TokenSearchResults searchResults = searchTokenEntries(0, Integer.MAX_VALUE, QueryCriteria.create() .add(new Term(RelationalOperator.EQ, CryptoTokenHelper.TokenEntryFields.alias.name(), existingKey)), true); LinkedList<String> aliases = new LinkedList<String>(); for (TokenEntry entry : searchResults.getEntries()) { aliases.add(entry.getAlias()); } assertArrayEquals(new String[] { existingKey }, aliases.toArray()); TokenEntry entry = searchResults.getEntries().iterator().next(); Certificate[] parsedChain = entry.getParsedChain(); assertEquals("right subject", new JcaX509CertificateConverter().getCertificate(subjectCert1).getSubjectX500Principal().getName(), ((X509Certificate) parsedChain[0]).getSubjectX500Principal().getName()); assertEquals("right issuer", new JcaX509CertificateConverter().getCertificate(issuerCert).getSubjectX500Principal().getName(), ((X509Certificate) parsedChain[1]).getSubjectX500Principal().getName()); // Import certificate chain 2 importCertificateChain(Arrays.asList(CertTools.getCertfromByteArray(subjectCert2.getEncoded()), CertTools.getCertfromByteArray(issuerCert.getEncoded())), existingKey); // Find the entry searchResults = searchTokenEntries(0, Integer.MAX_VALUE, QueryCriteria.create() .add(new Term(RelationalOperator.EQ, CryptoTokenHelper.TokenEntryFields.alias.name(), existingKey)), true); entry = searchResults.getEntries().iterator().next(); parsedChain = entry.getParsedChain(); assertEquals("right subject", new JcaX509CertificateConverter().getCertificate(subjectCert2).getSubjectX500Principal().getName(), ((X509Certificate) parsedChain[0]).getSubjectX500Principal().getName()); assertEquals("right issuer", new JcaX509CertificateConverter().getCertificate(issuerCert).getSubjectX500Principal().getName(), ((X509Certificate) parsedChain[1]).getSubjectX500Principal().getName()); }