List of usage examples for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder build
public DigestCalculatorProvider build() throws OperatorCreationException
From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java
License:Apache License
private Collection<?> extractCerts(byte[] contents) throws Exception { JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder(); builder.setProvider(CSR_SIGNER_PROVIDER); DigestCalculatorProvider provider = builder.build(); CMSSignedDataParser parser = new CMSSignedDataParser(provider, contents); Store store = parser.getCertificates(); return store.getMatches(certSelector); }
From source file:mitm.common.security.smime.SMIMEBuilderImpl.java
License:Open Source License
private void addSigner(PrivateKey privateKey, X509Certificate signer, SMIMESigningAlgorithm algorithm, AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException { try {/*from w w w . j a v a2 s . c o m*/ JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder(); digestBuilder.setProvider(nonSensitiveProvider); SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build()); if (signedAttr != null) { signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr)); } if (unsignedAttr != null) { signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr)); } JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm()); contentSignerBuilder.setProvider(sensitiveProvider); SignerInfoGenerator signerInfoGenerator = signerInfoBuilder .build(contentSignerBuilder.build(privateKey), new JcaX509CertificateHolder(signer)); signedGenerator.addSignerInfoGenerator(signerInfoGenerator); } catch (OperatorCreationException e) { throw new SMIMEBuilderException(e); } catch (CertificateEncodingException e) { throw new SMIMEBuilderException(e); } }
From source file:mitm.common.security.smime.SMIMEBuilderImpl.java
License:Open Source License
public void addSigner(PrivateKey privateKey, byte[] subjectKeyIdentifier, SMIMESigningAlgorithm algorithm, AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException { try {/*from ww w. j a v a2s .c o m*/ JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder(); digestBuilder.setProvider(nonSensitiveProvider); SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build()); if (signedAttr != null) { signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr)); } if (unsignedAttr != null) { signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr)); } JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm()); contentSignerBuilder.setProvider(sensitiveProvider); SignerInfoGenerator signerInfoGenerator = signerInfoBuilder .build(contentSignerBuilder.build(privateKey), subjectKeyIdentifier); signedGenerator.addSignerInfoGenerator(signerInfoGenerator); } catch (OperatorCreationException e) { throw new SMIMEBuilderException(e); } }
From source file:nu.yona.server.subscriptions.rest.AppleMobileConfigSigner.java
License:Mozilla Public License
private SignerInfoGenerator createSignerInfoGenerator() { try {// w ww. jav a2 s . c o m ContentSigner sha1Signer = createContentSigner(); JcaDigestCalculatorProviderBuilder digestProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider("BC"); JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder( digestProviderBuilder.build()); return signerInfoGeneratorBuilder.build(sha1Signer, signerCertificate); } catch (CertificateException | OperatorCreationException e) { throw YonaException.unexpected(e); } }
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 w w w.ja va2 s . co m*/ 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.codice.ddf.security.ocsp.checker.OcspChecker.java
License:Open Source License
/** * Creates an {@link OCSPReq} to send to the OCSP server for the given certificate. * * @param cert - the certificate to verify * @return the created OCSP request/*from ww w . j a va 2 s . c o m*/ * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs */ @VisibleForTesting OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException { try { X509CertificateHolder issuerCert = resolveIssuerCertificate(cert); JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder(); DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build(); DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1); CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue()); OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder(); ocspReqGenerator.addRequest(certId); return ocspReqGenerator.build(); } catch (OCSPException | OperatorCreationException e) { throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e); } }
From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java
License:Open Source License
@SuppressWarnings("unchecked") private static CMSValidationResult validateCMS(final CMSSignedData signedData, final Collection<Certificate> trustedCerts) { final CMSValidationResult result = new CMSValidationResult(); try {//from w w w . j a v a 2 s . co m final ContentInfo ci = signedData.toASN1Structure(); if (LOG.isDebugEnabled()) { LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: " + signedData.getSignedContent()); } final Object content = signedData.getSignedContent().getContent(); if (content instanceof byte[]) { result.setContent((byte[]) content); } Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); for (Object o : signers.getSigners()) { if (o instanceof SignerInformation) { SignerInformation si = (SignerInformation) o; if (LOG.isDebugEnabled()) { LOG.debug("*** SIGNATURE: " + "\n" + si.getSID()); } final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs .getMatches(si.getSID()); if (LOG.isDebugEnabled()) { LOG.debug("signerCerts: " + signerCerts); } JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); for (X509CertificateHolder signerCert : signerCerts) { final X509Certificate signerX509Cert = jcaX509CertificateConverter .getCertificate(signerCert); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean consistent = si .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey())); if (consistent) { if (LOG.isDebugEnabled()) { LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from " + signerX509Cert.getSubjectDN() + " issued by " + signerX509Cert.getIssuerDN()); } result.setValidSignature(consistent); try { final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs, trustedCerts); result.setValidChain(true); result.setSignerChain(signerChain); JOptionPane.showMessageDialog(null, "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"", "Signature check", JOptionPane.INFORMATION_MESSAGE); } catch (CertPathBuilderException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (CertPathValidatorException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, "Error: Certificate validation:\n" + ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (InvalidAlgorithmParameterException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (NoSuchAlgorithmException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (GeneralSecurityException e) { //Crappy catch-all, but not much to do due to underlying BC-code result.setError(e.getMessage()); JOptionPane.showMessageDialog(null, e.getMessage(), "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE); } } else { result.setError("Inconsistent signature!"); JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check", JOptionPane.ERROR_MESSAGE); } } } } } catch (CMSException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } catch (OperatorCreationException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } catch (CertificateException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } return result; }
From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java
License:Open Source License
@Override public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken, final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException { if (log.isTraceEnabled()) { log.trace(">extendedService"); }/* w ww . jav a 2 s . c o m*/ if (!(request instanceof CmsCAServiceRequest)) { throw new IllegalExtendedCAServiceRequestException(); } if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) { final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS"); log.error(msg); throw new ExtendedCAServiceNotActiveException(msg); } ExtendedCAServiceResponse returnval = null; final X509Certificate signerCert = (X509Certificate) certificatechain.get(0); final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request; // Create the signed data final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); try { byte[] resp = serviceReq.getDoc(); // Add our signer info and sign the message if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) { final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>(); for (Certificate certificate : certificatechain) { x509CertChain.add((X509Certificate) certificate); } gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain))); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); ASN1ObjectIdentifier oid = AlgorithmTools .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm()); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(BouncyCastleProvider.PROVIDER_NAME); ContentSigner contentSigner = signerBuilder.build(privKey); gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert)); final CMSTypedData msg = new CMSProcessableByteArray(resp); final CMSSignedData s = gen1.generate(msg, true); resp = s.getEncoded(); } if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate()) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp), jceCMSContentEncryptorBuilder.build()); resp = ed.getEncoded(); } if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) { final CMSEnvelopedData ed = new CMSEnvelopedData(resp); final RecipientInformationStore recipients = ed.getRecipientInfos(); final X500Name issuer = X500Name .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded()); final KeyTransRecipientId id = new KeyTransRecipientId(issuer, getCMSCertificate().getSerialNumber()); final RecipientInformation recipient = recipients.get(id); if (recipient != null) { JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey); // Provider for decrypting the symmetric key rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); rec.setProvider(cryptoToken.getSignProviderName()); // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below resp = recipient.getContent(rec); } } returnval = new CmsCAServiceResponse(resp); } catch (CMSException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (IOException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (OperatorCreationException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (CertificateEncodingException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } if (log.isTraceEnabled()) { log.trace("<extendedService"); } return returnval; }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
License:Open Source License
private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId, boolean crlRep, String digestOid, boolean noca) throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // Parse response message ///* w w w. j av a 2s . c o m*/ CMSSignedData s = new CMSSignedData(retMsg); // The signer, i.e. the CA, check it's the right CA SignerInformationStore signers = s.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> col = signers.getSigners(); assertTrue(col.size() > 0); Iterator<SignerInformation> iter = col.iterator(); SignerInformation signerInfo = iter.next(); // Check that the message is signed with the correct digest alg assertEquals(signerInfo.getDigestAlgOID(), digestOid); SignerId sinfo = signerInfo.getSID(); // Check that the signer is the expected CA assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuer().toString())); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey())); assertTrue(ret); // Get authenticated attributes AttributeTable tab = signerInfo.getSignedAttributes(); // --Fail info Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo)); // No failInfo on this success message assertNull(attr); // --Message type attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType)); assertNotNull(attr); ASN1Set values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0))); String messageType = str.getString(); assertEquals("3", messageType); // --Success status attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString()); // --SenderNonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // SenderNonce is something the server came up with, but it should be 16 // chars assertTrue(octstr.getOctets().length == 16); // --Recipient Nonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // recipient nonce should be the same as we sent away as sender nonce assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets()))); // --Transaction ID attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); // transid should be the same as the one we sent assertEquals(_transId, str.getString()); // // Check different message types // if (messageType.equals("3")) { // First we extract the encrypted data from the CMS enveloped data // contained // within the CMS signed data final CMSProcessable sp = s.getSignedContent(); final byte[] content = (byte[]) sp.getContent(); final CMSEnvelopedData ed = new CMSEnvelopedData(content); final RecipientInformationStore recipients = ed.getRecipientInfos(); Store certstore; @SuppressWarnings("unchecked") Collection<RecipientInformation> c = recipients.getRecipients(); assertEquals(c.size(), 1); Iterator<RecipientInformation> riIterator = c.iterator(); byte[] decBytes = null; RecipientInformation recipient = riIterator.next(); JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate()); rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); decBytes = recipient.getContent(rec); // This is yet another CMS signed data CMSSignedData sd = new CMSSignedData(decBytes); // Get certificates from the signed data certstore = sd.getCertificates(); if (crlRep) { // We got a reply with a requested CRL @SuppressWarnings("unchecked") final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null); assertEquals(crls.size(), 1); final Iterator<X509CRLHolder> it = crls.iterator(); // CRL is first (and only) final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next()); log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName()); // check the returned CRL assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl)); retCrl.verify(cacert.getPublicKey()); } else { // We got a reply with a requested certificate @SuppressWarnings("unchecked") final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore .getMatches(null); // EJBCA returns the issued cert and the CA cert (cisco vpn // client requires that the ca cert is included) if (noca) { assertEquals(certs.size(), 1); } else { assertEquals(certs.size(), 2); } final Iterator<X509CertificateHolder> it = certs.iterator(); // Issued certificate must be first boolean verified = false; boolean gotcacert = false; JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); while (it.hasNext()) { X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next()); log.info("Got cert with DN: " + retcert.getSubjectDN().getName()); // check the returned certificate String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) { // issued certificate assertEquals(CertTools.stringToBCDNString(userDN), subjectdn); assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert)); retcert.verify(cacert.getPublicKey()); assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey())); verified = true; } else { // ca certificate assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert)); gotcacert = true; } } assertTrue(verified); if (noca) { assertFalse(gotcacert); } else { assertTrue(gotcacert); } } } }
From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java
License:Open Source License
@Override public boolean create() throws CertificateEncodingException, CRLException { boolean ret = false; try {/*from www .j a v a2s. c o m*/ if (status.equals(ResponseStatus.SUCCESS)) { log.debug("Creating a STATUS_OK message."); } else { if (status.equals(ResponseStatus.FAILURE)) { log.debug("Creating a STATUS_FAILED message (or returning false)."); if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) { return false; } if (failInfo.equals(FailInfo.INCORRECT_DATA)) { return false; } } else { log.debug("Creating a STATUS_PENDING message."); } } CMSTypedData msg; // Create encrypted response if this is success and NOT a CRL response message if (status.equals(ResponseStatus.SUCCESS)) { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case) List<X509Certificate> certList = new ArrayList<X509Certificate>(); if (cert != null) { log.debug("Adding certificates to response message"); certList.add((X509Certificate) cert); // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there if (includeCACert) { if (caCert != null) { // If we have an explicit CAcertificate log.debug("Including explicitly set CA certificate in SCEP response."); certList.add((X509Certificate) caCert); } else { // If we don't have an explicit caCert, we think that the signCert is the CA cert // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one log.debug("Including message signer certificate in SCEP response."); certList.add((X509Certificate) signCertChain.iterator().next()); } } } // Create the signed CMS message to be contained inside the envelope // this message does not contain any message, and no signerInfo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList))); if (crl != null) { gen.addCRL(new JcaX509CRLHolder((X509CRL) crl)); } CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // Envelope the CMS message if (recipientKeyInfo != null) { try { X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo); log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec) + "', serno: '" + CertTools.getSerialNumberAsString(rec)); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } catch (CertificateParsingException e) { throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e); } } else { edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } try { JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()), jceCMSContentEncryptorBuilder.build()); if (log.isDebugEnabled()) { log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long"); } msg = new CMSProcessableByteArray(ed.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught", e); } } else { // Create an empty message here //msg = new CMSProcessableByteArray("PrimeKey".getBytes()); msg = new CMSProcessableByteArray(new byte[0]); } // Create the outermost signed data CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); // add authenticated attributes...status, transactionId, sender- and recipientNonce and more... Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>(); ASN1ObjectIdentifier oid; Attribute attr; DERSet value; // Message type (certrep) oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType); value = new DERSet(new DERPrintableString("3")); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); // TransactionId if (transactionId != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId); log.debug("Added transactionId: " + transactionId); value = new DERSet(new DERPrintableString(transactionId)); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // status oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus); value = new DERSet(new DERPrintableString(status.getStringValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); if (status.equals(ResponseStatus.FAILURE)) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo); log.debug("Added failInfo: " + failInfo.getValue()); value = new DERSet(new DERPrintableString(failInfo.getValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // senderNonce if (senderNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce); log.debug("Added senderNonce: " + senderNonce); value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // recipientNonce if (recipientNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce); log.debug("Added recipientNonce: " + recipientNonce); value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // Add our signer info and sign the message Certificate cacert = signCertChain.iterator().next(); log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert)); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg, signKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(provider).build(signKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); builder.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes))); gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert)); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } // The un-encoded response message itself final CMSSignedData signedData = gen1.generate(msg, true); try { responseMessage = signedData.getEncoded(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught.", e); } if (responseMessage != null) { ret = true; } } catch (CMSException e) { log.error("Error creating CMS message: ", e); } return ret; }