org.bouncycastle.cms.SignerInfoGenerator Java Examples

The following examples show how to use org.bouncycastle.cms.SignerInfoGenerator. 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: 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 #2
Source File: SMIMEKeyHolder.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an <CODE>SMIMESignedGenerator</CODE>. Includes a signer private key and certificate,
 * and a pool of certs and cerls (if any) to go with the signature.
 * @return The generated SMIMESignedGenerator.
 */
public SMIMESignedGenerator createGenerator() throws CertStoreException, SMIMEException, OperatorCreationException,
    CertificateEncodingException {
    
    // create the generator for creating an smime/signed message
    SMIMESignedGenerator generator = new SMIMESignedGenerator();
    
    // add a signer to the generator - this specifies we are using SHA1
    // the encryption algorithm used is taken from the key
    SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder()
        .setProvider("BC")
        .build("SHA1withRSA", privateKey, certificate);
    generator.addSignerInfoGenerator(signerInfoGenerator);
    
    // add our pool of certs and cerls (if any) to go with the signature
    generator.addCertificates(jcaCertStore);
    
    return generator;
    
}
 
Example #3
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 #4
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 #5
Source File: CMSSignedDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param signerInfoGeneratorBuilder
 *            the SignerInfoGeneratorBuilder
 * @param contentSigner
 *            the content signer
 * @param parameters
 *            set of the driving signing parameters
 * @return SignerInfoGenerator generated by the given builder according to the parameters
 * @throws OperatorCreationException
 */
private SignerInfoGenerator getSignerInfoGenerator(final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder, final ContentSigner contentSigner,
		CAdESSignatureParameters parameters) throws OperatorCreationException {
	final CertificateToken signingCertificate = parameters.getSigningCertificate();

	if (signingCertificate == null && parameters.isGenerateTBSWithoutCertificate()) {
		// Generate data-to-be-signed without signing certificate
		final SignerId signerId = new SignerId(DSSUtils.EMPTY_BYTE_ARRAY);
		return signerInfoGeneratorBuilder.build(contentSigner, signerId.getSubjectKeyIdentifier());
	}

	final X509CertificateHolder certHolder = DSSASN1Utils.getX509CertificateHolder(signingCertificate);
	return signerInfoGeneratorBuilder.build(contentSigner, certHolder);
}
 
Example #6
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 #7
Source File: RequestSigner.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
     * Signs a time stamp request
     *
     * @param privateKey private key to sign with
     * @param certificates certificate chain
     * @param request request to be signed
     * @return The signed request
     */
    public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) {
        try {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
            Security.addProvider(new BouncyCastleProvider());

            X509Certificate signCert = (X509Certificate) certificates[0];
            List<X509Certificate> certList = new ArrayList<>();
            certList.add(signCert);

            // setup the generator
            CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
            String varAlgorithm = null;
            if (algorithm != null && !algorithm.isEmpty()){
            	varAlgorithm = algorithm;
            }else{
            	
            	// If is WINDOWS, is ONLY WORKS with SHA256
				if (Configuration.getInstance().getSO().toLowerCase().indexOf("indows") > 0) {
					logger.info(timeStampMessagesBundle.getString("info.timestamp.winhash"));
					
					varAlgorithm = "SHA256withRSA";
				}else{
					logger.info(timeStampMessagesBundle.getString("info.timestamp.linuxhash"));					
					varAlgorithm = "SHA512withRSA";
				}
				
            }
            	
            SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert);
            generator.addSignerInfoGenerator(signerInfoGenerator);

            Store<?> certStore = new JcaCertStore(certList);
            generator.addCertificates(certStore);

//            Store crlStore = new JcaCRLStore(crlList);
//            generator.addCRLs(crlStore);
            // Create the signed data object
            CMSTypedData data = new CMSProcessableByteArray(request);
            CMSSignedData signed = generator.generate(data, true);
            return signed.getEncoded();

        } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
            logger.info(ex.getMessage());
        }
        return null;
    }
 
Example #8
Source File: NextCaMessage.java    From xipki with Apache License 2.0 4 votes vote down vote up
public ContentInfo encode(PrivateKey signingKey, X509Cert signerCert,
    X509Cert[] cmsCertSet) throws MessageEncodingException {
  Args.notNull(signingKey, "signingKey");
  Args.notNull(signerCert, "signerCert");

  try {
    CMSSignedDataGenerator degenerateSignedData = new CMSSignedDataGenerator();
    degenerateSignedData.addCertificate(caCert.toBcCert());
    if (CollectionUtil.isNotEmpty(raCerts)) {
      for (X509Cert m : raCerts) {
        degenerateSignedData.addCertificate(m.toBcCert());
      }
    }

    byte[] degenratedSignedDataBytes = degenerateSignedData.generate(
        new CMSAbsentContent()).getEncoded();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

    // I don't known which hash algorithm is supported by the client, use SHA-1
    String signatureAlgo = getSignatureAlgorithm(signingKey, HashAlgo.SHA1);
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgo).build(signingKey);

    // signerInfo
    JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(
        new BcDigestCalculatorProvider());

    signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator());

    SignerInfoGenerator signerInfo = signerInfoBuilder.build(signer, signerCert.toBcCert());
    generator.addSignerInfoGenerator(signerInfo);

    CMSTypedData cmsContent = new CMSProcessableByteArray(CMSObjectIdentifiers.signedData,
        degenratedSignedDataBytes);

    // certificateSet
    ScepUtil.addCmsCertSet(generator, cmsCertSet);
    return generator.generate(cmsContent, true).toASN1Structure();
  } catch (CMSException | CertificateEncodingException | IOException
      | OperatorCreationException ex) {
    throw new MessageEncodingException(ex);
  }
}