List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder
public JcaContentSignerBuilder(String signatureAlgorithm)
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain) throws SignRequestSignatureException { // First verify that we signed this certificate try {//from ww w . j a v a 2s. com if (cert != null) { final PublicKey verifyKey; final X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } cert.verify(verifyKey); } } catch (CryptoTokenOfflineException e) { throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7", e); } catch (InvalidKeyException e) { throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e); } catch (CertificateException e) { throw new SignRequestSignatureException("An encoding error was encountered.", e); } catch (NoSuchAlgorithmException e) { throw new SignRequestSignatureException( "The certificate provided was signed with an invalid algorithm.", e); } catch (NoSuchProviderException e) { throw new SignRequestSignatureException( "The crypto provider was not found for verification of the certificate.", e); } catch (SignatureException e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?", e); } Collection<Certificate> chain = getCertificateChain(); ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>(); try { if (cert != null) { certList.add(new JcaX509CertificateHolder((X509Certificate) cert)); } if (includeChain) { for (Certificate certificate : chain) { certList.add(new JcaX509CertificateHolder((X509Certificate) certificate)); } } } catch (CertificateEncodingException e) { throw new SignRequestSignatureException("Could not encode certificate", e); } try { CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes()); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final PrivateKey privateKey = cryptoToken .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); if (privateKey == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } String signatureAlgorithmName = AlgorithmTools .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(cryptoToken.getSignProviderName()).build(privateKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate())); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } gen.addCertificates(new CollectionStore(certList)); CMSSignedData s = null; CAToken catoken = getCAToken(); if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) { log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm " + privateKey.getAlgorithm()); s = gen.generate(msg, true); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CryptoTokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { //FIXME: This right here is just nasty throw new RuntimeException(e); } }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Sequence is ignored by X509CA. The ctParams argument will NOT be kept after the function call returns, * and is allowed to contain references to session beans. * /* w w w . ja v a 2 s. c o m*/ * @throws CAOfflineException if the CA wasn't active * @throws InvalidAlgorithmException if the signing algorithm in the certificate profile (or the CA Token if not found) was invalid. * @throws IllegalValidityException if validity was invalid * @throws IllegalNameException if the name specified in the certificate request was invalid * @throws CertificateExtensionException if any of the certificate extensions were invalid * @throws OperatorCreationException if CA's private key contained an unknown algorithm or provider * @throws CertificateCreateException if an error occurred when trying to create a certificate. * @throws SignatureException if the CA's certificate's and request's certificate's and signature algorithms differ */ private Certificate generateCertificate(final EndEntityInformation subject, final RequestMessage request, final PublicKey publicKey, final int keyusage, final Date notBefore, final Date notAfter, final CertificateProfile certProfile, final Extensions extensions, final String sequence, final PublicKey caPublicKey, final PrivateKey caPrivateKey, final String provider, CertificateGenerationParams certGenParams) throws CAOfflineException, InvalidAlgorithmException, IllegalValidityException, IllegalNameException, CertificateExtensionException, OperatorCreationException, CertificateCreateException, SignatureException { // We must only allow signing to take place if the CA itself is on line, even if the token is on-line. // We have to allow expired as well though, so we can renew expired CAs if ((getStatus() != CAConstants.CA_ACTIVE) && ((getStatus() != CAConstants.CA_EXPIRED))) { final String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus()); if (log.isDebugEnabled()) { log.debug(msg); // This is something we handle so no need to log with higher priority } throw new CAOfflineException(msg); } final String sigAlg; if (certProfile.getSignatureAlgorithm() == null) { sigAlg = getCAToken().getSignatureAlgorithm(); } else { sigAlg = certProfile.getSignatureAlgorithm(); } // Check that the signature algorithm is one of the allowed ones if (!ArrayUtils.contains(AlgorithmConstants.AVAILABLE_SIGALGS, sigAlg)) { final String msg = intres.getLocalizedMessage("createcert.invalidsignaturealg", sigAlg); throw new InvalidAlgorithmException(msg); } // Check if this is a root CA we are creating final boolean isRootCA = certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA; final X509Certificate cacert = (X509Certificate) getCACertificate(); // Check CA certificate PrivateKeyUsagePeriod if it exists (throws CAOfflineException if it exists and is not within this time) CertificateValidity.checkPrivateKeyUsagePeriod(cacert); // Get certificate validity time notBefore and notAfter final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); final BigInteger serno; { // Serialnumber is either random bits, where random generator is initialized by the serno generator. // Or a custom serial number defined in the end entity object final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowCertSerialNumberOverride()) { if (ei != null && ei.certificateSerialNumber() != null) { serno = ei.certificateSerialNumber(); } else { serno = SernoGeneratorRandom.instance().getSerno(); } } else { serno = SernoGeneratorRandom.instance().getSerno(); if ((ei != null) && (ei.certificateSerialNumber() != null)) { final String msg = intres.getLocalizedMessage( "createcert.certprof_not_allowing_cert_sn_override_using_normal", ei.certificateSerialNumber().toString(16)); log.info(msg); } } } // Make DNs String dn = subject.getCertificateDN(); if (certProfile.getUseSubjectDNSubSet()) { dn = certProfile.createSubjectDNSubSet(dn); } final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } if (certProfile.getUseCNPostfix()) { dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix(), nameStyle); } // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN final boolean ldapdnorder; if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) { ldapdnorder = false; } else { ldapdnorder = true; } final X500Name subjectDNName; if (certProfile.getAllowDNOverride() && (request != null) && (request.getRequestX500Name() != null)) { subjectDNName = request.getRequestX500Name(); if (log.isDebugEnabled()) { log.debug("Using X509Name from request instead of user's registered."); } } else { final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowDNOverrideByEndEntityInformation() && ei != null && ei.getRawSubjectDn() != null) { final String stripped = StringTools.strip(ei.getRawSubjectDn()); final String escapedPluses = CertTools.handleUnescapedPlus(stripped); final String emptiesRemoved = DNFieldsUtil.removeAllEmpties(escapedPluses); final X500Name subjectDNNameFromEei = CertTools.stringToUnorderedX500Name(emptiesRemoved, CeSecoreNameStyle.INSTANCE); if (subjectDNNameFromEei.toString().length() > 0) { subjectDNName = subjectDNNameFromEei; if (log.isDebugEnabled()) { log.debug( "Using X500Name from end entity information instead of user's registered subject DN fields."); log.debug("ExtendedInformation.getRawSubjectDn(): " + ei.getRawSubjectDn() + " will use: " + CeSecoreNameStyle.INSTANCE.toString(subjectDNName)); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } // Make sure the DN does not contain dangerous characters if (StringTools.hasStripChars(subjectDNName.toString())) { if (log.isTraceEnabled()) { log.trace("DN with illegal name: " + subjectDNName); } final String msg = intres.getLocalizedMessage("createcert.illegalname"); throw new IllegalNameException(msg); } if (log.isDebugEnabled()) { log.debug("Using subjectDN: " + subjectDNName.toString()); } // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN // which many applications do not like. X500Name issuerDNName; if (isRootCA) { // This will be an initial root CA, since no CA-certificate exists // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer, // it might have changed over the years. if (log.isDebugEnabled()) { log.debug("Using subject DN also as issuer DN, because it is a root CA"); } issuerDNName = subjectDNName; } else { issuerDNName = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); if (log.isDebugEnabled()) { log.debug("Using issuer DN directly from the CA certificate: " + issuerDNName.toString()); } } SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo); // Only created and used if Certificate Transparency is enabled final X509v3CertificateBuilder precertbuilder = certProfile.isUseCertificateTransparencyInCerts() ? new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo) : null; // Check that the certificate fulfills name constraints if (cacert instanceof X509Certificate) { GeneralNames altNameGNs = null; String altName = subject.getSubjectAltName(); if (certProfile.getUseSubjectAltNameSubSet()) { altName = certProfile.createSubjectAltNameSubSet(altName); } if (altName != null && altName.length() > 0) { altNameGNs = CertTools.getGeneralNamesFromAltName(altName); } CertTools.checkNameConstraints((X509Certificate) cacert, subjectDNName, altNameGNs); } // If the subject has Name Constraints, then name constraints must be enabled in the certificate profile! if (subject.getExtendedinformation() != null) { final ExtendedInformation ei = subject.getExtendedinformation(); final List<String> permittedNC = ei.getNameConstraintsPermitted(); final List<String> excludedNC = ei.getNameConstraintsExcluded(); if ((permittedNC != null && !permittedNC.isEmpty()) || (excludedNC != null && !excludedNC.isEmpty())) { if (!certProfile.getUseNameConstraints()) { throw new CertificateCreateException( "Tried to issue a certificate with Name Constraints without having enabled NC in the certificate profile."); } } } // // X509 Certificate Extensions // // Extensions we will add to the certificate, later when we have filled the structure with // everything we want. final ExtensionsGenerator extgen = new ExtensionsGenerator(); // First we check if there is general extension override, and add all extensions from // the request in that case if (certProfile.getAllowExtensionOverride() && extensions != null) { ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); for (ASN1ObjectIdentifier oid : oids) { final Extension ext = extensions.getExtension(oid); if (log.isDebugEnabled()) { log.debug("Overriding extension with oid: " + oid); } try { extgen.addExtension(oid, ext.isCritical(), ext.getParsedValue()); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } } // Second we see if there is Key usage override Extensions overridenexts = extgen.generate(); if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) { if (log.isDebugEnabled()) { log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage); } if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) { final KeyUsage ku = new KeyUsage(keyusage); // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(Extension.keyUsage) == null) { try { extgen.addExtension(Extension.keyUsage, certProfile.getKeyUsageCritical(), ku); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } else { if (log.isDebugEnabled()) { log.debug( "KeyUsage was already overridden by an extension, not using KeyUsage from parameter."); } } } } // Third, check for standard Certificate Extensions that should be added. // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory // and implemented in package org.ejbca.core.model.certextensions.standard final CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance(); final List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions(); final Iterator<String> certStdExtIter = usedStdCertExt.iterator(); overridenexts = extgen.generate(); while (certStdExtIter.hasNext()) { final String oid = certStdExtIter.next(); // We don't want to try to add standard extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(oid)) == null) { final CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile); if (certExt != null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + oid + " has been overridden, standard extension will not be added."); } } } // Fourth, check for custom Certificate Extensions that should be added. // Custom certificate extensions is defined in certextensions.properties final List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions(); final Iterator<Integer> certExtIter = usedCertExt.iterator(); while (certExtIter.hasNext()) { final Integer id = certExtIter.next(); final CertificateExtension certExt = fact.getCertificateExtensions(id); if (certExt != null) { // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(certExt.getOID())) == null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + certExt.getOID() + " has been overridden, custom extension will not be added."); } } } } // Finally add extensions to certificate generator final Extensions exts = extgen.generate(); ASN1ObjectIdentifier[] oids = exts.getExtensionOIDs(); try { for (ASN1ObjectIdentifier oid : oids) { final Extension extension = exts.getExtension(oid); if (oid.equals(Extension.subjectAlternativeName)) { // subjectAlternativeName extension value needs special handling ExtensionsGenerator sanExtGen = getSubjectAltNameExtensionForCert(extension, precertbuilder != null); Extensions sanExts = sanExtGen.generate(); Extension eext = sanExts.getExtension(oid); certbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjetAlternativeName extension to certbuilder if (precertbuilder != null) { // if a pre-certificate is to be published to a CTLog eext = getSubjectAltNameExtensionForCTCert(extension).generate().getExtension(oid); precertbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjectAlternativeName extension to precertbuilder eext = sanExts.getExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6")); if (eext != null) { certbuilder.addExtension(eext.getExtnId(), eext.isCritical(), eext.getParsedValue()); // adding nrOfRedactedLabels extension to certbuilder } } } else { // if not a subjectAlternativeName extension, just add it to both certbuilder and precertbuilder final boolean isCritical = extension.isCritical(); // We must get the raw octets here in order to be able to create invalid extensions that is not constructed from proper ASN.1 final byte[] value = extension.getExtnValue().getOctets(); certbuilder.addExtension(extension.getExtnId(), isCritical, value); if (precertbuilder != null) { precertbuilder.addExtension(extension.getExtnId(), isCritical, value); } } } // Add Certificate Transparency extension. It needs to access the certbuilder and // the CA key so it has to be processed here inside X509CA. if (ct != null && certProfile.isUseCertificateTransparencyInCerts() && certGenParams.getConfiguredCTLogs() != null && certGenParams.getCTAuditLogCallback() != null) { // Create pre-certificate // A critical extension is added to prevent this cert from being used ct.addPreCertPoison(precertbuilder); // Sign pre-certificate /* * TODO: Should be able to use a special CT signing certificate. * It should have CA=true and ExtKeyUsage=PRECERTIFICATE_SIGNING_OID, * and should not have any other key usages. */ final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = precertbuilder.build(signer); final X509Certificate cert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); // Get certificate chain final List<Certificate> chain = new ArrayList<Certificate>(); chain.add(cert); chain.addAll(getCertificateChain()); // Submit to logs and get signed timestamps byte[] sctlist = null; try { sctlist = ct.fetchSCTList(chain, certProfile, certGenParams.getConfiguredCTLogs()); } finally { // Notify that pre-cert has been successfully or unsuccessfully submitted so it can be audit logged. certGenParams.getCTAuditLogCallback().logPreCertSubmission(this, subject, cert, sctlist != null); } if (sctlist != null) { // can be null if the CTLog has been deleted from the configuration ASN1ObjectIdentifier sctOid = new ASN1ObjectIdentifier(CertificateTransparency.SCTLIST_OID); certbuilder.addExtension(sctOid, false, new DEROctetString(sctlist)); } } else { if (log.isDebugEnabled()) { String cause = ""; if (ct == null) { cause += "CT is not available in this version of EJBCA."; } else { if (!certProfile.isUseCertificateTransparencyInCerts()) { cause += "CT is not enabled in the certificate profile. "; } if (certGenParams == null) { cause += "Certificate generation parameters was null."; } else if (certGenParams.getCTAuditLogCallback() == null) { cause += "No CT audit logging callback was passed to X509CA."; } else if (certGenParams.getConfiguredCTLogs() == null) { cause += "There are no CT logs configured in System Configuration."; } } log.debug("Not logging to CT. " + cause); } } } catch (CertificateException e) { throw new CertificateCreateException( "Could not process CA's private key when parsing Certificate Transparency extension.", e); } catch (IOException e) { throw new CertificateCreateException( "IOException was caught when parsing Certificate Transparency extension.", e); } catch (CTLogException e) { throw new CertificateCreateException( "An exception occurred because too many CT servers were down to satisfy the certificate profile.", e); } // // End of extensions // if (log.isTraceEnabled()) { log.trace(">certgen.generate"); } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate cert; try { cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught when parsing certificate holder.", e); } catch (CertificateException e) { throw new CertificateCreateException("Could not create certificate from CA's private key,", e); } if (log.isTraceEnabled()) { log.trace("<certgen.generate"); } // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert // because something is wrong... final PublicKey verifyKey; // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing // the keys. In this case the _new_ key will not match the current CA certificate. if ((cacert != null) && (!isRootCA)) { verifyKey = cacert.getPublicKey(); } else { verifyKey = caPublicKey; } try { cert.verify(verifyKey); } catch (InvalidKeyException e) { throw new CertificateCreateException("CA's public key was invalid,", e); } catch (NoSuchAlgorithmException e) { throw new CertificateCreateException(e); } catch (NoSuchProviderException e) { throw new IllegalStateException("Provider was unknown", e); } catch (CertificateException e) { throw new CertificateCreateException(e); } // If we have a CA-certificate, verify that we have all path verification stuff correct if (cacert != null) { final byte[] aki = CertTools.getAuthorityKeyId(cert); final byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert); if ((aki != null) && (ski != null)) { final boolean eq = Arrays.equals(aki, ski); if (!eq) { final String akistr = new String(Hex.encode(aki)); final String skistr = new String(Hex.encode(ski)); final String msg = intres.getLocalizedMessage("createcert.errorpathverifykeyid", akistr, skistr); log.error(msg); // This will differ if we create link certificates, NewWithOld, therefore we can not throw an exception here. } } final Principal issuerDN = cert.getIssuerX500Principal(); final Principal caSubjectDN = cacert.getSubjectX500Principal(); if ((issuerDN != null) && (caSubjectDN != null)) { final boolean eq = issuerDN.equals(caSubjectDN); if (!eq) { final String msg = intres.getLocalizedMessage("createcert.errorpathverifydn", issuerDN.getName(), caSubjectDN.getName()); log.error(msg); throw new CertificateCreateException(msg); } } } // Before returning from this method, we will set the private key and provider in the request message, in case the response message needs to be signed if (request != null) { request.setResponseKeyInfo(caPrivateKey, provider); } if (log.isDebugEnabled()) { log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: " + subject.getCertificateDN()); } return cert; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Generate a CRL or a deltaCRL// ww w . j av a2s . c o m * * @param certs * list of revoked certificates * @param crlnumber * CRLNumber for this CRL * @param isDeltaCRL * true if we should generate a DeltaCRL * @param basecrlnumber * caseCRLNumber for a delta CRL, use 0 for full CRLs * @param certProfile * certificate profile for CRL Distribution point in the CRL, or null * @return CRL * @throws CryptoTokenOfflineException * @throws IllegalCryptoTokenException * @throws IOException * @throws SignatureException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CRLException * @throws NoSuchAlgorithmException */ private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL, int basecrlnumber) throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", " + basecrlnumber); } // Make DNs final X509Certificate cacert = (X509Certificate) getCACertificate(); final X500Name issuer; if (cacert == null) { // This is an initial root CA, since no CA-certificate exists // (I don't think we can ever get here!!!) final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder()); } else { issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); } final Date thisUpdate = new Date(); final Date nextUpdate = new Date(); nextUpdate.setTime(nextUpdate.getTime() + crlPeriod); final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate); crlgen.setNextUpdate(nextUpdate); if (certs != null) { if (log.isDebugEnabled()) { log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { final RevokedCertInfo certinfo = (RevokedCertInfo) it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } if (log.isDebugEnabled()) { log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } } // Authority key identifier if (getUseAuthorityKeyIdentifier() == true) { byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null); if (caSkid != null) { // Use subject key id from CA certificate AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } else { // Generate from SHA1 of public key ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)) .getEncoded())); try { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) asn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } finally { asn1InputStream.close(); } } } // Authority Information Access final ASN1EncodableVector accessList = new ASN1EncodableVector(); if (getAuthorityInformationAccess() != null) { for (String url : getAuthorityInformationAccess()) { if (StringUtils.isNotEmpty(url)) { GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } if (accessList.size() > 0) { AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess .getInstance(new DERSequence(accessList)); // "This CRL extension MUST NOT be marked critical." according to rfc4325 crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // CRLNumber extension if (getUseCRLNumber() == true) { CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum); } if (isDeltaCRL) { // DeltaCRLIndicator extension CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber)); crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum); } // CRL Distribution point URI and Freshest CRL DP if (getUseCrlDistributionPointOnCrl()) { String crldistpoint = getDefaultCRLDistPoint(); List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint); if (distpoints.size() > 0) { IssuingDistributionPoint idp = new IssuingDistributionPoint( distpoints.get(0).getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(), idp); } if (!isDeltaCRL) { String crlFreshestDP = getCADefinedFreshestCRL(); List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP); if (freshestDistPoints.size() > 0) { CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints .toArray(new DistributionPoint[freshestDistPoints.size()])); // According to the RFC, the Freshest CRL extension on a // CRL must not be marked as critical. Therefore it is // hardcoded as not critical and is independent of // getCrlDistributionPointOnCrlCritical(). crlgen.addExtension(Extension.freshestCRL, false, ext); } } } final X509CRLHolder crl; if (log.isDebugEnabled()) { log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN); try { final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg) .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480); crl = crlgen.build(signer); } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } if (log.isDebugEnabled()) { log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } // Verify using the CA certificate before returning // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL // because something is wrong... final PublicKey verifyKey; if (cacert != null) { verifyKey = cacert.getPublicKey(); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA certificate."); } } else { verifyKey = cryptoToken.getPublicKey(alias); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA token."); } } try { final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey); if (!crl.isSignatureValid(verifier)) { throw new SignatureException("Error verifying CRL to be returned."); } } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } catch (CertException e) { throw new SignatureException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } return crl; }
From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java
License:Open Source License
/** * Tests issuing a CRL from a CA with a SKID that is not generated with SHA1. * The CRL is checked to contain the correct AKID value. *//*from ww w .ja v a2 s . c om*/ @Test public void testNonSHA1KeyId() throws Exception { final String subcaname = "CrlCSTestSub"; final String subcadn = "CN=" + subcaname; try { // Create an external root ca certificate final KeyPair rootcakp = KeyTools.genKeys("1024", "RSA"); final String rootcadn = "CN=CrlCSTestRoot"; final X509Certificate rootcacert = CertTools.genSelfCert(rootcadn, 3650, null, rootcakp.getPrivate(), rootcakp.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, "BC", false); // Create sub ca final int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(authenticationToken, subcaname, "1024"); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); X509CAInfo subcainfo = new X509CAInfo(subcadn, subcaname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 365, CAInfo.SIGNEDBYEXTERNALCA, null, catoken); X509CA subca = new X509CA(subcainfo); subca.setCAToken(catoken); caSession.addCA(authenticationToken, subca); // Issue sub CA certificate with a non-standard SKID PublicKey subcapubkey = cryptoTokenMgmtSession.getPublicKey(authenticationToken, cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)).getPublicKey(); Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + 365 * 24 * 60 * 60 * 1000); final SubjectPublicKeyInfo subcaspki = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(subcapubkey.getEncoded())); final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(rootcadn, false), new BigInteger(64, new Random(System.nanoTime())), firstDate, lastDate, CertTools.stringToBcX500Name(subcadn, false), subcaspki); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(CertTools.getAuthorityKeyId(rootcacert)); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(TEST_AKID); // Non-standard SKID. It should match the AKID in the CRL certbuilder.addExtension(Extension.authorityKeyIdentifier, true, aki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); BasicConstraints bc = new BasicConstraints(true); certbuilder.addExtension(Extension.basicConstraints, true, bc); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign); certbuilder.addExtension(Extension.keyUsage, true, ku); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(rootcakp.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate subcacert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded(), "BC"); // Replace sub CA certificate with a sub CA cert containing the test AKID subcainfo = (X509CAInfo) caSession.getCAInfo(authenticationToken, subcaname); List<Certificate> certificatechain = new ArrayList<Certificate>(); certificatechain.add(subcacert); certificatechain.add(rootcacert); subcainfo.setCertificateChain(certificatechain); subcainfo.setExpireTime(CertTools.getNotAfter(subcacert)); caSession.editCA(authenticationToken, subcainfo); subca = (X509CA) caTestSessionRemote.getCA(authenticationToken, subcaname); assertArrayEquals("Wrong SKID in test CA.", TEST_AKID, CertTools.getSubjectKeyId(subca.getCACertificate())); // Create a base CRL and check the AKID int baseCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("For a new CA, the next crl number should be 1.", 1, baseCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), -1, baseCrlNumber); final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); checkCrlAkid(subca, crl); // Create a delta CRL and check the AKID int deltaCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("Next CRL number should be 2 at this point.", 2, deltaCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), baseCrlNumber, deltaCrlNumber); final byte[] deltacrl = crlStoreSession.getLastCRL(subcadn, true); // true = get delta CRL checkCrlAkid(subca, deltacrl); } finally { // Remove everything created above to clean the database final Integer cryptoTokenId = cryptoTokenMgmtSession.getIdFromName(subcaname); if (cryptoTokenId != null) { CryptoTokenTestUtils.removeCryptoToken(authenticationToken, cryptoTokenId); } try { int caid = caSession.getCAInfo(authenticationToken, subcaname).getCAId(); // Delete sub CA CRLs while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, true); // delta CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); // base CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } // Delete sub CA caSession.removeCA(authenticationToken, caid); } catch (CADoesntExistsException cade) { // NOPMD ignore } } }
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 {//ww w .j av a2 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.HsmResponseThread.java
License:Open Source License
@Override public BasicOCSPResp call() throws OCSPException { try {/*from ww w . j a va 2 s.co m*/ /* * BufferingContentSigner defaults to allocating a 4096 bytes buffer. Since a rather large OCSP response (e.g. signed with 4K * RSA key, nonce and a one level chain) is less then 2KiB, this is generally a waste of allocation and garbage collection. * * In high performance environments, the full OCSP response should in general be smaller than 1492 bytes to fit in a single * Ethernet frame. * * Lowering this allocation from 20480 to 4096 bytes under ECA-4084 which should still be plenty. */ final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(signingAlgorithm).setProvider(provider).build(signerKey), 20480); return basicRes.build(signer, chain, producedAt != null ? producedAt : new Date()); } catch (OperatorCreationException e) { throw new OcspFailureException(e); } }
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/* ww w. j av a2 s . 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.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** Tests using the default responder for external CAs for a good certificate. */ @Test/*from ww w.j a v a 2 s . 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/*from w w w . j av a 2 s.c o m*/ 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 ww. jav a 2 s . c o 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); } }