Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData CMSSignedData.

Prototype

public CMSSignedData(ContentInfo sigData) throws CMSException 

Source Link

Usage

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * @param data/*from w  w  w  .j a  va 2 s  .  co  m*/
 *            byte array representing CMSSignedData
 * @param certPool
 *            can be null
 * @throws org.bouncycastle.cms.CMSException
 */
public CAdESSignature(final byte[] data, final CertificatePool certPool) throws CMSException {
    this(new CMSSignedData(data), certPool);
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

private List<TimestampToken> createTimestamps(final ASN1ObjectIdentifier attrType,
        final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) {

    final List<TimestampToken> timestampTokenList = new ArrayList<TimestampToken>();
    final AttributeTable attributes = attrType.equals(id_aa_ets_contentTimestamp)
            ? signerInformation.getSignedAttributes()
            : signerInformation.getUnsignedAttributes();
    if (attributes != null) {

        final ASN1EncodableVector allAttributes = attributes.getAll(attrType);
        for (int ii = 0; ii < allAttributes.size(); ii++) {
            final Attribute attribute = (Attribute) allAttributes.get(ii);
            final ASN1Set attrValues = attribute.getAttrValues();
            for (final ASN1Encodable value : attrValues.toArray()) {
                if (value instanceof DEROctetString) {
                    LOG.warn("Illegal content for timestamp (OID : " + attrType
                            + ") : OCTET STRING is not allowed !");
                } else {
                    try {
                        byte[] encoded = value.toASN1Primitive().getEncoded();
                        final CMSSignedData signedData = new CMSSignedData(encoded);
                        final TimeStampToken token = new TimeStampToken(signedData);
                        final TimestampToken timestampToken = new TimestampToken(token, timestampType,
                                certPool);

                        timestampToken.setArchiveTimestampType(archiveTimestampType);
                        timestampTokenList.add(timestampToken);
                    } catch (Exception e) {
                        throw new DSSException(e);
                    }//from   ww w  .  ja  va  2s .c o m
                }
            }
        }
    }
    return timestampTokenList;
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken//from  www  .ja  v a2  s  . co  m
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {
    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

From source file:eu.europa.esig.dss.cades.validation.CMSDocumentValidator.java

License:Open Source License

/**
 * The default constructor for {@code CMSDocumentValidator}.
 *
 * @param document/*from   ww  w . ja  v  a2  s.  c o  m*/
 *            document to validate (with the signature(s))
 * @throws DSSException
 */
public CMSDocumentValidator(final DSSDocument document) throws DSSException {

    this();
    this.document = document;
    InputStream inputStream = null;
    try {

        inputStream = document.openStream();
        if (DSSUtils.available(inputStream) > 0) {
            this.cmsSignedData = new CMSSignedData(inputStream);
        }
    } catch (CMSException e) {
        throw new DSSException("Not a valid CAdES file", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxDocTimestampInfo.java

License:Open Source License

/**
 * @param validationCertPool//w w  w  .ja  v a 2  s  .c o m
 * @param dssDictionary
 *            the DSS dictionary
 * @param cms
 *            the CMS (CAdES) bytes
 * @param isArchiveTimestamp
 * @param inputStream
 *            the stream of the whole signed document
 * @throws DSSException
 */
PdfBoxDocTimestampInfo(CertificatePool validationCertPool, PDSignature signature, PdfDssDict dssDictionary,
        byte[] cms, byte[] signedContent, boolean isArchiveTimestamp) throws DSSException {
    super(signature, dssDictionary, cms, signedContent);
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(cms));
        TimestampType timestampType = TimestampType.SIGNATURE_TIMESTAMP;
        if (isArchiveTimestamp) {
            timestampType = TimestampType.ARCHIVE_TIMESTAMP;
        }
        timestampToken = new TimestampToken(timeStampToken, timestampType, validationCertPool);
        logger.debug("Created PdfBoxDocTimestampInfo {} : {}", timestampType, uniqueId());
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java

License:Open Source License

/**
 * This method generates a bouncycastle {@code TimeStampToken} based on base 64 encoded {@code String}.
 *
 * @param base64EncodedTimestamp/*from www . jav  a 2  s.c om*/
 * @return bouncycastle {@code TimeStampToken}
 * @throws DSSException
 */
private TimeStampToken createTimeStampToken(final String base64EncodedTimestamp) throws DSSException {
    try {
        final byte[] tokenBytes = Base64.decodeBase64(base64EncodedTimestamp);
        final CMSSignedData signedData = new CMSSignedData(tokenBytes);
        return new TimeStampToken(signedData);
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:id.govca.detachedsignature.DetachedSignature.java

/**
 * @param args the command line arguments
 *//*from w  w  w .  j  a va2  s . co m*/
public static void main(String[] args) {
    // TODO code application logic here
    //        String path_p12 = "D:\\Tugas PTIK\\Certificate Authority\\E-voting\\mempawah\\iqbal_196909191994031004.p12";
    String path_p12 = "D:\\Tugas PTIK\\Certificate Authority\\E-voting\\1234567890987654.p12";
    String instance = "PKCS12";
    String passphrase = "rahasiaya";

    String img_input = "D:\\Tugas PTIK\\Certificate Authority\\SIMONEV\\Input\\IMG-20161004-WA0012.jpg";
    String outfile = "CMS_example.DER";

    // Verify against root certificate
    String root_cert_path = "D:\\Tugas PTIK\\Certificate Authority\\E-voting\\Real_Root_CA.cer";

    try {
        PrivateKey_CertChain pkcc = new PrivateKey_CertChain(path_p12, passphrase, instance);

        byte[] img_byte_rep = FileHelper.BitmapToByteArray(img_input);

        System.out.println("***SIGNING***");
        MessageDigest digest01 = MessageDigest.getInstance("SHA-256");
        byte[] input_rep = img_byte_rep;
        byte[] myhash = digest01.digest(input_rep);
        String hash_str_rep = Hex.toHexString(myhash);
        System.out.format("%-32s%s\n", "Digest of Content", hash_str_rep);

        CMSController cms_control = new CMSController();
        cms_control.setRoot_cert_path(root_cert_path);
        CMSSignedData my_cms = cms_control.CMSGenerator(input_rep, pkcc);

        byte[] cms_byte_rep = FileHelper.CMStoDER(my_cms);
        FileHelper.binaryFileWriter(outfile, cms_byte_rep);

        System.out.println("***VERIFYING***");

        byte[] cms_from_file = FileHelper.binaryFileReader(outfile);
        CMSSignedData cms_obj = new CMSSignedData(cms_from_file);
        boolean b = cms_control.VerifyCMS(cms_obj, hash_str_rep);

        if (b) {
            System.out.println("---SIGNATURE VERIFIED---");

            System.out.println("===Fields of DN String===");
            HashMap<String, String> hm_fields_principal = cms_control.getDN_fields();
            for (String key : hm_fields_principal.keySet()) {
                String value = hm_fields_principal.get(key);
                System.out.println("Key = " + key + ", Value = " + value);
            }
            System.out.println("=========================");
        } else {
            System.out.println("---SIGNATURE VERIFICATION FAILED---");
        }

    } catch (KeyStoreException | UnrecoverableKeyException | UnsupportedEncodingException ex) {
        Logger.getLogger(DetachedSignature.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | NoSuchAlgorithmException ex) {
        Logger.getLogger(DetachedSignature.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CMSException | CertificateException | OperatorCreationException | UnmatchedSignatureException
            | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException
            | StringFormatException | ParseException ex) {
        Logger.getLogger(DetachedSignature.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(DetachedSignature.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:id.govca.detachedsignature.ui.SignatureVerifier.java

private void btn_VerifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_VerifyActionPerformed
    // TODO add your handling code here:
    txtArea_Log.setText("");

    // Verify against root certificate
    String root_cert_path = "D:\\Tugas PTIK\\Certificate Authority\\E-voting\\RootCA1.cer";

    // If the PKCS7 File was generated from Android phone
    File file = new File(txt_ImageFile.getText());
    byte[] fileData = new byte[(int) file.length()];
    DataInputStream dis = null;//from  ww  w.j  a  v a  2 s. c  o m
    try {
        dis = new DataInputStream(new FileInputStream(file));

        dis.readFully(fileData);
        dis.close();

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    // If the PKCS7 File was generated from Android desktop
    //byte[] fileData = FileHelper.binaryFileReader(txt_ImageFile.getText());

    System.out.println("***VERIFYING***");
    MessageDigest digest01 = null;
    try {
        digest01 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] input_rep = fileData;
    byte[] myhash = digest01.digest(input_rep);
    String hash_str_rep = Hex.toHexString(myhash);
    System.out.format("%-32s%s\n", "Digest of Content", hash_str_rep);

    CMSController cms_control = new CMSController();
    cms_control.setRoot_cert_path(root_cert_path);

    byte[] cms_from_file = null;
    try {
        cms_from_file = FileHelper.binaryFileReader(txt_CMSFile.getText());
    } catch (IOException ex) {
        Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
    }
    CMSSignedData cms_obj;
    try {
        cms_obj = new CMSSignedData(cms_from_file);

        boolean b = cms_control.VerifyCMS(cms_obj, hash_str_rep);

        if (b) {
            txt_VerifyStatus.setText("SIGNATURE VERIFIED");
            txt_VerifyStatus.setBackground(Color.GREEN);
            System.out.println("---SIGNATURE VERIFIED---");
        }
    } catch (CMSException | IOException | OperatorCreationException | UnmatchedSignatureException
            | StringFormatException | ParseException | GeneralSecurityException ex) {
        Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
        txt_VerifyStatus.setText("SIGNATURE VERIFICATION FAILED");
        txt_VerifyStatus.setBackground(Color.RED);
        System.out.println("---SIGNATURE VERIFICATION FAILED---");
    }

}

From source file:io.aos.crypto.spl09.EncapsulatedSignedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    gen.addSigner(key, (X509Certificate) chain[0], CMSSignedDataGenerator.DIGEST_SHA224);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSSignedData signed = gen.generate(data, true, "BC");

    // recreate// ww  w .  j  a va 2 s.c  om
    signed = new CMSSignedData(signed.getEncoded());

    // verification step
    X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

    if (isValid(signed, rootCert)) {
        System.out.println("signed-data verification succeeded");
    } else {
        System.out.println("signed-data verification failed");
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.splitting.index.lucene.P7mHandler.java

License:Open Source License

public static byte[] sbusta(byte[] p7m_bytes) {
    byte[] byte_out = null;
    CMSSignedData cms = null;//from   www. j a  va  2s.  com
    ByteArrayOutputStream out = null;
    try {
        cms = new CMSSignedData(p7m_bytes);
        CMSProcessable cmsp = cms.getSignedContent();
        if (cmsp != null) {
            out = new ByteArrayOutputStream();
            cmsp.write(out);
            byte_out = out.toByteArray();
            out.close();
        }
    } catch (Exception e) {
        byte_out = null;
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }
    return byte_out;
}