Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data.

Prototype

ASN1ObjectIdentifier data

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data.

Click Source Link

Document

PKCS#7: 1.2.840.113549.1.7.1

Usage

From source file:it.trento.comune.j4sign.examples.CLITest.java

License:Open Source License

/**
 * Implements a single signature, returning the
 * {@link ExternalSignatureSignerInfoGenerator}that encapsulates all signer
 * informations.//w  w  w. j a va2  s . c o m
 * 
 * 
 * @param msg
 *            the content to sign
 * @param certList
 *            the list which the signer certificate is to be added to.
 * @return the <code>ExternalSignatureSignerInfoGenerator</code> containing
 *         all signer informations.
 */
ExternalSignatureSignerInfoGenerator getSignerInfoGenerator(CMSProcessable msg, String digestAlg,
        String encryptionAlg, boolean digestOnToken, ArrayList certList) {

    // Il SignerInfoGenerator  molto simile alla versione standard
    // SignerInf; la differenza maggiore
    //  la presenza del metodo generateBytesToSign() che permette di
    // esternalizzare la firma.
    // Il nuovo metodo toSignerInfo() (senza parametri) restituisce un
    // signerInfo che usa il digest crittato
    // e certificati precedentemente impostati dall'esterno.
    // Il digest crittato  ora una variabile del generatore,
    // impostabile dall'esterno.

    ExternalSignatureSignerInfoGenerator signerGenerator = new ExternalSignatureSignerInfoGenerator(digestAlg,
            encryptionAlg);

    byte[] certBytes = null;
    byte[] signedBytes = null;
    byte[] bytesToSign = null;
    byte[] dInfoBytes = null;

    try {

        long mechanism = -1L;
        long certHandle = -1L;
        long t = -1L;

        mechanism = algToMechanism(digestOnToken, digestAlg, encryptionAlg);

        if (mechanism != -1L) {
            PKCS11Signer signAgent = new PKCS11Signer(getCryptokiLib(), System.out);

            System.out.println("Finding a token supporting required mechanism and " + "containing a suitable "
                    + "certificate...");

            t = signAgent.findSuitableToken(mechanism);

            // if suitable token found
            if (t != -1L) {
                signAgent.setMechanism(mechanism);
                signAgent.setTokenHandle(t);

                signAgent.openSession();

                certHandle = signAgent.findCertificateWithNonRepudiationCritical();

                if (certHandle >= 0)

                    certBytes = signAgent.getDEREncodedCertificate(certHandle);
                else
                    System.out.println("\nNo suitable  certificate on token!");

                signAgent.closeSession();
                System.out.println("Cert session Closed.");

                // signAgent.libFinalize();
                // System.out.println("Criptoki library finalized.");

                if (certBytes != null) {
                    System.out.println("======== Certificate found =========");

                    // get Certificate
                    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
                            .getInstance("X.509");
                    java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(certBytes);
                    java.security.cert.X509Certificate javaCert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(bais);

                    signerGenerator.setCertificate(javaCert);

                    System.out.println("Calculating bytes to sign ...");

                    bytesToSign = signerGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC");

                    byte[] rawDigest = null;
                    byte[] paddedBytes = null;

                    /*
                     * Let's calculate DigestInfo in any case (even if
                     * digestOnToken is TRUE) , in order to compare with
                     * decryption result
                     */
                    rawDigest = applyDigest(digestAlg, bytesToSign);

                    System.out.println("Raw digest bytes:\n" + formatAsString(rawDigest, " ", WRAP_AFTER));

                    System.out.println("Encapsulating in a DigestInfo...");

                    dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest);

                    System.out.println("DigestInfo bytes:\n" + formatAsString(dInfoBytes, " ", WRAP_AFTER));

                    if (!digestOnToken) {

                        System.out.println("Adding Pkcs1 padding...");

                        paddedBytes = applyPkcs1Padding(128, dInfoBytes);

                        System.out.println(
                                "Padded DigestInfo bytes:\n" + formatAsString(paddedBytes, " ", WRAP_AFTER));

                    }

                    // certBytes = null;
                    System.out.println("============ Encrypting with pkcs11 token ============");
                    /*
                     * mechanism = -1L; if
                     * (CMSSignedDataGenerator.ENCRYPTION_RSA
                     * .equals(encryptionAlg)) if (digestOnToken) { if
                     * (CMSSignedDataGenerator.DIGEST_MD5.equals(digestAlg))
                     * mechanism = PKCS11Constants.CKM_MD5_RSA_PKCS; else if
                     * (CMSSignedDataGenerator.DIGEST_SHA1
                     * .equals(digestAlg)) mechanism =
                     * PKCS11Constants.CKM_SHA1_RSA_PKCS; } else mechanism =
                     * PKCS11Constants.CKM_RSA_PKCS;
                     * 
                     * if (mechanism != -1L) { PKCS11Signer signAgent = new
                     * PKCS11Signer(getCryptokiLib(), System.out);
                     */

                    /*
                     * System.out .println(
                     * "Finding a token supporting required mechanism and "
                     * + "containing a suitable" + "certificate...");
                     * 
                     * if (t != -1L) t =
                     * signAgent.findSuitableToken(mechanism);
                     */
                    // if suitable token found
                    // if (t != -1L) {
                    signAgent.setMechanism(mechanism);
                    signAgent.setTokenHandle(t);

                    signAgent.openSession(readPassword());

                    /*
                     * sign using the first key found on token
                     * 
                     * long privateKeyHandle = signAgent.findSignatureKey();
                     * 
                     * if(privateKeyHandle > 0){ signedBytes =
                     * signAgent.signDataSinglePart(privateKeyHandle,
                     * digest); long certHandle =
                     * signAgent.findCertificateFromSignatureKeyHandle
                     * (privateKeyHandle); certBytes =
                     * signAgent.getDEREncodedCertificate(certHandle);
                     * 
                     * }else System.out.println("\nNo private key found on
                     * token!");
                     */

                    // trying a legal value signature finding suitable
                    // objects
                    // on
                    // token
                    if (certHandle == -1L)
                        certHandle = signAgent.findCertificateWithNonRepudiationCritical();

                    long privateKeyHandle = signAgent.findSignatureKeyFromCertificateHandle(certHandle);

                    if (privateKeyHandle >= 0) {
                        if (!digestOnToken) {
                            // Here we could provide padded bytes or
                            // DigestInfo
                            // bytes;
                            // but with padded bytes and Infocamere CNS
                            // signDataSinglePart fails!
                            // (CKR_FUNCTION_FAILED).
                            signedBytes = signAgent.signDataSinglePart(privateKeyHandle, dInfoBytes);
                        } else
                            /*
                             * signedBytes = signAgent.signDataMultiplePart(
                             * privateKeyHandle, new ByteArrayInputStream(
                             * bytesToSign));
                             */
                            signedBytes = signAgent.signDataSinglePart(privateKeyHandle, bytesToSign);

                        // certBytes = signAgent
                        // .getDEREncodedCertificate(certHandle);
                    } else
                        System.out.println("\nNo suitable private key and certificate on token!");

                    signAgent.closeSession();
                    System.out.println("Sign session Closed.");

                    signAgent.libFinalize();
                    System.out.println("Criptoki library finalized.");

                } // certBytes not null
            } // suitable token found
        } else
            System.out.println("Mechanism currently not supported");

        if ((certBytes != null) && (signedBytes != null)) {
            System.out.println("======== Encryption completed =========");
            System.out.println("\nBytes:\n" + formatAsString(bytesToSign, " ", WRAP_AFTER));

            if (dInfoBytes != null)
                System.out.println("DigestInfo bytes:\n" + formatAsString(dInfoBytes, " ", WRAP_AFTER));

            System.out.println("Encryption result:\n" + formatAsString(signedBytes, " ", WRAP_AFTER) + "\n");

            // get Certificate
            java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
                    .getInstance("X.509");
            java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(certBytes);
            java.security.cert.X509Certificate javaCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(bais);

            // Decription
            PublicKey pubKey = javaCert.getPublicKey();

            try {
                System.out.println("Decrypting...");

                Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");

                c.init(Cipher.DECRYPT_MODE, pubKey);

                byte[] decBytes = c.doFinal(signedBytes);

                System.out.println("Decrypted bytes (should match DigestInfo bytes):\n"
                        + formatAsString(decBytes, " ", WRAP_AFTER));

            } catch (NoSuchAlgorithmException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchPaddingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InvalidKeyException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (signerGenerator.getCertificate() != null)
                signerGenerator.setCertificate(javaCert);
            signerGenerator.setSignedBytes(signedBytes);

            certList.add(javaCert);

        } else
            signerGenerator = null;
    } catch (Exception e) {
        System.out.println(e);
    } catch (Throwable e) {
        System.out.println(e);
    }

    return signerGenerator;
}

From source file:it.trento.comune.j4sign.examples.CMSServlet.java

License:Open Source License

/**
 * Uses the provided {@link ExternalSignatureSignerInfoGenerator} for
 * calculating the authenticated attributes bytes to be digested-encrypted
 * by the signer. Note that the attributes include a timestamp, so the
 * result is time-dependent!/*  w w  w  .  ja va2 s.c  o m*/
 * 
 * @param signerGenerator
 *            the <code>ExternalSignatureSignerInfoGenerator</code> object
 *            that does the job.
 * @return the bytes to be signed.
 */
private byte[] getAuthenticatedAttributesBytes(ExternalSignatureSignerInfoGenerator signerGenerator) {

    System.out.println("Building AuthenticatedAttributes.");
    byte[] bytesToSign = null;
    try {
        CMSProcessable msg = new CMSProcessableByteArray(DATA.getBytes());
        bytesToSign = signerGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC");
    } catch (Exception e) {
        System.out.println(e);
    }
    return bytesToSign;
}

From source file:it.trento.comune.j4sign.examples.GUITest.java

License:Open Source License

/**
 * Prepares a signing procedure./*  w w  w .j  a v a 2s.  c o m*/
 * 
 * @param digestAlg
 * @param encryptionAlg
 * @param digestOnToken
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CMSException
 * @throws CertificateException
 */
private void openSignature(String digestAlg, String encryptionAlg, boolean digestOnToken)
        throws InvalidKeyException, SignatureException, NoSuchProviderException, NoSuchAlgorithmException,
        IOException, CMSException, CertificateException {

    this.msg = new CMSProcessableByteArray(dataArea.getText().getBytes("UTF8"));

    this.cmsGenerator = new ExternalSignatureCMSSignedDataGenerator();

    this.signersCertList = new ArrayList();

    log.println("Certificate bytes:\n" + formatAsHexString(getCertificate()));

    java.security.cert.X509Certificate javaCert = getJavaCertificate();

    this.signerInfoGenerator = new ExternalSignatureSignerInfoGenerator(digestAlg, encryptionAlg);
    this.signerInfoGenerator.setCertificate(javaCert);

    this.signersCertList.add(javaCert);

    this.bytesToSign = this.signerInfoGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC");

    if (!digestOnToken) {
        log.println("\nCalculating digest ...\n");

        MessageDigest md = MessageDigest.getInstance(digestAlg);
        md.update(bytesToSign);
        byte[] rawDigest = md.digest();

        log.println("Encapsulating in a DigestInfo...");

        byte[] dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest);

        log.println("Adding Pkcs1 padding...");

        byte[] paddedBytes = applyPkcs1Padding(128, dInfoBytes);

        log.println("Encapsulated digest:\n" + formatAsHexString(dInfoBytes));
        log.println("Done.");
        setEncodedDigest(encodeFromBytes(dInfoBytes));
    }

}

From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java

License:Open Source License

/**
 * Prepares a signing procedure.//ww w  .j av a2  s . c o m
 * 
 * @param digestAlg
 *            String
 * @param encryptionAlg
 *            String
 * @param digestOnToken
 *            boolean
 * @throws InvalidKeyException
 * @throws CertificateEncodingException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CMSException
 */
private void openSignature(String digestAlg, String encryptionAlg, boolean digestOnToken)
        throws InvalidKeyException, CertificateEncodingException, SignatureException, NoSuchProviderException,
        NoSuchAlgorithmException, IOException, CMSException {

    File inputFile = new File(fileDaAprire);

    if (fileDaAprire.substring(fileDaAprire.lastIndexOf('.') + 1, fileDaAprire.length()).toLowerCase()
            .equalsIgnoreCase("p7m")) {
        log.println("Resigning in progress...");
        // do resigning things
        resign = true;
        byte[] bytesFromFile = getBytesFromFile(inputFile);
        byte[] certData;
        try {
            certData = Base64.decode(bytesFromFile);
        } catch (Exception eb64) {
            certData = bytesFromFile;
        }
        CMSSignedData actualFile = new CMSSignedData(certData);
        this.msg = new CMSProcessableByteArray((byte[]) actualFile.getSignedContent().getContent());
    } else {
        this.msg = new CMSProcessableByteArray(getBytesFromFile(inputFile));
    }

    /**
     * Code notes:
     * 
     * On CLITest.java there is a method called getSignerInfoGenerator that gives some infos about the generator that then is added on the
     * 
     * ExternalSignatureCMSSignedDataGenerator() with cmsGenerator.addSignerInf(sig)
     * 
     */

    this.cmsGenerator = new ExternalSignatureCMSSignedDataGenerator();

    this.signersCertList = new ArrayList();

    log.println("\nCalculating digest ...\n");

    this.signerInfoGenerator = new ExternalSignatureSignerInfoGenerator(digestAlg, encryptionAlg);
    /* Cades Impl. */
    this.signerInfoGenerator.setCertificate(certforcades);
    /* End Cades Impl. */
    byte[] rawDigest = null;
    byte[] dInfoBytes = null;
    byte[] paddedBytes = null;

    /**
     * notes for multiple signing:
     * this.msg should be a CMSProcessableByteArray of the signedContent.
     * bytesToSign should be extracted with (byte[]) CMSSignedData.getSignedContent().getContent()
     */

    byte[] bytesToSign = this.signerInfoGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC");

    /*
     * Let's calculate DigestInfo in any case (even if digestOnToken is
     * TRUE) , in order to compare with decryption result
     */
    rawDigest = applyDigest(digestAlg, bytesToSign);

    log.println("Raw digest bytes:\n" + formatAsHexString(rawDigest));

    log.println("Encapsulating in a DigestInfo...");

    dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest);

    log.println("DigestInfo bytes:\n" + formatAsHexString(dInfoBytes));

    if (!digestOnToken) {
        // MessageDigest md = MessageDigest.getInstance(digestAlg);
        // md.update(bytesToSign);
        // byte[] digest = md.digest();
        //
        // log.println("digestAlg digest:\n" + formatAsHexString(digest));
        // log.println("Done.");
        setEncodedDigest(encodeFromBytes(dInfoBytes));
    }

}

From source file:mitm.common.security.asn1.ASN1Encoder.java

License:Open Source License

/**
 * Taken from org.bouncycastle.jce.provider.PKIXCertPath.
 * //  w  ww . j av  a 2s  .  c  o m
 * See ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-7.asc for info on PKCS#7 encoding
 */
public static byte[] encodePKCS7(ASN1EncodableVector certificatesVector, ASN1EncodableVector crlsVector)
        throws IOException {
    ContentInfo dataContentInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);

    ASN1Integer version = new ASN1Integer(1);
    ASN1Set digestAlgorithms = new DERSet();
    ASN1Set signerInfos = new DERSet();
    ASN1Set crls = null;
    ASN1Set certificates = null;

    if (certificatesVector != null) {
        /*
         * pre-sort the asn1Certificates vector with a much faster method then DERSet uses
         */
        ASN1EncodableVector sortedASN1Certificates = DERUtils.sortASN1EncodableVector(certificatesVector);
        certificates = new DERSet(sortedASN1Certificates);
    }

    if (crlsVector != null) {
        /*
         * pre-sort the asn1Certificates vector with a much faster method then DERSet uses
         */
        ASN1EncodableVector sortedASN1CRLs = DERUtils.sortASN1EncodableVector(crlsVector);
        crls = new DERSet(sortedASN1CRLs);
    }

    SignedData signedData = new SignedData(version, digestAlgorithms, dataContentInfo, certificates, crls,
            signerInfos);

    ContentInfo signedContentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, signedData);

    return DERUtils.toByteArray(signedContentInfo);
}

From source file:net.jsign.asn1.authenticode.AuthenticodeTimeStampRequest.java

License:Apache License

public AuthenticodeTimeStampRequest(byte[] digest) {
    contenInfo = new ContentInfo(PKCSObjectIdentifiers.data, new BEROctetString(digest));
}