Java Code Examples for org.bouncycastle.cms.CMSException

The following examples show how to use org.bouncycastle.cms.CMSException. These examples are extracted from open source projects. 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
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 Project: xipki   Source File: ScepResponder.java    License: Apache License 2.0 6 votes vote down vote up
private ContentInfo createSignedData(X509Cert cert) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();

  CMSSignedData cmsSigneddata;
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isSendCaCert()) {
      cmsSignedDataGen.addCertificate(caEmulator.getCaCert().toBcCert());
    }

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

  return cmsSigneddata.toASN1Structure();
}
 
Example 3
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 4
Source Project: xipki   Source File: ScepResponder.java    License: Apache License 2.0 6 votes vote down vote up
private SignedData getCrl(X509Ca ca, BigInteger serialNumber)
    throws FailInfoException, OperationException {
  if (!control.isSupportGetCrl()) {
    throw FailInfoException.BAD_REQUEST;
  }

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

  CMSSignedData signedData;
  try {
    signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex, "could not generate CMSSignedData");
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
  return SignedData.getInstance(signedData.toASN1Structure().getContent());
}
 
Example 5
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 6
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
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 8
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
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 10
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 11
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 12
/**
 * This specific doesn't verify in combination with its document, so
 * I wanted to look at its contents. As RSASSA-PSS does not allow to
 * read the original hash from the decrypted signature bytes, this
 * did not help at all.
 */
@Test
public void testDecryptSLMBC_PSS_Test1() throws IOException, CMSException, GeneralSecurityException
{
    Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding");
    KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");

    try (   InputStream resource = getClass().getResourceAsStream("SLMBC-PSS-Test1.cms")    )
    {
        CMSSignedData cmsSignedData = new CMSSignedData(resource);
        for (SignerInformation signerInformation : (Iterable<SignerInformation>)cmsSignedData.getSignerInfos().getSigners())
        {
            Collection<X509CertificateHolder> x509CertificateHolders = cmsSignedData.getCertificates().getMatches(signerInformation.getSID());
            if (x509CertificateHolders.size() != 1)
            {
                Assert.fail("Cannot uniquely determine signer certificate.");
            }
            X509CertificateHolder x509CertificateHolder = x509CertificateHolders.iterator().next();
            PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(x509CertificateHolder.getSubjectPublicKeyInfo().getEncoded()));
            cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] bytes = cipherNoPadding.doFinal(signerInformation.getSignature());

            Files.write(new File(RESULT_FOLDER, "SLMBC-PSS-Test1-signature-decoded").toPath(), bytes);
        }
    }
}
 
Example 13
private Timestamp checkTimeStampPDF(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		byte[] varTimeStamp = timeStamp;
		TimeStampOperator timeStampOperator = new TimeStampOperator();
		if (content != null){
			timeStampOperator.validate(content, varTimeStamp,null);
		}else{
			timeStampOperator.validate(null, varTimeStamp,hash);
		}			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
		| CMSException e) {
		throw new SignerException(e);
	}
	
}
 
Example 14
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example 15
/**
 * 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 16
Source Project: testarea-pdfbox2   Source File: CalculateDigest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/57926872/signed-pdf-content-digest-that-was-calculated-during-verification-is-diffrent-th">
 * Signed PDF content digest that was calculated during verification is diffrent than decripted digest from signature
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UlOZOp-UYllK7Ra35dggccoWdhcb_Ntp">
 * TEST-signed-pades-baseline-b.pdf
 * </a>
 * <p>
 * The code here demonstrates how to retrieve the messageDigest
 * signed attribute value from a signed PDF. For production use
 * obviously some null checks are required.
 * </p>
 */
@Test
public void testExtractMessageDigestAttributeForUser2893427() throws IOException, CMSException {
    try (   InputStream resource = getClass().getResourceAsStream("TEST-signed-pades-baseline-b.pdf")   ) {
        byte[] bytes = IOUtils.toByteArray(resource);
        PDDocument document = Loader.loadPDF(bytes);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        PDSignature sig = signatures.get(0);
        byte[] cmsBytes = sig.getContents(bytes);
        CMSSignedData cms = new CMSSignedData(cmsBytes);
        SignerInformation signerInformation = cms.getSignerInfos().iterator().next();
        Attribute attribute = signerInformation.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
        ASN1Encodable value = attribute.getAttributeValues()[0];
        System.out.printf("MessageDigest attribute value: %s\n", value);
    }
}
 
Example 17
Source Project: athenz   Source File: CryptoExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example 18
@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 19
@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 20
@Test(description = "This test case tests the behaviour of the CertificateAuthenticator for Certification "
        + "Verification Header requests")
public void testRequestCertificateVerificationHeader()
        throws CertificateEncodingException, IOException, CMSException, NoSuchFieldException,
        IllegalAccessException {
    Assert.assertTrue(certificateAuthenticator.canHandle(certificationVerificationRequest),
            "canHandle method returned false for a request with all the required header");
    AuthenticationInfo authenticationInfo = certificateAuthenticator
            .authenticate(certificationVerificationRequest, null);
    Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null");
    Assert.assertNull(authenticationInfo.getTenantDomain(), "Authentication got passed without proper certificate");
    authenticationInfo = certificateAuthenticator.authenticate(certificationVerificationRequest, null);
    Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null");
    Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            "Authentication failed for a valid request with " + CERTIFICATE_VERIFICATION_HEADER + " header");
}
 
Example 21
Source Project: dss   Source File: CAdESSignature.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method recreates a {@code SignerInformation} with the content using
 * a {@code CMSSignedDataParser}.
 *
 * @return
 * @throws CMSException
 * @throws IOException
 */
private SignerInformation recreateSignerInformation() throws CMSException, IOException {

	final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature
	CMSSignedDataParser cmsSignedDataParser = null;
	if (dssDocument instanceof DigestDocument) {
		cmsSignedDataParser = new CMSSignedDataParser(new PrecomputedDigestCalculatorProvider((DigestDocument) dssDocument), cmsSignedData.getEncoded());
	} else {
		try (InputStream inputStream = dssDocument.openStream()) {
			final CMSTypedStream signedContent = new CMSTypedStream(inputStream);
			cmsSignedDataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded());
			cmsSignedDataParser.getSignedContent().drain(); // Closes the stream
		}
	}

	final SignerId signerId = getSignerId();
	final SignerInformation signerInformationToCheck = cmsSignedDataParser.getSignerInfos().get(signerId);
	return signerInformationToCheck;
}
 
Example 22
@SuppressWarnings("rawtypes")
protected CMSSignedData regenerateCMSSignedData(CMSSignedData cmsSignedData, List<DSSDocument> detachedContents, Store certificatesStore,
		Store attributeCertificatesStore, Store crlsStore, Store otherRevocationInfoFormatStoreBasic, Store otherRevocationInfoFormatStoreOcsp) {
	try {

		final CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
		cmsSignedDataGenerator.addSigners(cmsSignedData.getSignerInfos());
		cmsSignedDataGenerator.addAttributeCertificates(attributeCertificatesStore);
		cmsSignedDataGenerator.addCertificates(certificatesStore);
		cmsSignedDataGenerator.addCRLs(crlsStore);
		cmsSignedDataGenerator.addOtherRevocationInfo(id_pkix_ocsp_basic, otherRevocationInfoFormatStoreBasic);
		cmsSignedDataGenerator.addOtherRevocationInfo(id_ri_ocsp_response, otherRevocationInfoFormatStoreOcsp);
		final boolean encapsulate = cmsSignedData.getSignedContent() != null;
		if (!encapsulate) {
			// CAdES can only sign one document
			final DSSDocument doc = detachedContents.get(0);
			final CMSTypedData content = CMSUtils.getContentToBeSign(doc);
			cmsSignedData = cmsSignedDataGenerator.generate(content, encapsulate);
		} else {
			cmsSignedData = cmsSignedDataGenerator.generate(cmsSignedData.getSignedContent(), encapsulate);
		}
		return cmsSignedData;
	} catch (CMSException e) {
		throw new DSSException(e);
	}
}
 
Example 23
/**
 * Returns a single TimestampToken to be validated
 * 
 * @return {@link TimestampToken}
 */
public TimestampToken getTimestamp() {
	if (timestampToken == null) {

		Objects.requireNonNull(certificateVerifier, "CertificateVerifier is not defined");
		Objects.requireNonNull(document, "The timestampFile must be defined!");
		Objects.requireNonNull(timestampType, "The TimestampType must be defined!");

		try {
			timestampToken = new TimestampToken(DSSUtils.toByteArray(document), timestampType);
			timestampToken.setFileName(document.getName());
			timestampToken.matchData(getTimestampedData());
			timestampToken.setTimestampScopes(getTimestampSignatureScope());
		} catch (CMSException | TSPException | IOException e) {
			throw new DSSException("Unable to parse timestamp", e);
		}
	}

	return timestampToken;
}
 
Example 24
Source Project: dss   Source File: TimestampToken.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean isValidCMSSignedData(SignerInformationVerifier signerInformationVerifier) {
	try {
		// Only validate the cryptographic validity
		SignerInformationStore signerInfos = timeStamp.toCMSSignedData().getSignerInfos();
		SignerInformation signerInformation = signerInfos.get(timeStamp.getSID());
		return signerInformation.verify(signerInformationVerifier);
	} catch (CMSException e) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Unable to validate the related CMSSignedData : ", e);
		} else {
			LOG.warn("Unable to validate the related CMSSignedData : {}", e.getMessage());
		}
		signatureInvalidityReason = e.getClass().getSimpleName() + " : " + e.getMessage();
		return false;
	}
}
 
Example 25
Source Project: xipki   Source File: EnvelopedDataDecryptor.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] decrypt(CMSEnvelopedData envData) throws MessageDecodingException {
  Args.notNull(envData, "envData");
  final RecipientInformationStore recipientInfos = envData.getRecipientInfos();
  RecipientInformation recipientInfo = null;
  EnvelopedDataDecryptorInstance decryptor = null;
  for (EnvelopedDataDecryptorInstance m : decryptors) {
    recipientInfo = recipientInfos.get(m.getRecipientId());
    if (recipientInfo != null) {
      decryptor = m;
      break;
    }
  }

  if (recipientInfo == null || decryptor == null) {
    throw new MessageDecodingException("missing expected key transfer recipient");
  }

  try {
    return recipientInfo.getContent(decryptor.getRecipient());
  } catch (CMSException ex) {
    throw new MessageDecodingException("could not decrypt the envelopedData");
  }
}
 
Example 26
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 27
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 28
Source Project: Launcher   Source File: SignHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates the beast that can actually sign the data (for JKS, for other make it).
 */
public static CMSSignedDataGenerator createSignedDataGenerator(KeyStore keyStore, String keyAlias, String signAlgo, String keyPassword) throws KeyStoreException, OperatorCreationException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, CMSException {
    List<Certificate> certChain = new ArrayList<>(Arrays.asList(keyStore.getCertificateChain(keyAlias)));
    @SuppressWarnings("rawtypes")
    Store certStore = new JcaCertStore(certChain);
    Certificate cert = keyStore.getCertificate(keyAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword != null ? keyPassword.toCharArray() : null);
    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey);
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert);
    generator.addSignerInfoGenerator(sig);
    generator.addCertificates(certStore);
    return generator;
}
 
Example 29
Source Project: Launcher   Source File: SignHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static CMSSignedDataGenerator createSignedDataGenerator(PrivateKey privateKey, Certificate cert, List<Certificate> certChain, String signAlgo) throws OperatorCreationException, CertificateEncodingException, CMSException {
    @SuppressWarnings("rawtypes")
    Store certStore = new JcaCertStore(certChain);
    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey);
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert);
    generator.addSignerInfoGenerator(sig);
    generator.addCertificates(certStore);
    return generator;
}
 
Example 30
Source Project: Launcher   Source File: SignJarTask.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static CMSSignedDataGenerator gen(LaunchServerConfig.JarSignerConf config, KeyStore c) {
    try {
        return SignHelper.createSignedDataGenerator(c,
                config.keyAlias, config.signAlgo, config.keyPass);
    } catch (CertificateEncodingException | UnrecoverableKeyException | KeyStoreException
            | OperatorCreationException | NoSuchAlgorithmException | CMSException e) {
        LogHelper.error(e);
        return null;
    }
}