org.bouncycastle.cms.CMSSignedDataGenerator Java Examples

The following examples show how to use org.bouncycastle.cms.CMSSignedDataGenerator. 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: AbstractExternalCMSPAdESSignatureTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Computes a CAdES with specific things for PAdES
 */
private byte[] getSignedCMSignedData(byte[] documentDigest) {
	CMSProcessableByteArray content = new CMSProcessableByteArray(documentDigest);

	PadesCMSSignedDataBuilder padesCMSSignedDataBuilder = new PadesCMSSignedDataBuilder(getOfflineCertificateVerifier());
	SignatureAlgorithm signatureAlgorithm = signatureParameters.getSignatureAlgorithm();

	CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId());
	SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = padesCMSSignedDataBuilder.getSignerInfoGeneratorBuilder(signatureParameters, documentDigest);

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

	CMSUtils.generateDetachedCMSSignedData(generator, content);

	SignatureValue signatureValue = getToken().sign(new ToBeSigned(customContentSigner.getOutputStream().toByteArray()),
			signatureParameters.getDigestAlgorithm(), getPrivateKeyEntry());

	customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue.getValue());
	generator = padesCMSSignedDataBuilder.createCMSSignedDataGenerator(signatureParameters, customContentSigner, signerInfoGeneratorBuilder, null);

	CMSSignedData cmsSignedData = CMSUtils.generateDetachedCMSSignedData(generator, content);
	return DSSASN1Utils.getDEREncoded(cmsSignedData);
}
 
Example #2
Source File: CertificateManagementServiceImplTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests Signature verification of a Certificate against the keystore")
public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
    BASE64Encoder encoder = new BASE64Encoder();
    //generate and save a certificate in the keystore
    X509Certificate x509Certificate = managementService.generateX509Certificate();
    //Generate CMSdata
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    List<X509Certificate> list = new ArrayList<>();
    list.add(x509Certificate);
    JcaCertStore store = new JcaCertStore(list);
    generator.addCertificates(store);
    CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
    byte[] signature = degenerateSd.getEncoded();
    boolean verifySignature = managementService.verifySignature(encoder.encode(signature));
    Assert.assertNotNull(verifySignature);
    Assert.assertTrue(verifySignature);
    log.info("VerifySignature Test Successful");
}
 
Example #3
Source File: CertificateManagementServiceImplTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests extracting Certificate from the header Signature")
public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
    BASE64Encoder encoder = new BASE64Encoder();
    //generate and save a certificate in the keystore
    X509Certificate x509Certificate = managementService.generateX509Certificate();
    //Generate CMSdata
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    List<X509Certificate> list = new ArrayList<>();
    list.add(x509Certificate);
    JcaCertStore store = new JcaCertStore(list);
    generator.addCertificates(store);
    CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
    byte[] signature = degenerateSd.getEncoded();
    X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature));
    Assert.assertNotNull(certificate);
    Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
    log.info("ExtractCertificateFromSignature Test Successful");
}
 
Example #4
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 #5
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 #6
Source File: CAdESService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public ToBeSigned getDataToSign(final DSSDocument toSignDocument, final CAdESSignatureParameters parameters) throws DSSException {
	Objects.requireNonNull(toSignDocument, "toSignDocument cannot be null!");
	Objects.requireNonNull(parameters, "SignatureParameters cannot be null!");
	
	assertSigningDateInCertificateValidityRange(parameters);
	final SignaturePackaging packaging = parameters.getSignaturePackaging();
	assertSignaturePackaging(packaging);

	final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
	final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId());
	final DigestCalculatorProvider dcp = getDigestCalculatorProvider(toSignDocument, parameters);

	final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = cmsSignedDataBuilder.getSignerInfoGeneratorBuilder(dcp, parameters, false);
	final CMSSignedData originalCmsSignedData = getCmsSignedData(toSignDocument, parameters);

	final CMSSignedDataGenerator cmsSignedDataGenerator = cmsSignedDataBuilder.createCMSSignedDataGenerator(parameters, customContentSigner,
			signerInfoGeneratorBuilder, originalCmsSignedData);

	final DSSDocument toSignData = getToSignData(toSignDocument, parameters, originalCmsSignedData);
	final CMSTypedData content = CMSUtils.getContentToBeSign(toSignData);
	final boolean encapsulate = !SignaturePackaging.DETACHED.equals(packaging);
	CMSUtils.generateCMSSignedData(cmsSignedDataGenerator, content, encapsulate);
	final byte[] bytes = customContentSigner.getOutputStream().toByteArray();
	return new ToBeSigned(bytes);
}
 
Example #7
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 6 votes vote down vote up
private static ASN1Set buildSignedAttributes(byte[] hash, Date dateTime, X509Certificate cert) throws Exception {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new Attribute(CMSAttributes.contentType, new DERSet(PKCSObjectIdentifiers.data)));
    if (dateTime != null)
        v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(dateTime))));
    v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));

    // CADES support section
    ASN1EncodableVector aaV2 = new ASN1EncodableVector();
    AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(CMSSignedDataGenerator.DIGEST_SHA256), null);
    aaV2.add(algoId);
    byte[] dig = SignUtils.calculateHASH(CMSSignedDataGenerator.DIGEST_SHA256, cert.getEncoded());
    aaV2.add(new DEROctetString(dig));
    Attribute cades = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
    v.add(cades);

    ASN1Set signedAttributes = new DERSet(v);
    return signedAttributes;
}
 
Example #8
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 #9
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 #10
Source File: SignHelper.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #11
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private SignedData getCrl(X509Ca ca, BigInteger serialNumber)
    throws FailInfoException, OperationException {
  if (!control.isSupportGetCrl()) {
    throw FailInfoException.BAD_REQUEST;
  }

  CertificateList crl = ca.getBcCurrentCrl();
  if (crl == null) {
    LOG.error("found no CRL");
    throw FailInfoException.BAD_REQUEST;
  }
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  cmsSignedDataGen.addCRL(new X509CRLHolder(crl));

  CMSSignedData signedData;
  try {
    signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex, "could not generate CMSSignedData");
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
  return SignedData.getInstance(signedData.toASN1Structure().getContent());
}
 
Example #12
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ContentInfo createSignedData(CertificateList crl) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  cmsSignedDataGen.addCRL(new X509CRLHolder(crl));

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

  return cmsSigneddata.toASN1Structure();
}
 
Example #13
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static void addCmsCertSet(CMSSignedDataGenerator generator, X509Cert[] cmsCertSet)
    throws CertificateEncodingException, CMSException {
  if (cmsCertSet == null || cmsCertSet.length == 0) {
    return;
  }
  Args.notNull(generator, "geneator");
  Collection<X509CertificateHolder> certColl = new LinkedList<>();
  for (X509Cert m : cmsCertSet) {
    certColl.add(m.toBcCert());
  }

  JcaCertStore certStore = new JcaCertStore(certColl);
  generator.addCertificates(certStore);
}
 
Example #14
Source File: SignatureBlockGenerator.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #15
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 #16
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ScepCaCertRespBytes(X509Cert caCert, X509Cert responderCert)
    throws CMSException, CertificateException {
  Args.notNull(caCert, "caCert");
  Args.notNull(responderCert, "responderCert");

  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  try {
    cmsSignedDataGen.addCertificate(caCert.toBcCert());
    cmsSignedDataGen.addCertificate(responderCert.toBcCert());
    CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent());
    bytes = degenerateSignedData.getEncoded();
  } catch (IOException ex) {
    throw new CMSException("could not build CMS SignedDta");
  }
}
 
Example #17
Source File: CAdESService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public DSSDocument signDocument(final DSSDocument toSignDocument, final CAdESSignatureParameters parameters, SignatureValue signatureValue)
		throws DSSException {
	Objects.requireNonNull(toSignDocument, "toSignDocument cannot be null!");
	Objects.requireNonNull(parameters, "SignatureParameters cannot be null!");
	Objects.requireNonNull(signatureValue, "SignatureValue cannot be null!");

	assertSigningDateInCertificateValidityRange(parameters);
	final SignaturePackaging packaging = parameters.getSignaturePackaging();
	assertSignaturePackaging(packaging);

	final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
	final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue.getValue());
	final DigestCalculatorProvider dcp = getDigestCalculatorProvider(toSignDocument, parameters);
	final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = cmsSignedDataBuilder.getSignerInfoGeneratorBuilder(dcp, parameters, true);
	final CMSSignedData originalCmsSignedData = getCmsSignedData(toSignDocument, parameters);
	if ((originalCmsSignedData == null) && SignaturePackaging.DETACHED.equals(packaging) && Utils.isCollectionEmpty(parameters.getDetachedContents())) {
		parameters.setDetachedContents(Arrays.asList(toSignDocument));
	}

	final CMSSignedDataGenerator cmsSignedDataGenerator = cmsSignedDataBuilder.createCMSSignedDataGenerator(parameters, customContentSigner,
			signerInfoGeneratorBuilder, originalCmsSignedData);

	final DSSDocument toSignData = getToSignData(toSignDocument, parameters, originalCmsSignedData);
	final CMSTypedData content = CMSUtils.getContentToBeSign(toSignData);

	final boolean encapsulate = !SignaturePackaging.DETACHED.equals(packaging);
	final CMSSignedData cmsSignedData = CMSUtils.generateCMSSignedData(cmsSignedDataGenerator, content, encapsulate);
	DSSDocument signature = new CMSSignedDocument(cmsSignedData);

	final SignatureLevel signatureLevel = parameters.getSignatureLevel();
	if (!SignatureLevel.CAdES_BASELINE_B.equals(signatureLevel)) {
		// true: Only the last signature will be extended
		final SignatureExtension<CAdESSignatureParameters> extension = getExtensionProfile(parameters, true);
		signature = extension.extendSignatures(signature, parameters);
	}
	signature.setName(getFinalFileName(toSignDocument, SigningOperation.SIGN, parameters.getSignatureLevel()));
	parameters.reinitDeterministicId();
	return signature;
}
 
Example #18
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private SignedData buildSignedData(X509Cert cert) throws OperationException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isIncludeCaCert()) {
      refreshCa();
      cmsSignedDataGen.addCertificate(caCert.toBcCert());
    }
    CMSSignedData signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
    return SignedData.getInstance(signedData.toASN1Structure().getContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex);
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
}
 
Example #19
Source File: CMSSignedDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #20
Source File: CertificateAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * To create a encoded signature from certificate.
 *
 * @param x509Certificate Certificate that need to be encoded.
 * @return Encoded signature.
 * @throws CertificateEncodingException Certificate Encoding Exception.
 * @throws CMSException                 CMS Exception.
 * @throws IOException                  IO Exception.
 */
private String createEncodedSignature(X509Certificate x509Certificate) throws CertificateEncodingException,
        CMSException, IOException {
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    List<X509Certificate> list = new ArrayList<>();
    list.add(x509Certificate);
    JcaCertStore store = new JcaCertStore(list);
    generator.addCertificates(store);
    AtomicReference<CMSSignedData> degenerateSd = new AtomicReference<>(generator.generate(new CMSAbsentContent()));
    byte[] signature = degenerateSd.get().getEncoded();
    return Base64.getEncoder().encodeToString(signature);
}
 
Example #21
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
static CMSSignedData createDegeneratedSigendData(X509Cert... certs)
    throws CMSException, CertificateException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  for (X509Cert cert : certs) {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
  }
  return cmsSignedDataGen.generate(new CMSAbsentContent());
}
 
Example #22
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #23
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #24
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE));
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #25
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE)).booleanValue();
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #26
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean) SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #27
Source File: SignHelper.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
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 #28
Source File: V1SchemeSigner.java    From walle with Apache License 2.0 5 votes vote down vote up
private static byte[] generateSignatureBlock(
        SignerConfig signerConfig, byte[] signatureFileBytes)
                throws InvalidKeyException, CertificateEncodingException, SignatureException {
    JcaCertStore certs = new JcaCertStore(signerConfig.certificates);
    X509Certificate signerCert = signerConfig.certificates.get(0);
    String jcaSignatureAlgorithm =
            getJcaSignatureAlgorithm(
                    signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm);
    try {
        ContentSigner signer =
                new JcaContentSignerBuilder(jcaSignatureAlgorithm)
                .build(signerConfig.privateKey);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addSignerInfoGenerator(
                new SignerInfoGeneratorBuilder(
                        new JcaDigestCalculatorProviderBuilder().build(),
                        SignerInfoSignatureAlgorithmFinder.INSTANCE)
                        .setDirectSignature(true)
                        .build(signer, new JcaX509CertificateHolder(signerCert)));
        gen.addCertificates(certs);

        CMSSignedData sigData =
                gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
            DEROutputStream dos = new DEROutputStream(out);
            dos.writeObject(asn1.readObject());
        }
        return out.toByteArray();
    } catch (OperatorCreationException | CMSException | IOException e) {
        throw new SignatureException("Failed to generate signature", e);
    }
}
 
Example #29
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey,
        PrivateKey privateKey)
                    throws IOException,
                    CertificateEncodingException,
                    OperatorCreationException,
                    CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(
                                   "SHA1with" + privateKey.getAlgorithm())
                               .build(privateKey);
    gen.addSignerInfoGenerator(
        new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder()
            .build())
        .setDirectSignature(true)
        .build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}
 
Example #30
Source File: LocalSignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Write the certificate file with a digital signature.
 */
private void writeSignatureBlock(CMSTypedData data,
                                 X509Certificate publicKey,
                                 PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" +
                                                                   privateKey.getAlgorithm()).build(
            privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                                                                         .build()).setDirectSignature(
            true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}