Java Code Examples for org.bouncycastle.cms.CMSSignedData#getEncoded()
The following examples show how to use
org.bouncycastle.cms.CMSSignedData#getEncoded() .
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: CAdESSigner.java From signer with GNU Lesser General Public License v3.0 | 6 votes |
@Override public byte[] doCounterSign(byte[] previewCMSSignature) { try { Security.addProvider(new BouncyCastleProvider()); // Reading a P7S file that is preview signature. CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature); // Build BouncyCastle object that is a set of signatures Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners(); for (SignerInformation previewSigner : previewSigners) { // build a counter-signature per previewSignature byte[] previewSignatureFromSigner = previewSigner.getSignature(); CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner)); cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData, previewSigner.getSID()); } return cmsPreviewSignedData.getEncoded(); } catch (Throwable error) { throw new SignerException(error); } }
Example 2
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 3
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 4
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 5
Source File: SignerJar.java From Launcher with GNU General Public License v3.0 | 5 votes |
/** * Returns the CMS signed data. */ private byte[] signSigFile(byte[] sigContents) throws Exception { CMSSignedDataGenerator gen = this.gen.get(); CMSTypedData cmsData = new CMSProcessableByteArray(sigContents); CMSSignedData signedData = gen.generate(cmsData, false); return signedData.getEncoded(); }
Example 6
Source File: PKCS7Manager.java From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") public static byte[] buildPKCS7(String digestOID, byte[] data, X509Certificate cert, byte[] signature, byte[] hash, Date dateTime) throws Exception { if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider()); CMSSignedDataWrapper cmsSignedDataWrapper = new CMSSignedDataWrapper(); byte[] content = data; if (data != null && isPKCS7File(data)) { // Here I have to add all the already presents signatures CMSSignedData cmsSignedDataOLD = new CMSSignedData(data); cmsSignedDataWrapper.addSignerInformation(cmsSignedDataOLD.getSignerInfos()); cmsSignedDataWrapper.addCert(cmsSignedDataOLD.getCertificates()); cmsSignedDataWrapper.addCrl(cmsSignedDataOLD.getCRLs()); content = extractData(data); } cmsSignedDataWrapper.addSignerInformation(digestOID, CMSSignedDataGenerator.ENCRYPTION_RSA, cert, signature, hash, dateTime); cmsSignedDataWrapper.addCert(cert.getEncoded()); if (content != null) cmsSignedDataWrapper.setContent(content); else cmsSignedDataWrapper.setEncapsulate(false); CMSSignedData cmsSignedData = cmsSignedDataWrapper.buildCMSSignedData(); return cmsSignedData.getEncoded(); }
Example 7
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 8
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 9
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 10
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 11
Source File: ScepResponder.java From xipki with Apache License 2.0 | 5 votes |
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 12
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 13
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 14
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 15
Source File: CAdESSignatureExtension.java From dss with GNU Lesser General Public License v2.1 | 4 votes |
public ASN1Object getTimeStampAttributeValue(final byte[] messageToTimestamp, final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) { try { if (LOG.isDebugEnabled()) { LOG.debug("Message to timestamp is: {}", Utils.toHex(messageToTimestamp)); } byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp); if (LOG.isDebugEnabled()) { LOG.debug("Digested ({}) message to timestamp is {}", timestampDigestAlgorithm, Utils.toHex(timestampDigest)); } final TimestampBinary timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm, timestampDigest); CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getBytes()); // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified if (attributesForTimestampToken != null) { // timeStampToken contains one and only one signer final SignerInformation signerInformation = cmsSignedDataTimeStampToken.getSignerInfos().getSigners().iterator().next(); AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation); for (final Attribute attributeToAdd : attributesForTimestampToken) { final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType(); final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0); unsignedAttributes = unsignedAttributes.add(attrType, objectAt); } // Unsigned attributes cannot be empty (RFC 5652 5.3) if (unsignedAttributes.size() == 0) { unsignedAttributes = null; } final SignerInformation newSignerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes); final List<SignerInformation> signerInformationList = new ArrayList<>(); signerInformationList.add(newSignerInformation); final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList); cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken, newSignerStore); } final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded(); return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes); } catch (IOException | CMSException e) { throw new DSSException("Cannot obtain timestamp attribute value.", e); } }
Example 16
Source File: DSSASN1Utils.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
/** * Returns an ASN.1 encoded bytes representing the {@code CMSSignedData} * * @param cmsSignedData * {@code CMSSignedData} * @return the binary of the {@code CMSSignedData} @ if the {@code * CMSSignedData} encoding fails */ public static byte[] getEncoded(final CMSSignedData cmsSignedData) { try { return cmsSignedData.getEncoded(); } catch (IOException e) { throw new DSSException("Unable to encode to DER", e); } }