Example usage for org.bouncycastle.asn1.cms ContentInfo getContentType

List of usage examples for org.bouncycastle.asn1.cms ContentInfo getContentType

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms ContentInfo getContentType.

Prototype

public ASN1ObjectIdentifier getContentType() 

Source Link

Usage

From source file:com.guardtime.asn1.Asn1Util.java

License:Apache License

/**
 * Extends the given content info with data from the given certification
 * token.//from w  ww .j  a va 2 s.co m
 *
 * @param contentInfo
 *            the original timestamp encoded in a CMS {@code ContentInfo}
 *            structure.
 * @param certToken
 *            the {@code CertToken} from the GuardTime online verification
 *            service.
 * @return updated (extended) timestamp encoded in a new CMS
 *         {@code ContentInfo} structure.
 */
static org.bouncycastle.asn1.cms.ContentInfo extend(org.bouncycastle.asn1.cms.ContentInfo contentInfo,
        Asn1CertToken certToken) throws Asn1FormatException {
    ASN1EncodableVector v;

    // Extract signed data
    ASN1Encodable asn1SignedData = contentInfo.getContent();
    org.bouncycastle.asn1.cms.SignedData content = org.bouncycastle.asn1.cms.SignedData
            .getInstance(asn1SignedData);

    // Extract signer info
    ASN1Encodable asn1SignerInfo = content.getSignerInfos().getObjectAt(0);
    org.bouncycastle.asn1.cms.SignerInfo signerInfo = org.bouncycastle.asn1.cms.SignerInfo
            .getInstance(asn1SignerInfo);

    // Extract time signature
    ASN1Primitive asn1TimeSignature = null;
    try {
        asn1TimeSignature = ASN1Primitive.fromByteArray(signerInfo.getEncryptedDigest().getOctets());
    } catch (IOException e) {
        throw new Asn1FormatException("time signature has invalid format");
    }
    Asn1TimeSignature timeSignature = Asn1TimeSignature.getInstance(asn1TimeSignature);

    // Extend TimeSignature
    v = new ASN1EncodableVector();
    v.add(timeSignature.getLocation());
    v.add(certToken.getHistory());
    v.add(certToken.getPublishedData());
    // Skip PK signature <- updated
    v.add(new DERTaggedObject(false, 1, certToken.getPubReference()));
    timeSignature = Asn1TimeSignature.getInstance(new DERSequence(v));

    // Extend SignerInfo
    v = new ASN1EncodableVector();
    v.add(signerInfo.getVersion());
    v.add(signerInfo.getSID());
    v.add(signerInfo.getDigestAlgorithm());

    ASN1Set signedAttrs = signerInfo.getAuthenticatedAttributes();
    if (signedAttrs != null) {
        v.add(new DERTaggedObject(false, 0, signedAttrs));
    }

    v.add(signerInfo.getDigestEncryptionAlgorithm());
    try {
        v.add(new DEROctetString(timeSignature)); // <- updated
    } catch (IOException e) {
        throw new Asn1FormatException(e);
    }

    ASN1Set unsignedAttrs = signerInfo.getUnauthenticatedAttributes();
    if (unsignedAttrs != null) {
        v.add(new DERTaggedObject(false, 1, unsignedAttrs));
    }

    signerInfo = org.bouncycastle.asn1.cms.SignerInfo.getInstance(new DERSequence(v));

    // Extend SignedData
    v = new ASN1EncodableVector();
    v.add(content.getVersion());
    v.add(content.getDigestAlgorithms());
    v.add(content.getEncapContentInfo());
    // Skipping certificates <- updated
    // Skipping CRLs <- updated
    v.add(new DERSet(signerInfo)); // <- updated
    content = org.bouncycastle.asn1.cms.SignedData.getInstance(new DERSequence(v));

    // Extend ContentInfo
    v = new ASN1EncodableVector();
    v.add(contentInfo.getContentType());
    v.add(new DERTaggedObject(true, 0, content)); // <- updated
    contentInfo = org.bouncycastle.asn1.cms.ContentInfo.getInstance(new DERSequence(v));

    return contentInfo;
}

From source file:com.guardtime.asn1.SignedData.java

License:Apache License

/**
 * Class constructor./*from   w  ww. j a v a2s  .co m*/
 *
 * @param obj ASN.1 representation of signed data.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
SignedData(ASN1Encodable obj) throws Asn1FormatException {
    try {
        signedData = org.bouncycastle.asn1.cms.SignedData.getInstance(obj);

        // Extract and check version
        //
        // RFC 2630/3161 require version to be 0..4
        // GuardTime requires version to be exactly 3
        BigInteger ver = signedData.getVersion().getValue();
        if (!ver.equals(BigInteger.valueOf(VERSION))) {
            throw new Asn1FormatException("invalid signed data version: " + ver);
        }
        version = ver.intValue();

        // Extract and check digest algorithm list
        //
        // Digest algorithm list can contain duplicate entries as
        // RFC 2630 does not directly deny that
        //
        // RFC 2630 allows digest algorithm list to be empty
        digestAlgorithms = new ArrayList();
        Enumeration e = signedData.getDigestAlgorithms().getObjects();
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            String algOid = AlgorithmIdentifier.getInstance(o).getAlgorithm().getId();
            Asn1Util.checkDigestAlgorithm(algOid);
            digestAlgorithms.add(algOid);
        }

        // Extract and check encapsulated content info
        ContentInfo eContentInfo = signedData.getEncapContentInfo();
        eContentType = eContentInfo.getContentType().toString();
        // RFC3161 requires type to be id-ct-TSTInfo
        if (!eContentType.equals(E_CONTENT_TYPE)) {
            throw new Asn1FormatException("invalid encapsulated content type: " + eContentType);
        }
        DEROctetString eContentData = (DEROctetString) eContentInfo.getContent();
        eContent = TstInfo.getInstance(eContentData.getOctetStream());

        // Extract certificates (optional field)
        ASN1Set certificates = signedData.getCertificates();
        if (certificates != null && certificates.size() > 0) {
            byte[] certBytes = certificates.getObjectAt(0).toASN1Primitive().getEncoded(ASN1Encoding.DER);
            InputStream in = new ByteArrayInputStream(certBytes);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            certificate = (X509Certificate) cf.generateCertificate(in);
        }

        // Extract CRLs (GuardTime is not currently using CRLs field)
        ASN1Set rawCrls = signedData.getCRLs();
        crls = ((rawCrls == null) ? null : rawCrls.getEncoded(ASN1Encoding.DER));

        // Extract and check signer info
        ASN1Set signerInfos = signedData.getSignerInfos();
        // RFC 3161 requires signer info list to contain exactly one entry
        if (signerInfos.size() != 1) {
            throw new Asn1FormatException("wrong number of signer infos found: " + signerInfos.size());
        }
        signerInfo = new SignerInfo(signerInfos.getObjectAt(0).toASN1Primitive());
        // Make sure digest algorithm is contained in digest algorithm list
        // TODO: check disabled as this problem is not critical.
        //String digestAlgorithmOid = signerInfo.getDigestAlgorithm();
        //if (!digestAlgorithms.contains(digestAlgorithmOid)) {
        //   throw new Asn1FormatException("digest algorithm not found in list: " + digestAlgorithmOid);
        //}
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        // Also catches IllegalArgumentException, NullPointerException, etc.
        throw new Asn1FormatException("signed data has invalid format", e);
    }
}

From source file:de.tsenger.animamea.Operator.java

License:Open Source License

private static SecurityInfos decodeEFCardSecurity(byte[] data) throws IOException, CertificateException,
        NoSuchProviderException, CMSException, OperatorCreationException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(data);
    ContentInfo contentInfo = ContentInfo.getInstance(asnSeq);
    DERSequence derSeq = (DERSequence) contentInfo.getContent();

    System.out.println("ContentType: " + contentInfo.getContentType().toString());
    SignedData cardSecurity = SignedData.getInstance(derSeq);

    //Get SecurityInfos
    ContentInfo encapContentInfo = cardSecurity.getEncapContentInfo();
    DEROctetString octString = (DEROctetString) encapContentInfo.getContent();
    SecurityInfos si = new SecurityInfos();
    si.decode(octString.getOctets());//w w w .j  a va  2 s . com

    return si;
}

From source file:de.tsenger.sandbox.CardSecurityParser.java

License:Open Source License

/**
 * @param args//from   w w w . ja v a2  s . com
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    byte[] efcsBytes = readBinaryFile("/home/tsenger/Desktop/EFCardSecurity.bin");
    ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(efcsBytes);
    ContentInfo contentInfo = ContentInfo.getInstance(asnSeq);
    System.out.println(contentInfo.getContentType());
    DERSequence derSeq = (DERSequence) contentInfo.getContent();
    System.out.println(HexString.bufferToHex(derSeq.getEncoded(null)));
    SignedData signedData = SignedData.getInstance(derSeq);
    System.out.println("CMSVersion: " + signedData.getVersion().getValue().intValue());
    ContentInfo contentInfo2 = signedData.getEncapContentInfo();
    System.out.println(contentInfo2.getContentType());
    DEROctetString octString = (DEROctetString) contentInfo2.getContent();
    System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getEncoded(null)));
    System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getOctets()));

    SecurityInfos si = new SecurityInfos();
    si.decode(octString.getOctets());
    System.out.println(si);

    byte[] parameter = si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getPublicKey();
    System.out.println(HexString.bufferToHex(parameter));
    System.out.println("Key Referenz: " + si.getChipAuthenticationPublicKeyInfoList().get(0).getKeyId());
    System.out.println("CA OID: "
            + si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getAlgorithm().getAlgorithm());

}

From source file:es.gob.afirma.applet.CMSInformation.java

License:Open Source License

/**
 * Obtiene la informaci&oacute;n de diferentes tipos de formatos.
 * @param doj Etiqueta ASN.1 de la que se obtienen los datos.
 * @param envelopeType   Tipo de formato:
 * <li>0: EnvelopedData</li>
 * <li>1: AuthenticatedData</li>
 * <li>2: AuthEnvelopedData</li>
 * <li>3: SignedAndEnvelopedData</li>
 * <li>4: SignedData</li>//from w ww  .jav a  2 s . com
 * <li>5: Encrypted</li>
 * @param tipoDetalle   Tipo de datos (literal)
 * @param signBinaryType Tipo de firmado binario (CADES o CMS)
 * @return  Representaci&oacute;n de los datos.
 */
private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle,
        final int signBinaryType) {
    String detalle = ""; //$NON-NLS-1$
    detalle = detalle + tipoDetalle + CR;

    ASN1Set rins = null;
    EncryptedContentInfo encryptedContentInfo = null;
    ASN1Set unprotectedAttrs = null;
    ASN1Integer version = null;
    AlgorithmIdentifier aid = null;
    ContentInfo ci = null;
    ASN1Set authAttrs = null;
    ASN1Set ds = null;
    ASN1Set signerInfosSd = null;

    switch (envelopeType) {
    case TYPE_ENVELOPED_DATA:
        final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject());
        version = enveloped.getVersion();
        rins = enveloped.getRecipientInfos();
        encryptedContentInfo = enveloped.getEncryptedContentInfo();
        unprotectedAttrs = enveloped.getUnprotectedAttrs();
        break;
    case TYPE_AUTHENTICATED_DATA:
        final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject());
        version = authenticated.getVersion();
        rins = authenticated.getRecipientInfos();
        aid = authenticated.getMacAlgorithm();
        ci = authenticated.getEncapsulatedContentInfo();
        authAttrs = authenticated.getAuthAttrs();
        unprotectedAttrs = authenticated.getUnauthAttrs();
        break;
    case TYPE_AUTHENTICATED_ENVELOPED_DATA:
        final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject());
        version = authEnveloped.getVersion();
        rins = authEnveloped.getRecipientInfos();
        encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo();
        authAttrs = authEnveloped.getAuthAttrs();
        unprotectedAttrs = authEnveloped.getUnauthAttrs();
        break;
    case TYPE_SIGNED_ENVELOPED_DATA:
        final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject());
        version = signedEnv.getVersion();
        rins = signedEnv.getRecipientInfos();
        encryptedContentInfo = signedEnv.getEncryptedContentInfo();
        signerInfosSd = signedEnv.getSignerInfos();
        break;
    case TYPE_SIGNED_DATA:
        final SignedData signed = SignedData.getInstance(doj.getObject());
        version = signed.getVersion();
        ds = signed.getDigestAlgorithms();
        ci = signed.getEncapContentInfo();
        signerInfosSd = signed.getSignerInfos();
        break;
    case TYPE_ENCRYPTED_DATA:
        final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject();
        version = ASN1Integer.getInstance(encrypted.getObjectAt(0));
        encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1));
        if (encrypted.size() == 3) {
            unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2);
        }
        break;
    default:
        throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$
    }

    //obtenemos la version
    detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$

    //recipientInfo
    if (rins != null) {
        if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < rins.size(); i++) {
            final KeyTransRecipientInfo kti = KeyTransRecipientInfo
                    .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo());
            detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm();

            //issuer y serial
            final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier
                    .getInstance(kti.getRecipientIdentifier().getId()).getId();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            // el algoritmo de cifrado de los datos
            AOCipherAlgorithm algorithm = null;
            final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values();

            // obtenemos el algoritmo usado para cifrar la pass
            for (final AOCipherAlgorithm algo : algos) {
                if (algo.getOid().equals(diAlg.getAlgorithm().toString())) {
                    algorithm = algo;
                }
            }
            if (algorithm != null) {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$
                        + algorithm.getName() + CR;
            } else {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$
                        + diAlg.getAlgorithm() + CR;
            }
        }
    }

    if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) {
        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) {
        // mac algorithm
        detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$

        //digestAlgorithm
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject());
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) {
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) {
        //algoritmo de firma
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1Set da = (ASN1Set) seq.getObjectAt(2);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) {
        //algoritmo de firma
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$
    }

    //obtenemos lo atributos opcionales
    if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) {
        if (unprotectedAttrs == null) {
            detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$
        } else {
            final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects());
            detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$
            detalle = detalle + atributos;
        }
    } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA)
            && signerInfosSd != null) {
        //obtenemos el(los) firmate(s)
        if (signerInfosSd.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < signerInfosSd.size(); i++) {
            final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));

            detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            // version
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$
            //signerIdentifier
            final SignerIdentifier sident = si.getSID();
            final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId());
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            //digestAlgorithm
            final AlgorithmIdentifier algId = si.getDigestAlgorithm();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$
                    + CR;

            //obtenemos lo atributos obligatorios
            final ASN1Set sa = si.getAuthenticatedAttributes();
            String satributes = ""; //$NON-NLS-1$
            if (sa != null) {
                satributes = getsignedAttributes(sa, signBinaryType);
            }
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$
            detalle = detalle + satributes;
        }
    }
    return detalle;
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBETSITS101733Test.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*from  w ww .  j  av  a 2  s  .  co  m*/

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);
            X509Certificate x509Certificate = certificate.getCertificate();
            x509Certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(x509Certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = "";
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Utils.toBase64(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Utils.toBase64(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        Utils.closeQuietly(asn1sInput);
        Utils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {// ww w  . ja  v  a2 s  .  com

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            X509Certificate certificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);

            certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = StringUtils.EMPTY;
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Base64.encodeBase64String(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        IOUtils.closeQuietly(asn1sInput);
        IOUtils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

License:Open Source License

/**
 * These signatures are invalid because of non ordered signed attributes
 *//*  ww  w  .  j av a2 s  .  c  om*/
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {

    try {/*from w w w.j ava2s. c o  m*/
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        PDDocument document = PDDocument.load(inputStream);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        assertEquals(1, signatures.size());

        for (PDSignature pdSignature : signatures) {
            byte[] contents = pdSignature.getContents(byteArray);
            byte[] signedContent = pdSignature.getSignedContent(byteArray);

            logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

            // IOUtils.write(contents, new FileOutputStream("sig.p7s"));

            ASN1InputStream asn1sInput = new ASN1InputStream(contents);
            ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

            logger.info("SEQ : " + asn1Seq.toString());

            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
            assertEquals(PKCSObjectIdentifiers.signedData, oid);

            SignedData signedData = SignedData
                    .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

            ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
            ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                    .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
            logger.info("DIGEST ALGO : " + digestAlgorithm);

            ContentInfo encapContentInfo = signedData.getEncapContentInfo();
            ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
            logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
            int previousSize = 0;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                ASN1ObjectIdentifier attrTypeOid = attribute.getAttrType();
                attributeOids.add(attrTypeOid);
                int size = attrTypeOid.getEncoded().length + attribute.getEncoded().length;
                assertTrue(size >= previousSize);

                previousSize = size;
            }
            logger.info("List of OID for Auth Attrb : " + attributeOids);

            Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
            assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);
            IOUtils.closeQuietly(asn1sInput);
        }

        IOUtils.closeQuietly(inputStream);
        document.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

License:Open Source License

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//  w w  w . j av a2  s  .c  o m
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}