org.bouncycastle.util.Store Java Examples
The following examples show how to use
org.bouncycastle.util.Store.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BouncyCastleCrypto.java From tutorials with MIT License | 6 votes |
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException { ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ASN1InputStream aIn = new ASN1InputStream(bIn); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); aIn.close(); bIn.close(); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); SignerInformation signer = c.iterator().next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); if (!verifResult) { return false; } return true; }
Example #2
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 6 votes |
/** * Creates the beast that can actually sign the data (for JKS, for other make it). */ public static CMSSignedDataGenerator createSignedDataGenerator(KeyStore keyStore, String keyAlias, String signAlgo, String keyPassword) throws KeyStoreException, OperatorCreationException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, CMSException { List<Certificate> certChain = new ArrayList<>(Arrays.asList(keyStore.getCertificateChain(keyAlias))); @SuppressWarnings("rawtypes") Store certStore = new JcaCertStore(certChain); Certificate cert = keyStore.getCertificate(keyAlias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword != null ? keyPassword.toCharArray() : null); ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert); generator.addSignerInfoGenerator(sig); generator.addCertificates(certStore); return generator; }
Example #3
Source File: CMSOCSPSource.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void addBasicOcspRespFrom_id_pkix_ocsp_basic() { final Store otherRevocationInfo = cmsSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic); final Collection otherRevocationInfoMatches = otherRevocationInfo.getMatches(null); for (final Object object : otherRevocationInfoMatches) { if (object instanceof ASN1Sequence) { final ASN1Sequence otherRevocationInfoMatch = (ASN1Sequence) object; final BasicOCSPResp basicOCSPResp = DSSRevocationUtils.getBasicOcspResp(otherRevocationInfoMatch); if (basicOCSPResp != null) { OCSPResponseBinary ocspResponseIdentifier = OCSPResponseBinary.build(basicOCSPResp); ocspResponseIdentifier.setAsn1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp_basic); addBinary(ocspResponseIdentifier, RevocationOrigin.CMS_SIGNED_DATA); } else { LOG.warn("Unable to create an OCSP response from an objects. The entry is skipped."); } } else { LOG.warn("Unsupported object type for id_pkix_ocsp_basic (SHALL be an ASN1Sequence) : {}", object.getClass().getSimpleName()); } } }
Example #4
Source File: CMSOCSPSource.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void addBasicOcspRespFrom_id_ri_ocsp_response() { final Store otherRevocationInfo = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response); final Collection otherRevocationInfoMatches = otherRevocationInfo.getMatches(null); for (final Object object : otherRevocationInfoMatches) { if (object instanceof ASN1Sequence) { final ASN1Sequence otherRevocationInfoMatch = (ASN1Sequence) object; final BasicOCSPResp basicOCSPResp; if (otherRevocationInfoMatch.size() == 4) { basicOCSPResp = DSSRevocationUtils.getBasicOcspResp(otherRevocationInfoMatch); } else { final OCSPResp ocspResp = DSSRevocationUtils.getOcspResp(otherRevocationInfoMatch); basicOCSPResp = DSSRevocationUtils.fromRespToBasic(ocspResp); } OCSPResponseBinary ocspResponseIdentifier = OCSPResponseBinary.build(basicOCSPResp); ocspResponseIdentifier.setAsn1ObjectIdentifier(CMSObjectIdentifiers.id_ri_ocsp_response); addBinary(ocspResponseIdentifier, RevocationOrigin.CMS_SIGNED_DATA); } else { LOG.warn("Unsupported object type for id_ri_ocsp_response (SHALL be an ASN1Sequence) : {}", object.getClass().getSimpleName()); } } }
Example #5
Source File: CMSSignedDataBuilder.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@SuppressWarnings("rawtypes") protected CMSSignedData regenerateCMSSignedData(CMSSignedData cmsSignedData, List<DSSDocument> detachedContents, Store certificatesStore, Store attributeCertificatesStore, Store crlsStore, Store otherRevocationInfoFormatStoreBasic, Store otherRevocationInfoFormatStoreOcsp) { try { final CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator(); cmsSignedDataGenerator.addSigners(cmsSignedData.getSignerInfos()); cmsSignedDataGenerator.addAttributeCertificates(attributeCertificatesStore); cmsSignedDataGenerator.addCertificates(certificatesStore); cmsSignedDataGenerator.addCRLs(crlsStore); cmsSignedDataGenerator.addOtherRevocationInfo(id_pkix_ocsp_basic, otherRevocationInfoFormatStoreBasic); cmsSignedDataGenerator.addOtherRevocationInfo(id_ri_ocsp_response, otherRevocationInfoFormatStoreOcsp); final boolean encapsulate = cmsSignedData.getSignedContent() != null; if (!encapsulate) { // CAdES can only sign one document final DSSDocument doc = detachedContents.get(0); final CMSTypedData content = CMSUtils.getContentToBeSign(doc); cmsSignedData = cmsSignedDataGenerator.generate(content, encapsulate); } else { cmsSignedData = cmsSignedDataGenerator.generate(cmsSignedData.getSignedContent(), encapsulate); } return cmsSignedData; } catch (CMSException e) { throw new DSSException(e); } }
Example #6
Source File: CreateMultipleVisualizations.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * Copy of <code>org.apache.pdfbox.examples.signature.CreateSignatureBase.sign(InputStream)</code> * from the pdfbox examples artifact. */ @Override public byte[] sign(InputStream content) throws IOException { try { List<Certificate> certList = new ArrayList<>(); certList.addAll(Arrays.asList(chain)); Store<?> certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(chain[0].getEncoded()); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(pk); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert))); gen.addCertificates(certs); CMSProcessableInputStream msg = new CMSProcessableInputStream(content); CMSSignedData signedData = gen.generate(msg, false); return signedData.getEncoded(); } catch (GeneralSecurityException | CMSException | OperatorCreationException e) { throw new IOException(e); } }
Example #7
Source File: CAdESSigner.java From signer with GNU Lesser General Public License v3.0 | 6 votes |
private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) { Collection<X509Certificate> result = new HashSet<X509Certificate>(); Store<?> certStore = previewSignerData.getCertificates(); SignerInformationStore signers = previewSignerData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); try { result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder)); } catch (CertificateException error) { } } return result; }
Example #8
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException { Store<X509CertificateHolder> certs = signedData.getCertificates(); Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector()); Iterator iterator = certCollection.iterator(); while(iterator.hasNext()) { result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next())); } }
Example #9
Source File: BouncyCastleCrypto.java From tutorials with MIT License | 5 votes |
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException { byte[] signedMessage = null; List<X509Certificate> certList = new ArrayList<X509Certificate>(); CMSTypedData cmsData = new CMSProcessableByteArray(data); certList.add(signingCertificate); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate)); cmsGenerator.addCertificates(certs); CMSSignedData cms = cmsGenerator.generate(cmsData, true); signedMessage = cms.getEncoded(); return signedMessage; }
Example #10
Source File: SignatureBlockGenerator.java From fdroidclient with GNU General Public License v3.0 | 5 votes |
/** * Sign the given content using the private and public keys from the keySet, and return the encoded CMS (PKCS#7) data. * Use of direct signature and DER encoding produces a block that is verifiable by Android recovery programs. */ public static byte[] generate(KeySet keySet, byte[] content) { try { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray(content); certList.add(keySet.getPublicKey()); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(keySet.getSignatureAlgorithm()).setProvider("BC"); ContentSigner sha1Signer = jcaContentSignerBuilder.build(keySet.getPrivateKey()); JcaDigestCalculatorProviderBuilder jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC"); DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build(); JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider); jcaSignerInfoGeneratorBuilder.setDirectSignature(true); SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.getPublicKey()); gen.addSignerInfoGenerator(signerInfoGenerator); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(msg, false); return sigData.toASN1Structure().getEncoded("DER"); } catch (Exception x) { throw new RuntimeException(x.getMessage(), x); } }
Example #11
Source File: CMSCRLSource.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private void collectFromSignedData() { final Store<X509CRLHolder> crLs = cmsSignedData.getCRLs(); final Collection<X509CRLHolder> collection = crLs.getMatches(null); for (final X509CRLHolder x509CRLHolder : collection) { addX509CRLHolder(x509CRLHolder, RevocationOrigin.CMS_SIGNED_DATA); } }
Example #12
Source File: CMSSignedDataBuilder.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
/** * Note: * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS * SignedData version is required to be set to 1. * CMS SignedData Version is handled automatically by BouncyCastle. * * @param parameters * set of the driving signing parameters * @param contentSigner * the contentSigner to get the hash of the data to be signed * @param signerInfoGeneratorBuilder * the builder for the signer info generator * @param originalSignedData * the original signed data if extending an existing signature. null otherwise. * @return the bouncycastle signed data generator which signs the document and adds the required signed and unsigned * CMS attributes * @throws eu.europa.esig.dss.model.DSSException */ protected CMSSignedDataGenerator createCMSSignedDataGenerator(final CAdESSignatureParameters parameters, final ContentSigner contentSigner, final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder, final CMSSignedData originalSignedData) throws DSSException { try { final CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); final SignerInfoGenerator signerInfoGenerator = getSignerInfoGenerator(signerInfoGeneratorBuilder, contentSigner, parameters); generator.addSignerInfoGenerator(signerInfoGenerator); final List<CertificateToken> certificateChain = new LinkedList<>(); if (originalSignedData != null) { generator.addSigners(originalSignedData.getSignerInfos()); generator.addAttributeCertificates(originalSignedData.getAttributeCertificates()); generator.addCRLs(originalSignedData.getCRLs()); generator.addOtherRevocationInfo(id_pkix_ocsp_basic, originalSignedData.getOtherRevocationInfo(id_pkix_ocsp_basic)); generator.addOtherRevocationInfo(id_ri_ocsp_response, originalSignedData.getOtherRevocationInfo(id_ri_ocsp_response)); final Store<X509CertificateHolder> certificates = originalSignedData.getCertificates(); final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null); for (final X509CertificateHolder certificatesMatch : certificatesMatches) { final CertificateToken token = DSSASN1Utils.getCertificate(certificatesMatch); if (!certificateChain.contains(token)) { certificateChain.add(token); } } } final JcaCertStore jcaCertStore = getJcaCertStore(certificateChain, parameters); generator.addCertificates(jcaCertStore); return generator; } catch (CMSException | OperatorCreationException e) { throw new DSSException(e); } }
Example #13
Source File: CMSSignedDataWrapper.java From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 | 5 votes |
public void addCrl(Store<X509CRL> crlStore) throws Exception { if (crlStore == null) return; Collection<X509CRL> crlStoreList = crlStore.getMatches(null); for (X509CRL crl : crlStoreList) addCert(crl.getEncoded()); }
Example #14
Source File: CMSSignedDataWrapper.java From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 | 5 votes |
public void addCert(Store<X509CertificateHolder> certStore) throws Exception { if (certStore == null) return; Collection<X509CertificateHolder> certStoreList = certStore.getMatches(null); for (X509CertificateHolder cert : certStoreList) addCert(cert.getEncoded()); }
Example #15
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 5 votes |
public static CMSSignedDataGenerator createSignedDataGenerator(PrivateKey privateKey, Certificate cert, List<Certificate> certChain, String signAlgo) throws OperatorCreationException, CertificateEncodingException, CMSException { @SuppressWarnings("rawtypes") Store certStore = new JcaCertStore(certChain); ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert); generator.addSignerInfoGenerator(sig); generator.addCertificates(certStore); return generator; }
Example #16
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException { Store<X509CertificateHolder> certs = signedData.getCertificates(); Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector()); Iterator iterator = certCollection.iterator(); while(iterator.hasNext()) { result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next())); } }
Example #17
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException { Store<X509CertificateHolder> certs = signedData.getCertificates(); Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector()); Iterator iterator = certCollection.iterator(); while(iterator.hasNext()) { result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next())); } }
Example #18
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException { Store<X509CertificateHolder> certs = signedData.getCertificates(); Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector()); Iterator iterator = certCollection.iterator(); while(iterator.hasNext()) { result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next())); } }
Example #19
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException { Store<X509CertificateHolder> certs = signedData.getCertificates(); Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector()); Iterator iterator = certCollection.iterator(); while(iterator.hasNext()) { result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next())); } }
Example #20
Source File: Timestamp.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
public Store<?> getCRLs() { return timeStampToken.getCRLs(); }
Example #21
Source File: Timestamp.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
public Store<?> getCertificates() { return timeStampToken.getCertificates(); }
Example #22
Source File: RequestSigner.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
/** * Signs a time stamp request * * @param privateKey private key to sign with * @param certificates certificate chain * @param request request to be signed * @return The signed request */ public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) { try { logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request")); Security.addProvider(new BouncyCastleProvider()); X509Certificate signCert = (X509Certificate) certificates[0]; List<X509Certificate> certList = new ArrayList<>(); certList.add(signCert); // setup the generator CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); String varAlgorithm = null; if (algorithm != null && !algorithm.isEmpty()){ varAlgorithm = algorithm; }else{ // If is WINDOWS, is ONLY WORKS with SHA256 if (Configuration.getInstance().getSO().toLowerCase().indexOf("indows") > 0) { logger.info(timeStampMessagesBundle.getString("info.timestamp.winhash")); varAlgorithm = "SHA256withRSA"; }else{ logger.info(timeStampMessagesBundle.getString("info.timestamp.linuxhash")); varAlgorithm = "SHA512withRSA"; } } SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert); generator.addSignerInfoGenerator(signerInfoGenerator); Store<?> certStore = new JcaCertStore(certList); generator.addCertificates(certStore); // Store crlStore = new JcaCRLStore(crlList); // generator.addCRLs(crlStore); // Create the signed data object CMSTypedData data = new CMSProcessableByteArray(request); CMSSignedData signed = generator.generate(data, true); return signed.getEncoded(); } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) { logger.info(ex.getMessage()); } return null; }
Example #23
Source File: CreateSignature.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest"> * Create pkcs7 signature from file digest * </a> * <p> * The OP's own <code>sign</code> method which has some errors. These * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}. * </p> */ public byte[] signBySnox(InputStream content) throws IOException { // testSHA1WithRSAAndAttributeTable try { MessageDigest md = MessageDigest.getInstance("SHA1", "BC"); List<Certificate> certList = new ArrayList<Certificate>(); CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content)); certList.addAll(Arrays.asList(chain)); Store<?> certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content))))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(chain[0].getEncoded()); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); gen.addSignerInfoGenerator(builder.build( new BcRSAContentSignerBuilder(sha1withRSA, new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA)) .build(PrivateKeyFactory.createKey(pk.getEncoded())), new JcaX509CertificateHolder(cert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); return new CMSSignedData(msg, s.getEncoded()).getEncoded(); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
Example #24
Source File: SMimePackageEncryptor.java From ats-framework with Apache License 2.0 | 4 votes |
@PublicAtsApi public Package sign( Package sourcePackage ) throws ActionException { try { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } KeyStore ks = getKeystore(); // TODO wrap exception with possible causes and add some hint PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray()); // Get whole certificate chain Certificate[] certArr = ks.getCertificateChain(aliasOrCN); // Pre 4.0.6 behavior was not to attach full cert. chain X509Certificate cer = (X509Certificate) ks.getCertificate(aliasOrCN); if (certArr.length >= 1) { LOG.debug("Found certificate of alias: " + aliasOrCN + ". Lenght of cert chain: " + certArr.length + ", child cert:" + certArr[0].toString()); } X509Certificate childCert = (X509Certificate) certArr[0]; /* Create the SMIMESignedGenerator */ ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(childCert.getIssuerDN() .getName()), childCert.getSerialNumber()))); SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.aES128_CBC); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); if (signatureAlgorithm == null) { // not specified explicitly // TODO check defaults to be used signatureAlgorithm = SignatureAlgorithm.DSA.equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA"; } SMIMESignedGenerator signer = new SMIMESignedGenerator(); JcaSimpleSignerInfoGeneratorBuilder signerGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder(); signerGeneratorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); signerGeneratorBuilder.setSignedAttributeGenerator(new AttributeTable(attributes)); signer.addSignerInfoGenerator(signerGeneratorBuilder.build(signatureAlgorithm, privateKey, childCert)); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); for (int i = 0; i < certArr.length; i++) { // first add child cert, and CAs certList.add((X509Certificate) certArr[i]); } Store<?> certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ Session session = Session.getDefaultInstance(System.getProperties(), null); MimeMultipart mm = signer.generate(getMimeMessage(sourcePackage)); MimeMessage signedMessage = new MimeMessage(session); /* Set all original MIME headers in the signed message */ Enumeration<?> headers = getMimeMessage(sourcePackage).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); return new MimePackage(signedMessage); } catch (Exception e) { throw new ActionException(EXCEPTION_WHILE_SIGNING, e); } }
Example #25
Source File: CMSSignedDataBuilder.java From dss with GNU Lesser General Public License v2.1 | 4 votes |
/** * Extends the provided {@code cmsSignedData} with the required validation data * @param cmsSignedData {@link CMSSignedData} to be extended * @param validationDataForInclusion the {@link ValidationDataForInclusion} to be included into the cmsSignedData * @param detachedContents list of detached {@link DSSDocument}s * @return extended {@link CMSSignedData} */ @SuppressWarnings({ "unchecked", "rawtypes" }) public CMSSignedData extendCMSSignedData(CMSSignedData cmsSignedData, ValidationDataForInclusion validationDataForInclusion, List<DSSDocument> detachedContents) { Store<X509CertificateHolder> certificatesStore = cmsSignedData.getCertificates(); final Set<CertificateToken> certificates = validationDataForInclusion.getCertificateTokens(); final Collection<X509CertificateHolder> newCertificateStore = new HashSet<>(certificatesStore.getMatches(null)); for (final CertificateToken certificateToken : certificates) { final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(certificateToken); newCertificateStore.add(x509CertificateHolder); } certificatesStore = new CollectionStore<>(newCertificateStore); Store<X509CRLHolder> crlsStore = cmsSignedData.getCRLs(); final Collection<X509CRLHolder> newCrlsStore = new HashSet<>(crlsStore.getMatches(null)); final List<CRLToken> crlTokens = validationDataForInclusion.getCrlTokens(); for (final CRLToken crlToken : crlTokens) { final X509CRLHolder x509CRLHolder = getX509CrlHolder(crlToken); newCrlsStore.add(x509CRLHolder); } crlsStore = new CollectionStore<>(newCrlsStore); Store otherRevocationInfoFormatStoreBasic = cmsSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic); final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<>(otherRevocationInfoFormatStoreBasic.getMatches(null)); final List<OCSPToken> ocspTokens = validationDataForInclusion.getOcspTokens(); for (final OCSPToken ocspToken : ocspTokens) { final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp(); if (basicOCSPResp != null) { newOtherRevocationInfoFormatStore.add(DSSASN1Utils.toASN1Primitive(DSSASN1Utils.getEncoded(basicOCSPResp))); } } otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore); Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates(); Store otherRevocationInfoFormatStoreOcsp = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response); final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier); cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, detachedContents, certificatesStore, attributeCertificatesStore, crlsStore, otherRevocationInfoFormatStoreBasic, otherRevocationInfoFormatStoreOcsp); return cmsSignedData; }
Example #26
Source File: RsaSsaPss.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * For some tests I needed SHA256withRSAandMGF1 CMS signatures. */ @Test public void testCreateSimpleSignatureContainer() throws CMSException, GeneralSecurityException, OperatorCreationException, IOException { byte[] message = "SHA256withRSAandMGF1".getBytes(); CMSTypedData msg = new CMSProcessableByteArray(message); List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSAandMGF1").setProvider("BC").build(signKP.getPrivate()); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha1Signer, signCert)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(msg, false); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.bin").toPath(), message); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.p7s").toPath(), sigData.getEncoded()); boolean verifies = sigData.verifySignatures(new SignerInformationVerifierProvider() { @Override public SignerInformationVerifier get(SignerId sid) throws OperatorCreationException { if (sid.getSerialNumber().equals(origCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for OrigCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(origCert); } if (sid.getSerialNumber().equals(signCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for SignCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(signCert); } System.out.println("SignerInformationVerifier requested for unknown " + sid); return null; } }); System.out.println("Verifies? " + verifies); }
Example #27
Source File: CounterSignatureValidationTest.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
@Override protected DSSDocument getSignedDocument() { FileDocument fileDocument = new FileDocument("src/test/resources/validation/counterSig.p7m"); try (InputStream is = fileDocument.openStream()) { CMSSignedData cms = new CMSSignedData(is); Collection<SignerInformation> signers = cms.getSignerInfos().getSigners(); assertEquals(1, signers.size()); Store<X509CertificateHolder> certificates = cms.getCertificates(); SignerInformation signerInformation = signers.iterator().next(); Collection<X509CertificateHolder> matches = certificates.getMatches(signerInformation.getSID()); X509CertificateHolder cert = matches.iterator().next(); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert); assertTrue(signerInformation.verify(verifier)); SignerInformationStore counterSignatures = signerInformation.getCounterSignatures(); for (SignerInformation counterSigner : counterSignatures) { Collection<X509CertificateHolder> matchesCounter = certificates.getMatches(counterSigner.getSID()); X509CertificateHolder counterCert = matchesCounter.iterator().next(); SignerInformationVerifier counterVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(counterCert); assertTrue(counterSigner.verify(counterVerifier)); } } catch (Exception e) { fail(e); } return fileDocument; }