org.bouncycastle.cms.CMSAbsentContent Java Examples

The following examples show how to use org.bouncycastle.cms.CMSAbsentContent. 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: 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 #2
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 #3
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 #4
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 #5
Source File: CertificateAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * To create a encoded signature from certificate.
 *
 * @param x509Certificate Certificate that need to be encoded.
 * @return Encoded signature.
 * @throws CertificateEncodingException Certificate Encoding Exception.
 * @throws CMSException                 CMS Exception.
 * @throws IOException                  IO Exception.
 */
private String createEncodedSignature(X509Certificate x509Certificate) throws CertificateEncodingException,
        CMSException, IOException {
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    List<X509Certificate> list = new ArrayList<>();
    list.add(x509Certificate);
    JcaCertStore store = new JcaCertStore(list);
    generator.addCertificates(store);
    AtomicReference<CMSSignedData> degenerateSd = new AtomicReference<>(generator.generate(new CMSAbsentContent()));
    byte[] signature = degenerateSd.get().getEncoded();
    return Base64.getEncoder().encodeToString(signature);
}
 
Example #6
Source File: CMSUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the original document from the provided {@code cmsSignedData}
 * @param cmsSignedData {@link CMSSignedData} to get original document from
 * @return original {@link DSSDocument}
 */
public static DSSDocument getOriginalDocument(CMSSignedData cmsSignedData, List<DSSDocument> detachedDocuments) {
	CMSTypedData signedContent = null;
	if (cmsSignedData != null) {
		signedContent = cmsSignedData.getSignedContent();
	}
	if (signedContent != null && !(signedContent instanceof CMSAbsentContent)) {
		return new InMemoryDocument(CMSUtils.getSignedContent(signedContent));
	} else if (Utils.collectionSize(detachedDocuments) == 1) {
		return detachedDocuments.get(0);
	} else {
		throw new DSSException("Only enveloping and detached signatures are supported");
	}
}
 
Example #7
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ContentInfo createSignedData(CertificateList crl) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  cmsSignedDataGen.addCRL(new X509CRLHolder(crl));

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

  return cmsSigneddata.toASN1Structure();
}
 
Example #8
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ScepCaCertRespBytes(X509Cert caCert, X509Cert responderCert)
    throws CMSException, CertificateException {
  Args.notNull(caCert, "caCert");
  Args.notNull(responderCert, "responderCert");

  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  try {
    cmsSignedDataGen.addCertificate(caCert.toBcCert());
    cmsSignedDataGen.addCertificate(responderCert.toBcCert());
    CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent());
    bytes = degenerateSignedData.getEncoded();
  } catch (IOException ex) {
    throw new CMSException("could not build CMS SignedDta");
  }
}
 
Example #9
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private SignedData buildSignedData(X509Cert cert) throws OperationException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isIncludeCaCert()) {
      refreshCa();
      cmsSignedDataGen.addCertificate(caCert.toBcCert());
    }
    CMSSignedData signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
    return SignedData.getInstance(signedData.toASN1Structure().getContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex);
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
}
 
Example #10
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 #11
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 #12
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 <code>sign</code> method after fixing some errors. The
 * OP's original method is {@link #signBySnox(InputStream)}. The
 * errors were
 * </p>
 * <ul>
 * <li>multiple attempts at reading the {@link InputStream} parameter;
 * <li>convoluted creation of final CMS container.
 * </ul>
 * <p>
 * Additionally this method uses SHA256 instead of SHA-1.
 * </p>
 */
public byte[] signWithSeparatedHashing(InputStream content) throws IOException
{
    try
    {
        // Digest generation step
        MessageDigest md = MessageDigest.getInstance("SHA256", "BC");
        byte[] digest = md.digest(IOUtils.toByteArray(content));

        // Separate signature container creation step
        List<Certificate> certList = Arrays.asList(chain);
        JcaCertStore certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha256withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return s.getEncoded();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example #13
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);
  }
}