org.bouncycastle.cms.CMSProcessableByteArray Java Examples

The following examples show how to use org.bouncycastle.cms.CMSProcessableByteArray. 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: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

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

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

   return result;
}
 
Example #2
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
    byte[] encryptedData = null;
    if (null != data && null != encryptionCertificate) {
        CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
        JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
        cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
        CMSTypedData msg = new CMSProcessableByteArray(data);
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build();
        CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
        encryptedData = cmsEnvelopedData.getEncoded();
    }
    return encryptedData;
}
 
Example #3
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

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

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

   return result;
}
 
Example #4
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 #5
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 #6
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

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

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

   return result;
}
 
Example #7
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * The code completely ignores the <b>SubFilter</b> of the signature.
 * It is appropriate for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b>
 * but will fail for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>.
 * </p>
 * <p>
 * The example document has been signed with a signatures with
 * <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTest() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes);
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        // result if false
        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}
 
Example #8
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

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

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

   return result;
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Closes the Jar archive by creating the manifest, and signing the archive.
 * @throws IOException
 * @throws SigningException
 */
public void close() throws IOException, SigningException {
    if (mManifest != null) {
        // write the manifest to the jar file
        mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
        mManifest.write(mOutputJar);

        try {
            // CERT.SF
            Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm());
            signature.initSign(mKey);
            mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF"));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            writeSignatureFile(baos);
            byte[] signedData = baos.toByteArray();
            mOutputJar.write(signedData);

            // CERT.*
            mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm()));
            writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey);
        } catch (Exception e) {
            throw new SigningException(e);
        }
    }

    mOutputJar.close();
    mOutputJar = null;
}
 
Example #14
Source File: LocalSignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the Jar archive by creating the manifest, and signing the archive.
 *
 * @throws IOException
 * @throws SigningException
 */
public void close() throws IOException, SigningException {
    if (mManifest != null) {
        // write the manifest to the jar file
        mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
        mManifest.write(mOutputJar);

        try {
            // CERT.SF
            Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm());
            signature.initSign(mKey);
            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF"));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF"));
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            writeSignatureFile(baos);
            byte[] signedData = baos.toByteArray();
            mOutputJar.write(signedData);

            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm()));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" +
                                                             mSignFile +
                                                             "." +
                                                             mKey.getAlgorithm()));
            }
            // CERT.*
            writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey);
        } catch (Exception e) {
            throw new SigningException(e);
        }
    }

    mOutputJar.close();
    mOutputJar = null;
}
 
Example #15
Source File: SignerJar.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #16
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 #17
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 #18
Source File: RaUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static <T> T transform(byte[] signedContent, Class<T> clazz) throws TechnicalConnectorException {
   try {
      CMSSignedData s = new CMSSignedData(signedContent);
      CMSProcessableByteArray cpb = (CMSProcessableByteArray)s.getSignedContent();
      byte[] unsignedContent = (byte[])((byte[])cpb.getContent());
      MarshallerHelper<T, T> helper = new MarshallerHelper(clazz, clazz);
      return helper.toObject(unsignedContent);
   } catch (CMSException var6) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_CRYPTO, var6, new Object[0]);
   }
}
 
Example #19
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 #20
Source File: RaUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static <T> T transform(byte[] signedContent, Class<T> clazz) throws TechnicalConnectorException {
   try {
      CMSSignedData s = new CMSSignedData(signedContent);
      CMSProcessableByteArray cpb = (CMSProcessableByteArray)s.getSignedContent();
      byte[] unsignedContent = (byte[])((byte[])cpb.getContent());
      MarshallerHelper<T, T> helper = new MarshallerHelper(clazz, clazz);
      return helper.toObject(unsignedContent);
   } catch (CMSException var6) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_CRYPTO, var6, new Object[0]);
   }
}
 
Example #21
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 #22
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public SignatureVerificationResult verify(byte[] content, byte[] signature, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

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

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

   return result;
}
 
Example #23
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setContent(byte[] content) {
    this.content = new CMSProcessableByteArray(content);
}
 
Example #24
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 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 #25
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 #26
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <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 #27
Source File: CMSUtils.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static CMSSignedData generateDetachedCMSSignedData(final CMSSignedDataGenerator generator, final CMSProcessableByteArray content)
		throws DSSException {
	return generateCMSSignedData(generator, content, false);
}
 
Example #28
Source File: PAdESService.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public ToBeSigned getDataToSign(final DSSDocument toSignDocument, final PAdESSignatureParameters parameters) throws DSSException {
	Objects.requireNonNull(toSignDocument, "toSignDocument cannot be null!");
	Objects.requireNonNull(parameters, "SignatureParameters cannot be null!");

	assertSigningDateInCertificateValidityRange(parameters);

	final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
	final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId());

	final byte[] messageDigest = computeDocumentDigest(toSignDocument, parameters);

	SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = padesCMSSignedDataBuilder.getSignerInfoGeneratorBuilder(parameters, messageDigest);

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

	final CMSProcessableByteArray content = new CMSProcessableByteArray(messageDigest);

	CMSUtils.generateDetachedCMSSignedData(generator, content);

	final byte[] dataToSign = customContentSigner.getOutputStream().toByteArray();
	return new ToBeSigned(dataToSign);
}
 
Example #29
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);
  }
}