org.bouncycastle.cms.CMSSignedData Java Examples

The following examples show how to use org.bouncycastle.cms.CMSSignedData. 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: 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 #2
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 #3
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #4
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[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedContent = new CMSSignedData(signature);
      byte[] signedData;
      if (signedContent.getSignedContent() == null) {
         LOG.info("Signature has no ecapsulated signature. Adding content.");
         signedData = (new CMSSignedData(new CMSProcessableByteArray(content), signature)).getEncoded();
      } else {
         signedData = ArrayUtils.clone(signature);
      }

      return this.verify(signedData, options);
   } catch (CMSException var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   } catch (IOException var8) {
      LOG.error("Unable to verify signature", var8);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #5
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[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedContent = new CMSSignedData(signature);
      byte[] signedData;
      if (signedContent.getSignedContent() == null) {
         LOG.info("Signature has no ecapsulated signature. Adding content.");
         signedData = (new CMSSignedData(new CMSProcessableByteArray(content), signature)).getEncoded();
      } else {
         signedData = ArrayUtils.clone(signature);
      }

      return this.verify(signedData, options);
   } catch (CMSException var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   } catch (IOException var8) {
      LOG.error("Unable to verify signature", var8);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #6
Source File: ASiCWithCAdESService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ValidationDataForInclusion getValidationDataForDocument(DSSDocument document, List<DSSDocument> originalSignedDocuments) {
	try {
		CMSSignedData cmsSignedData = DSSUtils.toCMSSignedData(document);
		CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, cmsSignedData.getSignerInfos().iterator().next());
		cadesSignature.setDetachedContents(originalSignedDocuments);
		ValidationContext validationContext = cadesSignature.getSignatureValidationContext(certificateVerifier);
		ValidationDataForInclusionBuilder validationDataForInclusionBuilder = 
				new ValidationDataForInclusionBuilder(validationContext, cadesSignature.getCompleteCertificateSource())
				.excludeCertificateTokens(cadesSignature.getCompleteCertificateSource().getAllCertificateTokens())
				.excludeCRLs(cadesSignature.getCompleteCRLSource().getAllRevocationBinaries())
				.excludeOCSPs(cadesSignature.getCompleteOCSPSource().getAllRevocationBinaries());
		return validationDataForInclusionBuilder.build();
		
	} catch (DSSException e) {
		String message = "Cannot extract validation data for an archive manifest entry with name '{}'. Reason : {}";
		if (LOG.isDebugEnabled()) {
			LOG.warn(message, document.getName(), e.getMessage(), e);
		} else {
			LOG.warn(message, document.getName(), e.getMessage());
		}

		// return empty
		return new ValidationDataForInclusion();
	}
}
 
Example #7
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #8
Source File: CMSSignedDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #9
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #10
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[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedContent = new CMSSignedData(signature);
      byte[] signedData;
      if (signedContent.getSignedContent() == null) {
         LOG.info("Signature has no ecapsulated signature. Adding content.");
         signedData = (new CMSSignedData(new CMSProcessableByteArray(content), signature)).getEncoded();
      } else {
         signedData = ArrayUtils.clone(signature);
      }

      return this.verify(signedData, options);
   } catch (CMSException var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   } catch (IOException var8) {
      LOG.error("Unable to verify signature", var8);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example #11
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 #12
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 #13
Source File: Client.java    From xipki with Apache License 2.0 6 votes vote down vote up
public EnrolmentResponse scepCertPoll(PrivateKey identityKey, X509Cert identityCert,
    TransactionId transactionId, X500Name issuer, X500Name subject) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(transactionId, "transactionId");

  initIfNotInited();

  PkiMessage pkiMessage = new PkiMessage(transactionId, MessageType.CertPoll);

  IssuerAndSubject is = new IssuerAndSubject(issuer, subject);
  pkiMessage.setMessageData(is);
  ContentInfo envRequest = encryptThenSign(pkiMessage, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);
  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  assertSameNonce(pkiMessage, response);
  return new EnrolmentResponse(response);
}
 
Example #14
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 #15
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example #16
Source File: PAdESService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected byte[] generateCMSSignedData(final DSSDocument toSignDocument, final PAdESSignatureParameters parameters, final SignatureValue signatureValue) {
	final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
	final SignatureLevel signatureLevel = parameters.getSignatureLevel();
	Objects.requireNonNull(signatureAlgorithm, "SignatureAlgorithm cannot be null!");
	Objects.requireNonNull(signatureLevel, "SignatureLevel must be defined!");
	
	final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue.getValue());

	final byte[] messageDigest = computeDocumentDigest(toSignDocument, parameters);
	final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = padesCMSSignedDataBuilder.getSignerInfoGeneratorBuilder(parameters, messageDigest);

	final CMSSignedDataGenerator generator = padesCMSSignedDataBuilder.createCMSSignedDataGenerator(parameters, customContentSigner,
			signerInfoGeneratorBuilder, null);

	final CMSProcessableByteArray content = new CMSProcessableByteArray(messageDigest);
	CMSSignedData data = CMSUtils.generateDetachedCMSSignedData(generator, content);

	if (signatureLevel != SignatureLevel.PAdES_BASELINE_B) {
		// use an embedded timestamp
		CAdESLevelBaselineT cadesLevelBaselineT = new CAdESLevelBaselineT(tspSource, false);
		data = cadesLevelBaselineT.extendCMSSignatures(data, parameters);
	}

	return DSSASN1Utils.getDEREncoded(data);
}
 
Example #17
Source File: CAdESService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method retrieves the data to be signed. It this data is located within a signature then it is extracted.
 *
 * @param toSignDocument
 *            document to sign
 * @param parameters
 *            set of the driving signing parameters
 * @param originalCmsSignedData
 *            the signed data extracted from an existing signature or null
 * @return
 */
private DSSDocument getToSignData(final DSSDocument toSignDocument, final CAdESSignatureParameters parameters, final CMSSignedData originalCmsSignedData) {
	final List<DSSDocument> detachedContents = parameters.getDetachedContents();
	if (Utils.isCollectionNotEmpty(detachedContents)) {
		// CAdES only can sign one document
		// (ASiC-S -> the document to sign /
		// ASiC-E -> ASiCManifest)
		return detachedContents.get(0);
	} else {
		if (originalCmsSignedData == null) {
			return toSignDocument;
		} else {
			return getSignedContent(originalCmsSignedData);
		}
	}
}
 
Example #18
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 #19
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 #20
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private ContentInfo createSignedData(X509Cert cert) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();

  CMSSignedData cmsSigneddata;
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isSendCaCert()) {
      cmsSignedDataGen.addCertificate(caEmulator.getCaCert().toBcCert());
    }

    cmsSigneddata = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    throw new CaException(ex);
  }

  return cmsSigneddata.toASN1Structure();
}
 
Example #21
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #22
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 #23
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 #24
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 #25
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStampPDF(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		byte[] varTimeStamp = timeStamp;
		TimeStampOperator timeStampOperator = new TimeStampOperator();
		if (content != null){
			timeStampOperator.validate(content, varTimeStamp,null);
		}else{
			timeStampOperator.validate(null, varTimeStamp,hash);
		}			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
		| CMSException e) {
		throw new SignerException(e);
	}
	
}
 
Example #26
Source File: CAdESChecker.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *  validade a timestampo on signature
 * @param attributeTimeStamp
 * @param varSignature
 * @return
 */
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature){
	try {
		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(varSignature,varTimeStamp , null);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException | CMSException e) {
		throw new SignerException(e);
	}		
}
 
Example #27
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a TimeStampToken from the provided {@code attribute}
 * @param attribute {@link Attribute} to generate {@link TimeStampToken} from
 * @return {@link TimeStampToken}
 */
public static TimeStampToken getTimeStampToken(Attribute attribute) {
	try {
		CMSSignedData signedData = getCMSSignedData(attribute);
		if (signedData != null) {
			return new TimeStampToken(signedData);
		}
	} catch (IOException | CMSException | TSPException e) {
		LOG.warn("The given TimeStampToken cannot be created! Reason: [{}]", e.getMessage());
	}
	return null;
}
 
Example #28
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 5 votes vote down vote up
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 #29
Source File: CAdESDEREncodedTst2Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);
	
	List<AdvancedSignature> signatures = validator.getSignatures();
	assertEquals(1, signatures.size());
	assertTrue(signatures.get(0) instanceof CAdESSignature);
	
	CAdESSignature signature = (CAdESSignature) signatures.get(0);
	CMSSignedData cmsSignedData = signature.getCmsSignedData();
	assertNotNull(cmsSignedData);
}
 
Example #30
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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()));
   }

}