List of usage examples for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder
public JcaDigestCalculatorProviderBuilder()
From source file:org.eclipse.andmore.android.certmanager.packaging.sign.SignatureBlockFile.java
License:Apache License
/** * Writes this file to an output stream//www. j ava 2 s. com * * @param outputStream * the output stream to write the file * @throws IOException * if an I/O error occurs during the signing process * @throws SignException * if a processing error occurs during the signing process * @throws KeyStoreManagerException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws CertificateEncodingException * @throws OperatorCreationException * @throws CMSException */ public void write(OutputStream outputStream) throws IOException, SignException, UnrecoverableKeyException, KeyStoreException, KeyStoreManagerException, NoSuchAlgorithmException, InvalidKeyException, CertificateEncodingException, OperatorCreationException, CMSException { // get certificate from entry X509Certificate[] certChain = { keystoreEntry.getX509Certificate() }; if (certChain.length > 0) { X509Certificate publicKey = certChain[0]; PrivateKey privateKey = keystoreEntry.getPrivateKey(keyEntryPassword); String blockalgorithm = getBlockAlgorithm(); if (!blockalgorithm.equalsIgnoreCase(ISignConstants.DSA) && !blockalgorithm.equalsIgnoreCase(ISignConstants.RSA)) { AndmoreLogger.error(SignatureBlockFile.class, "Signing block algorithm not supported. Key algorithm must be DSA or RSA"); throw new SignException("Signing block algorithm not supported"); } String signatureAlgorithm = ISignConstants.SHA1 + ISignConstants.ALGORITHM_CONNECTOR + blockalgorithm; Security.addProvider(new BouncyCastleProvider()); ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(signer, publicKey)); generator.addCertificates(certs); ByteArrayOutputStream baos = new ByteArrayOutputStream(); signatureFile.write(baos); CMSTypedData cmsdata = new CMSProcessableByteArray(baos.toByteArray()); CMSSignedData signeddata = generator.generate(cmsdata, false); ASN1InputStream asn1 = new ASN1InputStream(signeddata.getEncoded()); DEROutputStream dos = new DEROutputStream(outputStream); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); } AndmoreLogger.info(SignatureBlockFile.class, "Created signature block file"); }
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 va 2 s .c o 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"); }/*from w ww . java 2s .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 . jav a 2 s. 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 {//w w w. ja va2 s. c om 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; }
From source file:org.ejbca.util.CMS.java
License:Open Source License
/** * @param is data to be signed//w ww. j a v a 2 s.c o m * @param os signed data * @param key to do be used for signing * @param providerName the provider that should do the signing * @throws Exception */ public static void sign(final InputStream is, OutputStream os, PrivateKey key, String providerName, X509Certificate cert) throws Exception { final InputStream bis = new BufferedInputStream(is, bufferSize); final OutputStream bos = new BufferedOutputStream(os, bufferSize); final CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); final String digest = CMSSignedGenerator.DIGEST_SHA256; String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digest, key.getAlgorithm()); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName).setProvider(providerName) .build(key); if (cert != null) { gen.addSignerInfoGenerator(builder.build(contentSigner, cert)); } else { gen.addSignerInfoGenerator(builder.build(contentSigner, "hej".getBytes())); } final OutputStream out = gen.open(bos, true); fromInToOut(bis, out); bos.close(); os.close(); }
From source file:org.ejbca.util.CMS.java
License:Open Source License
/** * @param is signed data to be verified//from w ww. ja v a2s . co m * @param os signature removed from signed data * @param cert the certificate with the public key that should do the verification * @return true if the signing was to with the private key corresponding to the public key in the certificate. * @throws Exception */ public static VerifyResult verify(final InputStream is, OutputStream os, X509Certificate cert) throws Exception { final InputStream bis = new BufferedInputStream(is, bufferSize); final OutputStream bos = new BufferedOutputStream(os, bufferSize); final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), bis); final CMSTypedStream sc = sp.getSignedContent(); final InputStream ris = sc.getContentStream(); fromInToOut(ris, bos); os.close(); sc.drain(); @SuppressWarnings("rawtypes") final Iterator it = sp.getSignerInfos().getSigners().iterator(); if (!it.hasNext()) { return null; } final SignerInformation signerInfo = (SignerInformation) it.next(); final Attribute attribute = (Attribute) signerInfo.getSignedAttributes().getAll(CMSAttributes.signingTime) .get(0); final Date date = Time.getInstance(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()).getDate(); final SignerId id = signerInfo.getSID(); boolean result = false; try { JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); result = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cert.getPublicKey())); } catch (Throwable t) { // NOPMD log.debug("Exception when verifying", t); } return new VerifyResult(date, result, id); }
From source file:org.jivesoftware.openfire.net.OCSPChecker.java
License:Open Source License
@Override public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException { Log.debug("OCSPChecker: check called"); InputStream in = null;/*from w ww.j a v a2s.c om*/ OutputStream out = null; try { // Examine OCSP properties X509Certificate responderCert = null; boolean haveResponderCert = true; //defaults to issuers cert X500Principal responderSubjectName = null; boolean haveIssuerCert = false; // If we set the subject name, we need to find the certificate if (ocspServerSubject != null) { haveResponderCert = false; responderSubjectName = new X500Principal(ocspServerSubject); } X509Certificate issuerCert = null; X509Certificate currCert = (X509Certificate) cert; // Set the issuer certificate if we were passed a chain if (certIndex != 0) { issuerCert = (X509Certificate) (certs[certIndex]); haveIssuerCert = true; if (haveResponderCert) { responderCert = certs[certIndex]; } } if (!haveIssuerCert || !haveResponderCert) { if (!haveResponderCert) { Log.debug("OCSPChecker: Looking for responder's certificate"); } if (!haveIssuerCert) { Log.debug("OCSPChecker: Looking for issuer's certificate"); } // Extract the anchor certs Iterator anchors = pkixParams.getTrustAnchors().iterator(); if (!anchors.hasNext()) { throw new CertPathValidatorException("Must specify at least one trust anchor"); } X500Principal certIssuerName = currCert.getIssuerX500Principal(); while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) { TrustAnchor anchor = (TrustAnchor) anchors.next(); X509Certificate anchorCert = anchor.getTrustedCert(); X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal(); // Check if this anchor cert is the issuer cert if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) { issuerCert = anchorCert; haveIssuerCert = true; //If we have not set the responderCert at this point, set it to the issuer if (haveResponderCert && responderCert == null) { responderCert = anchorCert; Log.debug("OCSPChecker: Responder's certificate = issuer certificate"); } } // Check if this anchor cert is the responder cert if (!haveResponderCert) { if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) { responderCert = anchorCert; haveResponderCert = true; } } } if (issuerCert == null) { //No trust anchor was found matching the issuer throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN()); } // Check cert stores if responder cert has not yet been found if (!haveResponderCert) { Log.debug("OCSPChecker: Searching cert stores for responder's certificate"); if (responderSubjectName != null) { X509CertSelector filter = new X509CertSelector(); filter.setSubject(responderSubjectName.getName()); List<CertStore> certStores = pkixParams.getCertStores(); for (CertStore certStore : certStores) { Iterator i = certStore.getCertificates(filter).iterator(); if (i.hasNext()) { responderCert = (X509Certificate) i.next(); haveResponderCert = true; break; } } } } } // Could not find the responder cert if (!haveResponderCert) { throw new CertPathValidatorException("Cannot find the responder's certificate."); } // Construct an OCSP Request OCSPReqBuilder gen = new OCSPReqBuilder(); CertificateID certID = new CertificateID( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber()); gen.addRequest(certID); OCSPReq ocspRequest = gen.build(); URL url; if (ocspServerUrl != null) { try { url = new URL(ocspServerUrl); } catch (MalformedURLException e) { throw new CertPathValidatorException(e); } } else { throw new CertPathValidatorException("Must set OCSP Server URL"); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); Log.debug("OCSPChecker: connecting to OCSP service at: " + url); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); byte[] bytes = ocspRequest.getEncoded(); con.setRequestProperty("Content-length", String.valueOf(bytes.length)); out = con.getOutputStream(); out.write(bytes); out.flush(); // Check the response if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } in = con.getInputStream(); OCSPResp ocspResponse = new OCSPResp(in); BigInteger serialNumber = currCert.getSerialNumber(); BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject(); try { if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(responderCert.getPublicKey()))) { throw new CertPathValidatorException("OCSP response is not verified"); } } catch (Exception e) { throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex); } SingleResp[] singleResp = brep.getResponses(); boolean foundResponse = false; for (SingleResp resp : singleResp) { CertificateID respCertID = resp.getCertID(); if (respCertID.equals(certID)) { Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good"); foundResponse = true; break; } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked"); throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex); } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown"); throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex); } else { Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized"); throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex); } } } // Check that response applies to the cert that was supplied if (!foundResponse) { throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request."); } } catch (CertPathValidatorException cpve) { throw cpve; } catch (Exception e) { throw new CertPathValidatorException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } if (out != null) { try { out.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } } }
From source file:org.jnotary.crypto.Hasher.java
License:Open Source License
public static byte[] makeHash(ASN1ObjectIdentifier algorithm, byte[] data) throws OperatorCreationException, IOException { DigestCalculatorProvider calcProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); DigestCalculator calc = calcProvider.get(new AlgorithmIdentifier(algorithm)); OutputStream stream = null;//from w ww.j a v a2 s . c o m try { stream = calc.getOutputStream(); stream.write(data); } finally { stream.close(); } return calc.getDigest(); }
From source file:org.jnotary.crypto.Signer.java
License:Open Source License
public byte[] sign(UserKeyStore myStorage, byte[] content, Parameters parameters) throws Exception { CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder(algorithm).setProvider("BC") .build(myStorage.getPrivateKey()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, myStorage.getUserCertificate())); if (parameters.isAddSignerSertificate()) gen.addCertificates(myStorage.getCertStore()); CMSTypedData msg = new CMSProcessableByteArray(content); CMSSignedData sigData = gen.generate(msg, !parameters.isDetached()); return sigData.getEncoded(); }