org.bouncycastle.cms.SignerInformation Java Examples

The following examples show how to use org.bouncycastle.cms.SignerInformation. 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 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 #2
Source File: CAdESSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public byte[] doCounterSign(byte[] previewCMSSignature) {
	try {
		Security.addProvider(new BouncyCastleProvider());

		// Reading a P7S file that is preview signature.
		CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature);

		// Build BouncyCastle object that is a set of signatures
		Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners();

		for (SignerInformation previewSigner : previewSigners) {
			// build a counter-signature per previewSignature
			byte[] previewSignatureFromSigner = previewSigner.getSignature();
			CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner));
			cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData,
					previewSigner.getSID());
		}
		return cmsPreviewSignedData.getEncoded();
	} catch (Throwable error) {
		throw new SignerException(error);
	}
}
 
Example #3
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #4
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 #5
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 #6
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #7
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #8
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #9
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This specific doesn't verify in combination with its document, so
 * I wanted to look at its contents. As RSASSA-PSS does not allow to
 * read the original hash from the decrypted signature bytes, this
 * did not help at all.
 */
@Test
public void testDecryptSLMBC_PSS_Test1() throws IOException, CMSException, GeneralSecurityException
{
    Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding");
    KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");

    try (   InputStream resource = getClass().getResourceAsStream("SLMBC-PSS-Test1.cms")    )
    {
        CMSSignedData cmsSignedData = new CMSSignedData(resource);
        for (SignerInformation signerInformation : (Iterable<SignerInformation>)cmsSignedData.getSignerInfos().getSigners())
        {
            Collection<X509CertificateHolder> x509CertificateHolders = cmsSignedData.getCertificates().getMatches(signerInformation.getSID());
            if (x509CertificateHolders.size() != 1)
            {
                Assert.fail("Cannot uniquely determine signer certificate.");
            }
            X509CertificateHolder x509CertificateHolder = x509CertificateHolders.iterator().next();
            PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(x509CertificateHolder.getSubjectPublicKeyInfo().getEncoded()));
            cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] bytes = cipherNoPadding.doFinal(signerInformation.getSignature());

            Files.write(new File(RESULT_FOLDER, "SLMBC-PSS-Test1-signature-decoded").toPath(), bytes);
        }
    }
}
 
Example #10
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * The code completely ignores the <b>SubFilter</b> of the signature.
 * It is appropriate for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b>
 * but will fail for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>.
 * </p>
 * <p>
 * The example document has been signed with a signatures with
 * <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTest() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes);
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        // result if false
        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}
 
Example #11
Source File: CalculateDigest.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/57926872/signed-pdf-content-digest-that-was-calculated-during-verification-is-diffrent-th">
 * Signed PDF content digest that was calculated during verification is diffrent than decripted digest from signature
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UlOZOp-UYllK7Ra35dggccoWdhcb_Ntp">
 * TEST-signed-pades-baseline-b.pdf
 * </a>
 * <p>
 * The code here demonstrates how to retrieve the messageDigest
 * signed attribute value from a signed PDF. For production use
 * obviously some null checks are required.
 * </p>
 */
@Test
public void testExtractMessageDigestAttributeForUser2893427() throws IOException, CMSException {
    try (   InputStream resource = getClass().getResourceAsStream("TEST-signed-pades-baseline-b.pdf")   ) {
        byte[] bytes = IOUtils.toByteArray(resource);
        PDDocument document = Loader.loadPDF(bytes);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        PDSignature sig = signatures.get(0);
        byte[] cmsBytes = sig.getContents(bytes);
        CMSSignedData cms = new CMSSignedData(cmsBytes);
        SignerInformation signerInformation = cms.getSignerInfos().iterator().next();
        Attribute attribute = signerInformation.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
        ASN1Encodable value = attribute.getAttributeValues()[0];
        System.out.printf("MessageDigest attribute value: %s\n", value);
    }
}
 
Example #12
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 #13
Source File: CMSDocumentValidator.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public List<AdvancedSignature> getSignatures() {
	List<AdvancedSignature> signatures = new ArrayList<>();
	if (cmsSignedData != null) {
		for (final SignerInformation signerInformation : cmsSignedData.getSignerInfos().getSigners()) {
			final CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
			if (document != null) {
				cadesSignature.setSignatureFilename(document.getName());
			}
			cadesSignature.setDetachedContents(detachedContents);
			cadesSignature.setContainerContents(containerContents);
			cadesSignature.setManifestFiles(manifestFiles);
			cadesSignature.setProvidedSigningCertificateToken(providedSigningCertificateToken);
			cadesSignature.prepareOfflineCertificateVerifier(certificateVerifier);
			signatures.add(cadesSignature);
		}
	}
	return signatures;
}
 
Example #14
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ReferenceValidation getContentReferenceValidation(DSSDocument originalDocument, SignerInformation signerInformation) {
	ReferenceValidation contentValidation = new ReferenceValidation();
	contentValidation.setType(DigestMatcherType.CONTENT_DIGEST);
	DigestAlgorithm digestAlgorithm = getDigestAlgorithmForOID(signerInformation.getDigestAlgOID());
	if (originalDocument != null && digestAlgorithm != null) {
		byte[] contentDigest = signerInformation.getContentDigest();
		if (Utils.isArrayNotEmpty(contentDigest)) {
			contentValidation.setFound(true);
			contentValidation.setDigest(new Digest(digestAlgorithm, contentDigest));
			if (Arrays.equals(contentDigest, Utils.fromBase64(originalDocument.getDigest(digestAlgorithm)))) {
				contentValidation.setIntact(true);
			}
		}
	}
	return contentValidation;
}
 
Example #15
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #16
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 #17
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractCertificateIdentifiers() {
	CertificateIdentifier currentCertificateIdentifier = DSSASN1Utils.toIssuerSerialInfo(currentSignerInformation.getSID());
	boolean found = false;
	Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
	for (SignerInformation signerInformation : signers) {
		CertificateIdentifier certificateIdentifier = DSSASN1Utils.toIssuerSerialInfo(signerInformation.getSID());
		if (certificateIdentifier.isEquivalent(currentCertificateIdentifier)) {
			certificateIdentifier.setCurrent(true);
			found = true;
		}
		addCertificateIdentifier(certificateIdentifier, CertificateOrigin.SIGNED_DATA);
	}
	if (!found) {
		LOG.warn("SID not found in SignerInfos");
		currentCertificateIdentifier.setCurrent(true);
		addCertificateIdentifier(currentCertificateIdentifier, CertificateOrigin.SIGNED_DATA);
	}
}
 
Example #18
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 #19
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public byte[] getArchiveTimestampDataV3(SignerInformation signerInformation, Attribute atsHashIndexAttribute, byte[] originalDocumentDigest) {
	final byte[] encodedContentType = getEncodedContentType(cmsSignedData); // OID
	final byte[] signedDataDigest = originalDocumentDigest;
	final byte[] encodedFields = getSignedFields(signerInformation);
	final byte[] encodedAtsHashIndex = DSSASN1Utils.getDEREncoded(atsHashIndexAttribute.getAttrValues().getObjectAt(0));
	/**
	 * The input for the archive-time-stamp-v3’s message imprint computation shall be the concatenation (in the
	 * order shown by the list below) of the signed data hash (see bullet 2 below) and certain fields in their
	 * binary encoded
	 * form without any modification and including the tag, length and value octets:
	 */
	final byte[] dataToTimestamp = DSSUtils.concatenate(encodedContentType, signedDataDigest, encodedFields, encodedAtsHashIndex);
	if (LOG.isDebugEnabled()) {
		LOG.debug("eContentType={}", encodedContentType != null ? Utils.toHex(encodedContentType) : encodedContentType);
		LOG.debug("signedDataDigest={}", signedDataDigest != null ? Utils.toHex(signedDataDigest) : signedDataDigest);
		LOG.debug("encodedFields=see above");
		LOG.debug("encodedAtsHashIndex={}", encodedAtsHashIndex != null ? Utils.toHex(encodedAtsHashIndex) : encodedAtsHashIndex);
		LOG.debug("Archive Timestamp Data v3 is: {}", dataToTimestamp != null ? Utils.toHex(dataToTimestamp) : dataToTimestamp);
	}
	return dataToTimestamp;
}
 
Example #20
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The field unsignedAttrsHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of Attribute within unsignedAttrs field of the SignerInfo. A hash value for every instance of
 * Attribute, as present at the time when the corresponding archive time-stamp is requested, shall be included in
 * unsignedAttrsHashIndex. No other hash values shall be included in this field.
 *
 * @param signerInformation {@link SignerInformation}
 * @param atsHashIndexVersionIdentifier {@link ASN1ObjectIdentifier} of the ats-hash-index table version to create
 * @return
 */
private ASN1Sequence getUnsignedAttributesHashIndex(SignerInformation signerInformation, ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {

	final ASN1EncodableVector unsignedAttributesHashIndex = new ASN1EncodableVector();
	AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
	final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector();
	for (int i = 0; i < asn1EncodableVector.size(); i++) {
		final Attribute attribute = (Attribute) asn1EncodableVector.get(i);
		if (!excludedAttributesFromAtsHashIndex.contains(attribute.getAttrType())) {
			List<DEROctetString> attributeDerOctetStringHashes = getAttributeDerOctetStringHashes(attribute, atsHashIndexVersionIdentifier);
			for (DEROctetString derOctetStringDigest : attributeDerOctetStringHashes) {
				unsignedAttributesHashIndex.add(derOctetStringDigest);
			}
		}
	}
	return new DERSequence(unsignedAttributesHashIndex);
}
 
Example #21
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * get the atsHash index for verification of the provided token.
 *
 * @param signerInformation
 * @param timestampToken
 * @return a re-built ats-hash-index
 */
public Attribute getVerifiedAtsHashIndex(SignerInformation signerInformation, TimestampToken timestampToken) {
	final AttributeTable unsignedAttributes = timestampToken.getUnsignedAttributes();
	ASN1ObjectIdentifier atsHashIndexVersionIdentifier = DSSASN1Utils.getAtsHashIndexVersionIdentifier(unsignedAttributes);
	ASN1Sequence atsHashIndex = DSSASN1Utils.getAtsHashIndexByVersion(unsignedAttributes, atsHashIndexVersionIdentifier);
	if (atsHashIndex == null) {
		LOG.warn("A valid atsHashIndex [oid: {}] has not been found for a timestamp with id {}",
				atsHashIndexVersionIdentifier, timestampToken.getDSSIdAsString());
	}
	
	final AlgorithmIdentifier derObjectAlgorithmIdentifier = getAlgorithmIdentifier(atsHashIndex);
	final ASN1Sequence certificatesHashIndex = getVerifiedCertificatesHashIndex(atsHashIndex);
	final ASN1Sequence crLsHashIndex = getVerifiedCRLsHashIndex(atsHashIndex);
	final ASN1Sequence verifiedAttributesHashIndex = getVerifiedUnsignedAttributesHashIndex(signerInformation, atsHashIndex, 
			atsHashIndexVersionIdentifier);
	return getComposedAtsHashIndex(derObjectAlgorithmIdentifier, certificatesHashIndex, crLsHashIndex, 
			verifiedAttributesHashIndex, atsHashIndexVersionIdentifier);
}
 
Example #22
Source File: CAdESLevelBaselineLT.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected SignerInformation extendCMSSignature(CMSSignedData cmsSignedData, SignerInformation signerInformation, CAdESSignatureParameters parameters)
		throws DSSException {
	// add a LT level or replace an existing LT level
	CAdESSignature cadesSignature = newCAdESSignature(cmsSignedData, signerInformation, parameters.getDetachedContents());

	// add T level if needed
	if (Utils.isCollectionEmpty(cadesSignature.getSignatureTimestamps())) {
		signerInformation = cadesProfileT.extendCMSSignature(cmsSignedData, signerInformation, parameters);
		cadesSignature = newCAdESSignature(cmsSignedData, signerInformation, parameters.getDetachedContents());
	}
	// check if the resulted signature can be extended
	assertExtendSignaturePossible(cadesSignature);

	return signerInformation;
}
 
Example #23
Source File: CAdESSignatureIdentifier.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the related position of {@code this.signerInformation} in the cmsSignedData
 * among signers with the same SID
 * 
 * @param cadesSignature {@link CAdESSignature}
 * @return integer identifier
 */
private static int getUniqueIntegerIfNeeded(CAdESSignature cadesSignature) {
	Collection<SignerInformation> signerInformations;
	SignerId signerId = cadesSignature.getSignerId();
	if (cadesSignature.isCounterSignature()) {
		signerInformations = cadesSignature.getSignerInformation().getCounterSignatures().getSigners(signerId);
	} else {
		signerInformations = cadesSignature.getCmsSignedData().getSignerInfos().getSigners(signerId);
	}
	int counter = 0;
	for (SignerInformation currentSignerInformation : signerInformations) {
		if (cadesSignature.getSignerInformation() == currentSignerInformation) {
			break;
		}
		counter++;
	}
	return counter;
}
 
Example #24
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method recreates a {@code SignerInformation} with the content using
 * a {@code CMSSignedDataParser}.
 *
 * @return
 * @throws CMSException
 * @throws IOException
 */
private SignerInformation recreateSignerInformation() throws CMSException, IOException {

	final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature
	CMSSignedDataParser cmsSignedDataParser = null;
	if (dssDocument instanceof DigestDocument) {
		cmsSignedDataParser = new CMSSignedDataParser(new PrecomputedDigestCalculatorProvider((DigestDocument) dssDocument), cmsSignedData.getEncoded());
	} else {
		try (InputStream inputStream = dssDocument.openStream()) {
			final CMSTypedStream signedContent = new CMSTypedStream(inputStream);
			cmsSignedDataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded());
			cmsSignedDataParser.getSignedContent().drain(); // Closes the stream
		}
	}

	final SignerId signerId = getSignerId();
	final SignerInformation signerInformationToCheck = cmsSignedDataParser.getSignerInfos().get(signerId);
	return signerInformationToCheck;
}
 
Example #25
Source File: CMSDocumentValidator.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public List<DSSDocument> getOriginalDocuments(final String signatureId) {
	Objects.requireNonNull(signatureId, "Signature Id cannot be null");

	List<DSSDocument> results = new ArrayList<>();

	for (final SignerInformation signerInformation : cmsSignedData.getSignerInfos().getSigners()) {
		final CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
		cadesSignature.setSignatureFilename(document.getName());
		cadesSignature.setDetachedContents(detachedContents);
		cadesSignature.setProvidedSigningCertificateToken(providedSigningCertificateToken);
		if (Utils.areStringsEqual(cadesSignature.getId(), signatureId) || isCounterSignature(cadesSignature, signatureId)) {
			results.add(cadesSignature.getOriginalDocument());
		}
	}
	return results;
}
 
Example #26
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The field unsignedAttrsHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of Attribute within unsignedAttrs field of the SignerInfo. A hash value for every instance of
 * Attribute, as present at the time when the corresponding archive time-stamp is requested, shall be included in
 * unsignedAttrsHashIndex. No other hash values shall be included in this field.
 *
 * We check that every hash attribute found in the timestamp token is found if the signerInformation.
 *
 * If there is more unsigned attributes in the signerInformation than present in the hash attributes list
 * (and there is at least the archiveTimestampAttributeV3), we don't report any error nor which attributes are
 * signed by the timestamp.
 * If there is some attributes that are not present or altered in the signerInformation, we just return some empty
 * sequence to make
 * sure that the timestamped data will not match. We do not report which attributes hash are present if any.
 *
 * If there is not attribute at all in the archive timestamp hash index, that would means we didn't check anything.
 *
 * @param signerInformation
 * @param timestampHashIndex
 * @return
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getVerifiedUnsignedAttributesHashIndex(SignerInformation signerInformation, final ASN1Sequence timestampHashIndex, 
		ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {
	
	final ASN1Sequence unsignedAttributesHashes = DSSASN1Utils.getUnsignedAttributesHashIndex(timestampHashIndex);
	
	final List<DEROctetString> timestampUnsignedAttributesHashesList = new ArrayList<>();
	if (unsignedAttributesHashes != null) {
		timestampUnsignedAttributesHashesList.addAll(Collections.list(unsignedAttributesHashes.getObjects()));
	}
	AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
	final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector();
	for (int i = 0; i < asn1EncodableVector.size(); i++) {
		final Attribute attribute = (Attribute) asn1EncodableVector.get(i);
		List<DEROctetString> attributeDerOctetStringHashes = getAttributeDerOctetStringHashes(attribute, atsHashIndexVersionIdentifier);
		for (DEROctetString derOctetStringDigest : attributeDerOctetStringHashes) {
			final ASN1ObjectIdentifier attrType = attribute.getAttrType();
			if (timestampUnsignedAttributesHashesList.remove(derOctetStringDigest)) {
				// attribute present in signature and in timestamp
				LOG.debug("Attribute {} present in timestamp", attrType.getId());
			} else {
				LOG.debug("Attribute {} not present in timestamp", attrType.getId());
			}
		}
	}
	if (!timestampUnsignedAttributesHashesList.isEmpty()) {
		LOG.error("{} attribute(s) hash in Timestamp has not been found in document attributes: {}", timestampUnsignedAttributesHashesList.size(),
				timestampUnsignedAttributesHashesList);
		// return a empty DERSequence to screw up the hash
		return new DERSequence();
	}
	// return the original DERSequence
	return unsignedAttributesHashes;
}
 
Example #27
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 3) Fields version, sid, digestAlgorithm, signedAttrs, signatureAlgorithm, and
 * signature within the SignedData.signerInfos’s item corresponding to the signature being archive
 * time-stamped, in their order of appearance.
 *
 * @param signerInformation
 * @return
 */
private byte[] getSignedFields(final SignerInformation signerInformation) {

	final SignerInfo signerInfo = signerInformation.toASN1Structure();
	final ASN1Integer version = signerInfo.getVersion();
	final SignerIdentifier sid = signerInfo.getSID();
	final AlgorithmIdentifier digestAlgorithm = signerInfo.getDigestAlgorithm();
	final DERTaggedObject signedAttributes = CMSUtils.getDERSignedAttributes(signerInformation);
	final AlgorithmIdentifier digestEncryptionAlgorithm = signerInfo.getDigestEncryptionAlgorithm();
	final ASN1OctetString encryptedDigest = signerInfo.getEncryptedDigest();

	final byte[] derEncodedVersion = DSSASN1Utils.getDEREncoded(version);
	final byte[] derEncodedSid = DSSASN1Utils.getDEREncoded(sid);
	final byte[] derEncodedDigestAlgorithm = DSSASN1Utils.getDEREncoded(digestAlgorithm);
	final byte[] derEncodedSignedAttributes = DSSASN1Utils.getDEREncoded(signedAttributes);
	final byte[] derEncodedDigestEncryptionAlgorithm = DSSASN1Utils.getDEREncoded(digestEncryptionAlgorithm);
	final byte[] derEncodedEncryptedDigest = DSSASN1Utils.getDEREncoded(encryptedDigest);
	if (LOG.isDebugEnabled()) {

		LOG.debug("getSignedFields Version={}", Utils.toBase64(derEncodedVersion));
		LOG.debug("getSignedFields Sid={}", Utils.toBase64(derEncodedSid));
		LOG.debug("getSignedFields DigestAlgorithm={}", Utils.toBase64(derEncodedDigestAlgorithm));
		LOG.debug("getSignedFields SignedAttributes={}", Utils.toBase64(derEncodedSignedAttributes));
		LOG.debug("getSignedFields DigestEncryptionAlgorithm={}", Utils.toBase64(derEncodedDigestEncryptionAlgorithm));
		LOG.debug("getSignedFields EncryptedDigest={}", Utils.toBase64(derEncodedEncryptedDigest));
	}
	return DSSUtils.concatenate(derEncodedVersion, derEncodedSid, derEncodedDigestAlgorithm, derEncodedSignedAttributes,
			derEncodedDigestEncryptionAlgorithm, derEncodedEncryptedDigest);
}
 
Example #28
Source File: CAdESLevelBaselineT.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation signerInformation, CAdESSignatureParameters parameters)
		throws DSSException {
	final CAdESSignature cadesSignature = newCAdESSignature(signedData, signerInformation, parameters.getDetachedContents());
	assertExtendSignaturePossible(cadesSignature);

	AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
	unsignedAttributes = addSignatureTimestampAttribute(signerInformation, unsignedAttributes, parameters);

	return SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);
}
 
Example #29
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 #30
Source File: CMSUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns an unsigned attribute by its given {@code oid}
 * @param signerInformation {@link SignerInformation} to get attribute from
 * @param oid {@link ASN1ObjectIdentifier} of the target attribute
 * @return {@link Attribute}
 */
public static Attribute getUnsignedAttribute(SignerInformation signerInformation, ASN1ObjectIdentifier oid) {
	final AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
	if (unsignedAttributes == null) {
		return null;
	}
	return unsignedAttributes.get(oid);
}