org.bouncycastle.cms.SignerInformationStore Java Examples

The following examples show how to use org.bouncycastle.cms.SignerInformationStore. 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: CAdESSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #2
Source File: CAdESSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("static-access")
private CMSSignedData updateWithCounterSignature(final CMSSignedData counterSignature,
		final CMSSignedData originalSignature, SignerId selector) {

	// Retrieve the SignerInformation from the countersigned signature
	final SignerInformationStore originalSignerInfos = originalSignature.getSignerInfos();
	// Retrieve the SignerInformation from the countersignature
	final SignerInformationStore signerInfos = counterSignature.getSignerInfos();

	// Add the countersignature
	SignerInformation updatedSI = originalSignature.getSignerInfos().get(selector)
			.addCounterSigners(originalSignerInfos.get(selector), signerInfos);

	// Create updated SignerInformationStore
	Collection<SignerInformation> counterSignatureInformationCollection = new ArrayList<SignerInformation>();
	counterSignatureInformationCollection.add(updatedSI);
	SignerInformationStore signerInformationStore = new SignerInformationStore(
			counterSignatureInformationCollection);

	// Return new, updated signature
	return CMSSignedData.replaceSigners(originalSignature, signerInformationStore);
}
 
Example #3
Source File: JarSigner.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {

		Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();

		// get signature of first signer (should be the only one)
		SignerInformation si = signerInfos.iterator().next();
		byte[] signature = si.getSignature();

		// send request to TSA
		byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);

		// create new SignerInformation with TS attribute
		Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
				new DERSet(ASN1Primitive.fromByteArray(token)));
		ASN1EncodableVector timestampVector = new ASN1EncodableVector();
		timestampVector.add(tokenAttr);
		AttributeTable at = new AttributeTable(timestampVector);
		si = SignerInformation.replaceUnsignedAttributes(si, at);
		signerInfos.clear();
		signerInfos.add(si);
		SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);

		// create new signed data
		CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
		return newSignedData;
	}
 
Example #4
Source File: CAdESSignatureWrapperTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);

	SignatureWrapper signature = diagnosticData.getSignatureById(diagnosticData.getFirstSignatureId());
	XmlSignatureDigestReference signatureDigestReference = signature.getSignatureDigestReference();
	assertNotNull(signatureDigestReference);
	
	List<AdvancedSignature> signatures = validator.getSignatures();
	assertEquals(1, signatures.size());
	CAdESSignature cadesSignature = (CAdESSignature) signatures.get(0);
	CMSSignedData cmsSignedData = cadesSignature.getCmsSignedData();
	SignerInformationStore signerInfos = cmsSignedData.getSignerInfos();
	SignerInformation signerInformation = signerInfos.iterator().next();
	SignerInfo signerInfo = signerInformation.toASN1Structure();
	byte[] derEncoded = DSSASN1Utils.getDEREncoded(signerInfo);
	byte[] digest = DSSUtils.digest(signatureDigestReference.getDigestMethod(), derEncoded);
	
	String signatureReferenceDigestValue = Utils.toBase64(signatureDigestReference.getDigestValue());
	String signatureElementDigestValue = Utils.toBase64(digest);
	assertEquals(signatureReferenceDigestValue, signatureElementDigestValue);
}
 
Example #5
Source File: TimestampToken.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean isValidCMSSignedData(SignerInformationVerifier signerInformationVerifier) {
	try {
		// Only validate the cryptographic validity
		SignerInformationStore signerInfos = timeStamp.toCMSSignedData().getSignerInfos();
		SignerInformation signerInformation = signerInfos.get(timeStamp.getSID());
		return signerInformation.verify(signerInformationVerifier);
	} catch (CMSException e) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Unable to validate the related CMSSignedData : ", e);
		} else {
			LOG.warn("Unable to validate the related CMSSignedData : {}", e.getMessage());
		}
		signatureInvalidityReason = e.getClass().getSimpleName() + " : " + e.getMessage();
		return false;
	}
}
 
Example #6
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
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 #7
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
	try {
		Security.addProvider(new BouncyCastleProvider());
		List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>();
		CMSSignedData cmsSignedData = new CMSSignedData(signature);
		SignerInformationStore signers = cmsSignedData.getSignerInfos();
		Iterator<?> it = signers.getSigners().iterator();
		while (it.hasNext()) {
			SignerInformation signer = (SignerInformation) it.next();
			AttributeTable unsignedAttributes = signer
					.getUnsignedAttributes();
			Attribute attributeTimeStamp = unsignedAttributes
					.get(new ASN1ObjectIdentifier(
							PKCSObjectIdentifiers.id_aa_signatureTimeStampToken
									.getId()));
			if (attributeTimeStamp != null) {
				TimeStampOperator timeStampOperator = new TimeStampOperator();
				byte[] varTimeStamp = attributeTimeStamp.getAttrValues()
						.getObjectAt(0).toASN1Primitive().getEncoded();
				TimeStampToken timeStampToken = new TimeStampToken(
						new CMSSignedData(varTimeStamp));
				Timestamp timeStampSigner = new Timestamp(timeStampToken);
				timeStampOperator.validate(signer.getSignature(),
						varTimeStamp, null);
				listOfTimeStamp.add(timeStampSigner);
			}
		}
		return listOfTimeStamp;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}		
}
 
Example #8
Source File: CAdESSignatureExtension.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Take the last signerInformation of the cmsSignedData and extends the signature
 *
 * @param cmsSignedData
 * @return
 */
private CMSSignedData extendLastCMSSignature(CMSSignedData cmsSignedData, CAdESSignatureParameters parameters) {

	LOG.info("EXTEND LAST CMS SIGNATURES.");
	cmsSignedData = preExtendCMSSignedData(cmsSignedData, parameters);

	Collection<SignerInformation> signerInformationCollection = cmsSignedData.getSignerInfos().getSigners();
	SignerInformation lastSignerInformation = getFirstSigner(cmsSignedData);
	final List<SignerInformation> newSignerInformationList = new ArrayList<>();
	for (SignerInformation signerInformation : signerInformationCollection) {

		if (lastSignerInformation == signerInformation) {

			final CAdESSignature cadesSignature = newCAdESSignature(cmsSignedData, signerInformation, parameters.getDetachedContents());
			assertSignatureValid(cadesSignature, parameters);
			final SignerInformation newSignerInformation = extendCMSSignature(cmsSignedData, signerInformation, parameters);
			newSignerInformationList.add(newSignerInformation);
		} else {
			newSignerInformationList.add(signerInformation);
		}
	}

	final SignerInformationStore newSignerStore = new SignerInformationStore(newSignerInformationList);
	cmsSignedData = CMSSignedData.replaceSigners(cmsSignedData, newSignerStore);

	lastSignerInformation = getFirstSigner(cmsSignedData);
	return postExtendCMSSignedData(cmsSignedData, lastSignerInformation, parameters.getDetachedContents());
}
 
Example #9
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
public void addSignerInformation(SignerInformationStore signerInfStore) {
    Collection<SignerInformation> SignerInformationList = signerInfStore.getSigners();
    if (SignerInformationList != null)
        for (SignerInformation si : SignerInformationList)
            addSignerInformation(si);
}
 
Example #10
Source File: CAdESSignatureExtension.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ASN1Object getTimeStampAttributeValue(final byte[] messageToTimestamp, final DigestAlgorithm timestampDigestAlgorithm,
		final Attribute... attributesForTimestampToken) {
	try {

		if (LOG.isDebugEnabled()) {
			LOG.debug("Message to timestamp is: {}", Utils.toHex(messageToTimestamp));
		}
		byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
		if (LOG.isDebugEnabled()) {
			LOG.debug("Digested ({}) message to timestamp is {}", timestampDigestAlgorithm, Utils.toHex(timestampDigest));
		}

		final TimestampBinary timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm, timestampDigest);
		CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getBytes());

		// TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
		if (attributesForTimestampToken != null) {
			// timeStampToken contains one and only one signer
			final SignerInformation signerInformation = cmsSignedDataTimeStampToken.getSignerInfos().getSigners().iterator().next();
			AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
			for (final Attribute attributeToAdd : attributesForTimestampToken) {
				final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
				final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
				unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
			}
			// Unsigned attributes cannot be empty (RFC 5652 5.3)
			if (unsignedAttributes.size() == 0) {
				unsignedAttributes = null;
			}
			final SignerInformation newSignerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);
			final List<SignerInformation> signerInformationList = new ArrayList<>();
			signerInformationList.add(newSignerInformation);
			final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
			cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken, newSignerStore);
		}
		final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
		return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
	} catch (IOException | CMSException e) {
		throw new DSSException("Cannot obtain timestamp attribute value.", e);
	}

}
 
Example #11
Source File: KeyStoreHolder.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies the signature of a SMIME message.
 * 
 * It checks also if the signer's certificate is trusted using the loaded
 * keystore as trusted certificate store.
 * 
 * @param signed
 *            the signed mail to check.
 * @return a list of SMIMESignerInfo which keeps the data of each mail
 *         signer.
 * @throws Exception
 * @throws MessagingException
 */
public List<SMIMESignerInfo> verifySignatures(SMIMESigned signed) throws Exception {

    CertStore certs = new JcaCertStoreBuilder()
        .addCertificates(signed.getCertificates())
        .addCRLs(signed.getCRLs())
        .build();
    SignerInformationStore siginfo = signed.getSignerInfos();
    Collection<SignerInformation> sigCol = siginfo.getSigners();
    List<SMIMESignerInfo> result = new ArrayList<>(sigCol.size());
    // I iterate over the signer collection 
    // checking if the signatures put
    // on the message are valid.
    for (SignerInformation info: sigCol) {
        // I get the signer's certificate
        X509CertificateHolderSelector x509CertificateHolderSelector = new X509CertificateHolderSelector(info.getSID().getSubjectKeyIdentifier());
        X509CertSelector certSelector = new JcaX509CertSelectorConverter().getCertSelector(x509CertificateHolderSelector);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certCollection = (Collection<X509Certificate>) certs.getCertificates(certSelector);
        if (!certCollection.isEmpty()) {
            X509Certificate signerCert = certCollection.iterator().next();
            // The issuer's certifcate is searched in the list of trusted certificate.
            CertPath path = verifyCertificate(signerCert, certs, keyStore);

            try {
                // if the signature is valid the SMIMESignedInfo is 
                // created using "true" as last argument. If it is  
                // invalid an exception is thrown by the "verify" method
                // and the SMIMESignerInfo is created with "false".
                //
                // The second argument "path" is not null if the 
                // certificate can be trusted (it can be connected 
                // by a chain of trust to a trusted certificate), null
                // otherwise.
                if (info.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(signerCert))) {
                    result.add(new SMIMESignerInfo(signerCert, path, true));
                }
            } catch (Exception e) { 
                result.add(new SMIMESignerInfo(signerCert,path, false)); 
            }
        }
    }
    return result;
}
 
Example #12
Source File: CounterSignatureValidationTest.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
@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;
	
}