List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME
String PROVIDER_NAME
To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.
Click Source Link
From source file:org.cesecore.certificates.ocsp.cache.OcspExtensionsTest.java
License:Open Source License
@BeforeClass public static void beforeClass() throws Exception { CryptoProviderTools.installBCProviderIfNotAvailable(); trustDir = FileTools.createTempDirectory(); caCertificateFile = File.createTempFile("tmp", ".pem"); trustedCertificateFile = File.createTempFile("tmp", ".pem", trustDir); KeyPair caKeyPair = KeyTools.genKeys("1024", "RSA"); Certificate caCertificate = CertTools.genSelfCert("CN=TESTCA", 10L, null, caKeyPair.getPrivate(), caKeyPair.getPublic(), "SHA256WithRSA", true); FileOutputStream fileOutputStream = new FileOutputStream(caCertificateFile); try {// w w w . j av a 2 s . co m fileOutputStream.write(CertTools.getPemFromCertificateChain(Arrays.asList(caCertificate))); } finally { fileOutputStream.close(); } Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); final String certDn = "CN=TEST,SN=4711"; X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(certDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(certDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caKeyPair.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); certificate = CertTools.getCertfromByteArray(certHolder.getEncoded()); fileOutputStream = new FileOutputStream(trustedCertificateFile); try { fileOutputStream.write(CertTools.getPemFromCertificateChain(Arrays.asList(certificate))); } finally { fileOutputStream.close(); } ConfigurationHolder.updateConfiguration("ocsp.extensionoid", OCSP_UNID_OID + ';' + OcspCertHashExtension.CERT_HASH_OID); ConfigurationHolder.updateConfiguration("ocsp.extensionclass", OCSP_UNID_CLASSNAME + ';' + OCSP_CERTHASH_CLASSNAME); ConfigurationHolder.updateConfiguration("ocsp.uniddatsource", "foo"); ConfigurationHolder.updateConfiguration("ocsp.unidtrustdir", trustDir.getAbsolutePath()); ConfigurationHolder.updateConfiguration("ocsp.unidcacert", caCertificateFile.getAbsolutePath()); OcspExtensionsCache.INSTANCE.reloadCache(); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** Tests using the default responder for external CAs for a good certificate. */ @Test//from w w w.j ava2s .c o m public void testResponseWithDefaultResponderForExternal() throws Exception { // Make sure that a default responder is set GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); final String originalDefaultResponder = ocspConfiguration.getOcspDefaultResponderReference(); ocspConfiguration.setOcspDefaultResponderReference(testx509ca.getSubjectDN()); globalConfigurationSession.saveConfiguration(internalAdmin, ocspConfiguration); try { // Now, construct an external CA. final String externalCaName = "testStandAloneOcspResponseExternalCa"; final String externalCaSubjectDn = "CN=" + externalCaName; long validity = 3650L; KeyPair externalCaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate externalCaCertificate = CertTools.genSelfCert(externalCaSubjectDn, validity, null, externalCaKeys.getPrivate(), externalCaKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); X509CAInfo externalCaInfo = new X509CAInfo(externalCaSubjectDn, externalCaName, CAConstants.CA_EXTERNAL, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, validity, CAInfo.SELFSIGNED, null, null); CAToken token = new CAToken(externalCaInfo.getCAId(), new NullCryptoToken().getProperties()); X509CA externalCa = new X509CA(externalCaInfo); externalCa.setCAToken(token); externalCa.setCertificateChain(Arrays.asList(externalCaCertificate)); caSession.addCA(internalAdmin, externalCa); certificateStoreSession.storeCertificate(internalAdmin, externalCaCertificate, externalCaName, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ROOTCA, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, null, new Date().getTime()); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final String externalUsername = "testStandAloneOcspResponseExternalUser"; final String externalSubjectDn = "CN=" + externalUsername; // Create a certificate signed by the external CA and stuff it in the database (we can pretend it was imported) Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(externalCaSubjectDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(externalSubjectDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(externalCaKeys.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate importedCertificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); certificateStoreSession.storeCertificate(internalAdmin, importedCertificate, externalUsername, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); try { //Now everything is in place. Perform a request, make sure that the default responder signed it. OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), (X509Certificate) externalCaCertificate, importedCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq ocspRequest = gen.build(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession.getOcspResponse(ocspRequest.getEncoded(), null, "", "", null, auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", OCSPResp.SUCCESSFUL, response.getStatus()); final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertNotNull("Signed request generated null-response.", basicOcspResponse); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder() .build(testx509ca.getCACertificate().getPublicKey()))); final SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", importedCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); } finally { internalCertificateStoreSession.removeCertificate(importedCertificate); } } finally { caSession.removeCA(internalAdmin, externalCa.getCAId()); internalCertificateStoreSession.removeCertificate(externalCaCertificate); } } finally { GlobalOcspConfiguration restoredOcspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(originalDefaultResponder); globalConfigurationSession.saveConfiguration(internalAdmin, restoredOcspConfiguration); } }
From source file:org.cesecore.certificates.ocsp.OcspResponseInformation.java
License:Open Source License
public OcspResponseInformation(OCSPResp ocspResponse, long maxAge) throws OCSPException { try {/*from w w w .ja v a 2 s . c om*/ this.ocspResponse = ocspResponse.getEncoded(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught when encoding ocsp response.", e); } this.maxAge = maxAge; /* * This may seem like a somewhat odd place to perform the below operations (instead of in the end servlet which demanded * this object), but BouncyCastle (up to 1.47) is a bit shy about making their classes serializable. This means that * OCSPResp can't be transmitted, neither can many of the objects it contains such as SingleResp. Luckily we only need * these classes for the diagnostic operations performed below, so we can sum up the result in the boolean member * addCacheHeaders. If BC choose to change their policy, the below code can med moved to a more logical location. * -mikek */ if (ocspResponse.getResponseObject() == null) { if (log.isDebugEnabled()) { log.debug("Will not add cache headers for response to bad request."); } addCacheHeaders = false; } else { final BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResponse.getResponseObject(); final SingleResp[] singleRespones = basicOCSPResp.getResponses(); if (singleRespones.length != 1) { if (log.isDebugEnabled()) { log.debug("Will not add RFC 5019 cache headers: reponse contains multiple embedded responses."); } addCacheHeaders = false; } else if (singleRespones[0].getNextUpdate() == null) { if (log.isDebugEnabled()) { log.debug("Will not add RFC 5019 cache headers: nextUpdate isn't set."); } addCacheHeaders = false; } else if (basicOCSPResp.hasExtensions() && basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce) != null) { if (log.isDebugEnabled()) { log.debug("Will not add RFC 5019 cache headers: response contains a nonce."); } addCacheHeaders = false; } else { nextUpdate = singleRespones[0].getNextUpdate().getTime(); thisUpdate = singleRespones[0].getThisUpdate().getTime(); try { responseHeader = new String(Hex.encode(MessageDigest .getInstance("SHA-1", BouncyCastleProvider.PROVIDER_NAME).digest(this.ocspResponse))); } catch (NoSuchProviderException e) { throw new OcspFailureException("Bouncycastle was not available as a provider", e); } catch (NoSuchAlgorithmException e) { throw new OcspFailureException("SHA-1 was not an available algorithm for MessageDigester", e); } } if (addCacheHeaders && singleRespones[0].getCertStatus() instanceof UnknownStatus) { explicitNoCache = true; } } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** Tests using the default responder for external CAs for a good certificate. */ @Test// www .j a v a 2s . c om public void testResponseWithDefaultResponderForExternal() throws Exception { // Make sure that a default responder is set GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); final String originalDefaultResponder = ocspConfiguration.getOcspDefaultResponderReference(); ocspConfiguration.setOcspDefaultResponderReference(CertTools.getIssuerDN(ocspSigningCertificate)); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); try { //Make default responder standalone OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); // Now, construct an external CA. final String externalCaName = "testStandAloneOcspResponseExternalCa"; final String externalCaSubjectDn = "CN=" + externalCaName; long validity = 3650L; KeyPair externalCaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate externalCaCertificate = CertTools.genSelfCert(externalCaSubjectDn, validity, null, externalCaKeys.getPrivate(), externalCaKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); X509CAInfo externalCaInfo = new X509CAInfo(externalCaSubjectDn, externalCaName, CAConstants.CA_EXTERNAL, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, validity, CAInfo.SELFSIGNED, null, null); CAToken token = new CAToken(externalCaInfo.getCAId(), new NullCryptoToken().getProperties()); X509CA externalCa = new X509CA(externalCaInfo); externalCa.setCAToken(token); externalCa.setCertificateChain(Arrays.asList(externalCaCertificate)); caSession.addCA(authenticationToken, externalCa); certificateStoreSession.storeCertificate(authenticationToken, externalCaCertificate, externalCaName, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ROOTCA, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, null, new Date().getTime()); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final String externalUsername = "testStandAloneOcspResponseExternalUser"; final String externalSubjectDn = "CN=" + externalUsername; // Create a certificate signed by the external CA and stuff it in the database (we can pretend it was imported) Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(externalCaSubjectDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(externalSubjectDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(externalCaKeys.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate importedCertificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); certificateStoreSession.storeCertificate(authenticationToken, importedCertificate, externalUsername, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); try { //Now everything is in place. Perform a request, make sure that the default responder signed it. final OCSPReq ocspRequest = buildOcspRequest(null, null, (X509Certificate) externalCaCertificate, importedCertificate.getSerialNumber()); final OCSPResp response = sendRequest(ocspRequest); assertEquals("Response status not zero.", OCSPResp.SUCCESSFUL, response.getStatus()); final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertNotNull("Signed request generated null-response.", basicOcspResponse); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid( new JcaContentVerifierProviderBuilder().build(ocspSigningCertificate.getPublicKey()))); final SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", importedCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); } finally { internalCertificateStoreSession.removeCertificate(importedCertificate); } } finally { caSession.removeCA(authenticationToken, externalCa.getCAId()); internalCertificateStoreSession.removeCertificate(externalCaCertificate); } } finally { GlobalOcspConfiguration restoredOcspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(originalDefaultResponder); globalConfigurationSession.saveConfiguration(authenticationToken, restoredOcspConfiguration); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** Tests using the default responder for external CAs for a good certificate. */ @Test/* w w w . j a v a 2 s. c om*/ public void testResponseWithDefaultResponderForExternalNoDefaultSet() throws Exception { // Make sure that a default responder is set GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(""); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); String originalNoneExistingIsGood = cesecoreConfigurationProxySession .getConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, "false"); try { //Make default responder standalone OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); // Now, construct an external CA. final String externalCaName = "testStandAloneOcspResponseExternalCa"; final String externalCaSubjectDn = "CN=" + externalCaName; long validity = 3650L; KeyPair externalCaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate externalCaCertificate = CertTools.genSelfCert(externalCaSubjectDn, validity, null, externalCaKeys.getPrivate(), externalCaKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); X509CAInfo externalCaInfo = new X509CAInfo(externalCaSubjectDn, externalCaName, CAConstants.CA_EXTERNAL, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, validity, CAInfo.SELFSIGNED, null, null); CAToken token = new CAToken(externalCaInfo.getCAId(), new NullCryptoToken().getProperties()); X509CA externalCa = new X509CA(externalCaInfo); externalCa.setCAToken(token); externalCa.setCertificateChain(Arrays.asList(externalCaCertificate)); caSession.addCA(authenticationToken, externalCa); certificateStoreSession.storeCertificate(authenticationToken, externalCaCertificate, externalCaName, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ROOTCA, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, null, new Date().getTime()); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final String externalUsername = "testStandAloneOcspResponseExternalUser"; final String externalSubjectDn = "CN=" + externalUsername; // Create a certificate signed by the external CA and stuff it in the database (we can pretend it was imported) Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(externalCaSubjectDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(externalSubjectDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(externalCaKeys.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate importedCertificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); certificateStoreSession.storeCertificate(authenticationToken, importedCertificate, externalUsername, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); try { //Now everything is in place. Perform a request, make sure that the default responder signed it. final OCSPReq ocspRequest = buildOcspRequest(null, null, (X509Certificate) externalCaCertificate, importedCertificate.getSerialNumber()); final OCSPResp response = sendRequest(ocspRequest); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); assertNull("Response should not have contained a response object.", response.getResponseObject()); } finally { internalCertificateStoreSession.removeCertificate(importedCertificate); } } finally { caSession.removeCA(authenticationToken, externalCa.getCAId()); internalCertificateStoreSession.removeCertificate(externalCaCertificate); } } finally { cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, originalNoneExistingIsGood); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** Tests using the default responder for external CAs, tests with a revoked cert */ @Test/*from w w w .j av a2 s. co m*/ public void testResponseWithDefaultResponderForExternalRevoked() throws Exception { // Make sure that a default responder is set GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(CertTools.getIssuerDN(ocspSigningCertificate)); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); String originalNoneExistingIsGood = cesecoreConfigurationProxySession .getConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, "false"); try { //Make default responder standalone OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); // Now, construct an external CA. final String externalCaName = "testStandAloneOcspResponseExternalCa"; final String externalCaSubjectDn = "CN=" + externalCaName; long validity = 3650L; KeyPair externalCaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate externalCaCertificate = CertTools.genSelfCert(externalCaSubjectDn, validity, null, externalCaKeys.getPrivate(), externalCaKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); X509CAInfo externalCaInfo = new X509CAInfo(externalCaSubjectDn, externalCaName, CAConstants.CA_EXTERNAL, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, validity, CAInfo.SELFSIGNED, null, null); CAToken token = new CAToken(externalCaInfo.getCAId(), new NullCryptoToken().getProperties()); X509CA externalCa = new X509CA(externalCaInfo); externalCa.setCAToken(token); externalCa.setCertificateChain(Arrays.asList(externalCaCertificate)); caSession.addCA(authenticationToken, externalCa); certificateStoreSession.storeCertificate(authenticationToken, externalCaCertificate, externalCaName, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ROOTCA, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, null, new Date().getTime()); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final String externalUsername = "testStandAloneOcspResponseExternalUser"; final String externalSubjectDn = "CN=" + externalUsername; // Create a certificate signed by the external CA and stuff it in the database (we can pretend it was imported) Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(externalCaSubjectDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(externalSubjectDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(externalCaKeys.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate importedCertificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); certificateStoreSession.storeCertificate(authenticationToken, importedCertificate, externalUsername, "1234", CertificateConstants.CERT_REVOKED, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); try { //Now everything is in place. Perform a request, make sure that the default responder signed it. final OCSPReq ocspRequest = buildOcspRequest(null, null, (X509Certificate) externalCaCertificate, importedCertificate.getSerialNumber()); final OCSPResp response = sendRequest(ocspRequest); assertEquals("Response status not zero.", OCSPResp.SUCCESSFUL, response.getStatus()); final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertNotNull("Signed request generated null-response.", basicOcspResponse); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid( new JcaContentVerifierProviderBuilder().build(ocspSigningCertificate.getPublicKey()))); final SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", importedCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertTrue("Status is not revoked", singleResponses[0].getCertStatus() instanceof RevokedStatus); } finally { internalCertificateStoreSession.removeCertificate(importedCertificate); } } finally { caSession.removeCA(authenticationToken, externalCa.getCAId()); internalCertificateStoreSession.removeCertificate(externalCaCertificate); } } finally { cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, originalNoneExistingIsGood); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
@Test public void testGetOcspResponseWithIncorrectDefaultResponder() throws Exception { // Set a fake value GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference("CN=FancyPants"); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "true"); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspSigningCertificate, ocspSigningCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); //Create a signed request in order to test all aspects KeyPair keys = KeyTools.genKeys("512", "RSA"); // Issue a certificate to a test user final String endEntityName = "testGetOcspResponseWithIncorrectDefaultResponder"; final EndEntityInformation user = new EndEntityInformation(endEntityName, "CN=" + endEntityName, x509ca.getCAId(), null, null, new EndEntityType(EndEntityTypes.ENDUSER), 1, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null); user.setStatus(EndEntityConstants.STATUS_NEW); user.setPassword("foo123"); final SimpleRequestMessage certreq = new SimpleRequestMessage(keys.getPublic(), user.getUsername(), user.getPassword());//from w w w . j av a2 s. c o m final X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate( authenticationToken, user, certreq, X509ResponseMessage.class, signSession.fetchCertGenParams()); final X509Certificate ocspTestCert = (X509Certificate) resp.getCertificate(); X509CertificateHolder chain[] = new JcaX509CertificateHolder[2]; chain[0] = new JcaX509CertificateHolder(ocspTestCert); chain[1] = new JcaX509CertificateHolder(caCertificate); gen.setRequestorName(chain[0].getSubject()); OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain); //Now delete the original CA, making this test completely standalone. OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); //We're expecting back an unsigned reply saying unauthorized, as per RFC2690 Section 2.3 assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); assertNull("Response should not have contained a response object.", response.getResponseObject()); } finally { try { if (ocspTestCert != null) internalCertificateStoreSession.removeCertificate(ocspTestCert); } catch (Exception e) { //NOPMD: Ignore } cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "false"); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** * Build an OCSP request, that will optionally be signed if authentication parameters are specified * /*from ww w. j av a 2 s. com*/ * @param ocspAuthenticationCertificate signing certificate * @param ocspAuthenticationPrivateKey private key to sign with * @param caCertificate issuer of the queried certificate * @param certificateSerialnumber serial number of the certificate to be queried * @return * @throws Exception */ private OCSPReq buildOcspRequest(final X509Certificate ocspAuthenticationCertificate, final PrivateKey ocspAuthenticationPrivateKey, final X509Certificate caCertificate, final BigInteger certificateSerialnumber) throws Exception { final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); if (ocspAuthenticationCertificate != null) { // Signed requests are required to have an OCSPRequest.TBSRequest.requestorName ocspReqBuilder.setRequestorName(new X500Name(ocspAuthenticationCertificate.getSubjectDN().getName())); } ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, certificateSerialnumber)); ocspReqBuilder.setRequestExtensions( new Extensions(new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())) })); if (ocspAuthenticationCertificate != null && ocspAuthenticationPrivateKey != null) { // Create a signed request final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspAuthenticationPrivateKey), 20480); return ocspReqBuilder.build(signer, new X509CertificateHolder[] { new X509CertificateHolder(ocspAuthenticationCertificate.getEncoded()) }); } else { // Create an unsigned request return ocspReqBuilder.build(); } }
From source file:org.cesecore.keys.token.CachingKeyStoreWrapperTest.java
License:Open Source License
private void testGenerateUseDelete(final boolean cache) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME); keyStore.load(null, null);//from www. j a va 2 s. c om final CachingKeyStoreWrapper cachingKeyStoreWrapper = new CachingKeyStoreWrapper(keyStore, cache); testGenerate(cachingKeyStoreWrapper, ALIAS); testUse(cachingKeyStoreWrapper, ALIAS); testRemove(cachingKeyStoreWrapper, ALIAS); }
From source file:org.cesecore.keys.token.CachingKeyStoreWrapperTest.java
License:Open Source License
private void testPersistLoad(final boolean cache) throws Exception { // Create a key store with some content final KeyStore keyStore = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME); keyStore.load(null, null);/* ww w . j a v a2s.c o m*/ final CachingKeyStoreWrapper cachingKeyStoreWrapper = new CachingKeyStoreWrapper(keyStore, cache); testGenerate(cachingKeyStoreWrapper, ALIAS); // "Persist" and load it back from storage final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); cachingKeyStoreWrapper.store(baos2, PASSWORD); final KeyStore keyStore2 = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME); keyStore2.load(new ByteArrayInputStream(baos2.toByteArray()), PASSWORD); // Test loaded key store final CachingKeyStoreWrapper cachingKeyStoreWrapper2 = new CachingKeyStoreWrapper(keyStore2, cache); testUse(cachingKeyStoreWrapper2, ALIAS); // "Persist" and load it back from storage final ByteArrayOutputStream baos3 = new ByteArrayOutputStream(); cachingKeyStoreWrapper2.store(baos3, PASSWORD); final KeyStore keyStore3 = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME); keyStore3.load(new ByteArrayInputStream(baos3.toByteArray()), PASSWORD); // Test loaded key store final CachingKeyStoreWrapper cachingKeyStoreWrapper3 = new CachingKeyStoreWrapper(keyStore3, cache); testRemove(cachingKeyStoreWrapper3, ALIAS); }