org.bouncycastle.cms.CMSException Java Examples

The following examples show how to use org.bouncycastle.cms.CMSException. 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: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: ScepResponder.java    From xipki with 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
Source File: TimestampToken.java    From dss with 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 #4
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 #5
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #7
Source File: ScepResponder.java    From xipki with 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 #8
Source File: CMSSignedDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #9
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 #10
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: DetachedTimestampValidator.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #12
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #13
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #14
Source File: CAdESSignature.java    From dss with 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 #15
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 #16
Source File: CalculateDigest.java    From testarea-pdfbox2 with 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 File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #18
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #19
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 #20
Source File: CryptoExceptionTest.java    From athenz with 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 #21
Source File: CertificateManagementServiceImplTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@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 #22
Source File: CertificateManagementServiceImplTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@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 #23
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #24
Source File: CertificateAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@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 #25
Source File: SignHelper.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates the beast that can actually sign the data (for JKS, for other make it).
 */
public static CMSSignedDataGenerator createSignedDataGenerator(KeyStore keyStore, String keyAlias, String signAlgo, String keyPassword) throws KeyStoreException, OperatorCreationException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, CMSException {
    List<Certificate> certChain = new ArrayList<>(Arrays.asList(keyStore.getCertificateChain(keyAlias)));
    @SuppressWarnings("rawtypes")
    Store certStore = new JcaCertStore(certChain);
    Certificate cert = keyStore.getCertificate(keyAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword != null ? keyPassword.toCharArray() : null);
    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey);
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert);
    generator.addSignerInfoGenerator(sig);
    generator.addCertificates(certStore);
    return generator;
}
 
Example #26
Source File: ZipUtils.java    From isu with GNU General Public License v3.0 5 votes vote down vote up
/** 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 #27
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
public void write(OutputStream out) throws IOException, CMSException
{
    // read the content only one time
    IOUtils.copy(in, out);
    in.close();
}
 
Example #28
Source File: TimestampTokenTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void incorrectTimestamp() throws Exception {
	Exception exception = assertThrows(CMSException.class, () -> {
		new TimestampToken(new byte[] { 1, 2, 3 }, TimestampType.ARCHIVE_TIMESTAMP);
	});
	assertEquals("IOException reading content.", exception.getMessage());
}
 
Example #29
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
static CMSSignedData createDegeneratedSigendData(X509Cert... certs)
    throws CMSException, CertificateException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  for (X509Cert cert : certs) {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
  }
  return cmsSignedDataGen.generate(new CMSAbsentContent());
}
 
Example #30
Source File: CMSDocumentValidatorTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testCMSOnly() throws IOException, CMSException {
	CMSSignedData cmsSignedData = new CMSSignedData(new FileInputStream(PATH));
	CMSDocumentValidator validator = new CMSDocumentValidator(cmsSignedData);
	List<AdvancedSignature> signatures = validator.getSignatures();
	assertTrue(Utils.isCollectionNotEmpty(signatures));
}