org.bouncycastle.cert.jcajce.JcaCertStore Java Examples
The following examples show how to use
org.bouncycastle.cert.jcajce.JcaCertStore.
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: CMSSignedDataBuilder.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
/** * The order of the certificates is important, the fist one must be the signing certificate. * * @return a store with the certificate chain of the signing certificate. The {@code Collection} is unique. */ private JcaCertStore getJcaCertStore(final Collection<CertificateToken> certificateChain, CAdESSignatureParameters parameters) { BaselineBCertificateSelector certificateSelectors = new BaselineBCertificateSelector(certificateVerifier, parameters); List<CertificateToken> certificatesToAdd; if (parameters.getSigningCertificate() == null && parameters.isGenerateTBSWithoutCertificate()) { certificatesToAdd = new ArrayList<>(); } else { certificatesToAdd = certificateSelectors.getCertificates(); } for (CertificateToken certificateToken : certificatesToAdd) { if (!certificateChain.contains(certificateToken)) { certificateChain.add(certificateToken); } } try { final Collection<X509Certificate> certs = new ArrayList<>(); for (final CertificateToken certificateInChain : certificateChain) { certs.add(certificateInChain.getCertificate()); } return new JcaCertStore(certs); } catch (CertificateEncodingException e) { throw new DSSException(e); } }
Example #2
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 6 votes |
/** * 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 #3
Source File: CertificateManagementServiceImplTests.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
@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: CertificateManagementServiceImplTests.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
@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 #5
Source File: CreateMultipleVisualizations.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: BouncyCastleCrypto.java From tutorials with MIT License | 5 votes |
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 #7
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #8
Source File: ScepUtil.java From xipki with Apache License 2.0 | 5 votes |
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 #9
Source File: SignatureBlockGenerator.java From fdroidclient with GNU General Public License v3.0 | 5 votes |
/** * 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 #10
Source File: CMSSignedDataBuilder.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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 #11
Source File: CertificateAuthenticatorTest.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
/** * 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 #12
Source File: ZipUtils.java From isu with GNU General Public License v3.0 | 5 votes |
/** Sign data and write the digital signature to 'out'. */ private static void writeSignatureBlock( CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList < X509Certificate > certList = new ArrayList < > (1); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey)) .setProvider(sBouncyCastleProvider) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder() .setProvider(sBouncyCastleProvider) .build()) .setDirectSignature(true) .build(signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); }
Example #13
Source File: V1SchemeSigner.java From walle with Apache License 2.0 | 5 votes |
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 #14
Source File: SignedJarBuilder.java From javaide with GNU General Public License v3.0 | 5 votes |
/** 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 #15
Source File: LocalSignedJarBuilder.java From atlas with Apache License 2.0 | 5 votes |
/** * 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 #16
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 5 votes |
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 #17
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #18
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #19
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #20
Source File: CmsSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #21
Source File: RequestSigner.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
/** * 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 #22
Source File: CreateSignature.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest"> * Create pkcs7 signature from file digest * </a> * <p> * The OP's own <code>sign</code> method which has some errors. These * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}. * </p> */ public byte[] signBySnox(InputStream content) throws IOException { // testSHA1WithRSAAndAttributeTable try { MessageDigest md = MessageDigest.getInstance("SHA1", "BC"); List<Certificate> certList = new ArrayList<Certificate>(); CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content)); certList.addAll(Arrays.asList(chain)); Store<?> certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content))))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(chain[0].getEncoded()); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); gen.addSignerInfoGenerator(builder.build( new BcRSAContentSignerBuilder(sha1withRSA, new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA)) .build(PrivateKeyFactory.createKey(pk.getEncoded())), new JcaX509CertificateHolder(cert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); return new CMSSignedData(msg, s.getEncoded()).getEncoded(); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
Example #23
Source File: CreateSignature.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest"> * Create pkcs7 signature from file digest * </a> * <p> * The OP's <code>sign</code> method after fixing some errors. The * OP's original method is {@link #signBySnox(InputStream)}. The * errors were * </p> * <ul> * <li>multiple attempts at reading the {@link InputStream} parameter; * <li>convoluted creation of final CMS container. * </ul> * <p> * Additionally this method uses SHA256 instead of SHA-1. * </p> */ public byte[] signWithSeparatedHashing(InputStream content) throws IOException { try { // Digest generation step MessageDigest md = MessageDigest.getInstance("SHA256", "BC"); byte[] digest = md.digest(IOUtils.toByteArray(content)); // Separate signature container creation step List<Certificate> certList = Arrays.asList(chain); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(chain[0].getEncoded()); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); gen.addSignerInfoGenerator(builder.build( new BcRSAContentSignerBuilder(sha256withRSA, new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA)) .build(PrivateKeyFactory.createKey(pk.getEncoded())), new JcaX509CertificateHolder(cert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); return s.getEncoded(); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
Example #24
Source File: SMimePackageEncryptor.java From ats-framework with Apache License 2.0 | 4 votes |
@PublicAtsApi public Package sign( Package sourcePackage ) throws ActionException { try { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } KeyStore ks = getKeystore(); // TODO wrap exception with possible causes and add some hint PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray()); // Get whole certificate chain Certificate[] certArr = ks.getCertificateChain(aliasOrCN); // Pre 4.0.6 behavior was not to attach full cert. chain X509Certificate cer = (X509Certificate) ks.getCertificate(aliasOrCN); if (certArr.length >= 1) { LOG.debug("Found certificate of alias: " + aliasOrCN + ". Lenght of cert chain: " + certArr.length + ", child cert:" + certArr[0].toString()); } X509Certificate childCert = (X509Certificate) certArr[0]; /* Create the SMIMESignedGenerator */ ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(childCert.getIssuerDN() .getName()), childCert.getSerialNumber()))); SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.aES128_CBC); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); if (signatureAlgorithm == null) { // not specified explicitly // TODO check defaults to be used signatureAlgorithm = SignatureAlgorithm.DSA.equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA"; } SMIMESignedGenerator signer = new SMIMESignedGenerator(); JcaSimpleSignerInfoGeneratorBuilder signerGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder(); signerGeneratorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); signerGeneratorBuilder.setSignedAttributeGenerator(new AttributeTable(attributes)); signer.addSignerInfoGenerator(signerGeneratorBuilder.build(signatureAlgorithm, privateKey, childCert)); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); for (int i = 0; i < certArr.length; i++) { // first add child cert, and CAs certList.add((X509Certificate) certArr[i]); } Store<?> certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ Session session = Session.getDefaultInstance(System.getProperties(), null); MimeMultipart mm = signer.generate(getMimeMessage(sourcePackage)); MimeMessage signedMessage = new MimeMessage(session); /* Set all original MIME headers in the signed message */ Enumeration<?> headers = getMimeMessage(sourcePackage).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); return new MimePackage(signedMessage); } catch (Exception e) { throw new ActionException(EXCEPTION_WHILE_SIGNING, e); } }
Example #25
Source File: RsaSsaPss.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * For some tests I needed SHA256withRSAandMGF1 CMS signatures. */ @Test public void testCreateSimpleSignatureContainer() throws CMSException, GeneralSecurityException, OperatorCreationException, IOException { byte[] message = "SHA256withRSAandMGF1".getBytes(); CMSTypedData msg = new CMSProcessableByteArray(message); List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSAandMGF1").setProvider("BC").build(signKP.getPrivate()); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha1Signer, signCert)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(msg, false); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.bin").toPath(), message); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.p7s").toPath(), sigData.getEncoded()); boolean verifies = sigData.verifySignatures(new SignerInformationVerifierProvider() { @Override public SignerInformationVerifier get(SignerId sid) throws OperatorCreationException { if (sid.getSerialNumber().equals(origCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for OrigCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(origCert); } if (sid.getSerialNumber().equals(signCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for SignCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(signCert); } System.out.println("SignerInformationVerifier requested for unknown " + sid); return null; } }); System.out.println("Verifies? " + verifies); }
Example #26
Source File: SMIMEKeyHolder.java From james-project with Apache License 2.0 | 4 votes |
/** * Creates a new instance of <CODE>KeyHolder</CODE> using {@link java.security.KeyStore} related parameters. * @param keyStoreFileName The (absolute) file name of the .keystore file to load the keystore from. * @param keyStorePassword The (optional) password used to check the integrity of the keystore. * If given, it is used to check the integrity of the keystore data, * otherwise, if null, the integrity of the keystore is not checked. * @param keyAlias The alias name of the key. * If missing (is null) and if there is only one key in the keystore, will default to it. * @param keyAliasPassword The password of the alias for recovering the key. * If missing (is null) will default to <I>keyStorePassword</I>. At least one of the passwords must be provided. * @param keyStoreType The type of keystore. * If missing (is null) will default to the keystore type as specified in the Java security properties file, * or the string "jks" (acronym for "Java keystore") if no such property exists. * @throws java.security.KeyStoreException Thrown when the <I>keyAlias</I> is specified and not found, * or is not specified and either no alias is found or more than one is found. * @see java.security.KeyStore#getDefaultType * @see java.security.KeyStore#getInstance(String) * @see java.security.KeyStore#load * @see java.security.KeyStore#getKey * @see java.security.KeyStore#getCertificate */ public SMIMEKeyHolder(String keyStoreFileName, String keyStorePassword, String keyAlias, String keyAliasPassword, String keyStoreType) throws KeyStoreException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableKeyException, NoSuchProviderException { try { InitJCE.init(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { NoSuchProviderException ex = new NoSuchProviderException("Error during cryptography provider initialization. Has bcprov-jdkxx-yyy.jar been copied in the lib directory or installed in the system?"); ex.initCause(e); throw ex; } if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(new BufferedInputStream(new FileInputStream(keyStoreFileName)), keyStorePassword.toCharArray()); Enumeration<String> aliases = keyStore.aliases(); if (keyAlias == null) { if (aliases.hasMoreElements()) { keyAlias = aliases.nextElement(); } else { throw new KeyStoreException("No alias was found in keystore."); } if (aliases.hasMoreElements()) { throw new KeyStoreException("No <keyAlias> was given and more than one alias was found in keystore."); } } if (keyAliasPassword == null) { keyAliasPassword = keyStorePassword; } this.privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyAliasPassword.toCharArray()); if (this.privateKey == null) { throw new KeyStoreException("The \"" + keyAlias + "\" PrivateKey alias was not found in keystore."); } this.certificate = (X509Certificate) keyStore.getCertificate(keyAlias); if (this.certificate == null) { throw new KeyStoreException("The \"" + keyAlias + "\" X509Certificate alias was not found in keystore."); } java.security.cert.Certificate[] certificateChain = keyStore.getCertificateChain(keyAlias); ArrayList<java.security.cert.Certificate> certList = new ArrayList<>(); if (certificateChain == null) { certList.add(this.certificate); } else { Collections.addAll(certList, certificateChain); } // create a CertStore containing the certificates we want carried // in the signature this.certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); jcaCertStore = new JcaCertStore(certList); }