Example usage for org.bouncycastle.asn1.cms IssuerAndSerialNumber getName

List of usage examples for org.bouncycastle.asn1.cms IssuerAndSerialNumber getName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms IssuerAndSerialNumber getName.

Prototype

public X500Name getName() 

Source Link

Usage

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

License:Apache License

/**
 * Class constructor./*www  . ja  v a  2s.c om*/
 *
 * @param obj ASN.1 representation of signer info.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
SignerInfo(ASN1Encodable obj) throws Asn1FormatException {
    try {
        signerInfo = org.bouncycastle.asn1.cms.SignerInfo.getInstance(obj);

        // Extract and check version
        //
        // Since we use the IssuerAndSerialNumber option to identify the
        // signer's certificate, the version has to be 1.
        BigInteger ver = signerInfo.getVersion().getValue();
        if (!ver.equals(BigInteger.valueOf(VERSION))) {
            throw new Asn1FormatException("invalid signer info version: " + ver);
        }
        version = ver.intValue();

        // Extract the signer's certificate identification
        IssuerAndSerialNumber sid = IssuerAndSerialNumber.getInstance(signerInfo.getSID().toASN1Primitive());
        issuerName = sid.getName().toString();
        serialNumber = sid.getSerialNumber().getValue();

        // Extract the digest algorithm ID
        digestAlgorithm = signerInfo.getDigestAlgorithm().getAlgorithm().getId();
        Asn1Util.checkDigestAlgorithm(digestAlgorithm);

        // Extract and check the signed attributes
        //
        // The content-type and message-digest attributes must be present.
        ASN1Set sigAttrs = signerInfo.getAuthenticatedAttributes();
        if (sigAttrs == null) {
            throw new Asn1FormatException("no signed attributes");
        }
        ASN1Encodable ct = Asn1Util.getAttributeValue(sigAttrs, CONTENT_TYPE_ID);
        if (ct == null || !ct.equals(new ASN1ObjectIdentifier(CONTENT_TYPE))) {
            throw new Asn1FormatException("invalid content-type signed attribute value");
        }
        ASN1Encodable md = Asn1Util.getAttributeValue(sigAttrs, MESSAGE_DIGEST_ID);
        if (md == null || !(md instanceof DEROctetString)) {
            throw new Asn1FormatException("invalid message-digest signed attribute");
        }
        messageDigest = ((ASN1OctetString) md).getOctets();
        signedAttrs = sigAttrs.getEncoded(ASN1Encoding.DER);

        // Extract and check the signature algorithm ID
        signatureAlgorithm = signerInfo.getDigestEncryptionAlgorithm().getAlgorithm().getId();
        if (!signatureAlgorithm.equals(SIGNATURE_ALGORITHM)) {
            throw new Asn1FormatException("invalid signature algorithm: " + signatureAlgorithm);
        }

        // Extract the signature
        signature = new TimeSignature(ASN1Primitive.fromByteArray(signerInfo.getEncryptedDigest().getOctets()));

        // Extract the unsigned attributes
        ASN1Set unsigAttrs = signerInfo.getUnauthenticatedAttributes();
        unsignedAttrs = ((unsigAttrs == null) ? null : unsigAttrs.getEncoded(ASN1Encoding.DER));
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        // Also catches IllegalArgumentException, NullPointerException, etc.
        throw new Asn1FormatException("signer info has invalid format", e);
    }
}

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

License:Open Source License

/**
 * Obtiene la informació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>// www .  j  a  v  a  2 s. c o  m
 * <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.pades.InfiniteLoopDSS621Test.java

License:Open Source License

/**
 * These signatures are invalid because of non ordered signed attributes
 *///from  w w  w  . ja  va  2  s  . com
@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  ww .ja v a 2  s . 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.ejbca.core.protocol.scep.ScepRequestMessage.java

License:Open Source License

private void init() throws IOException {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }//from w  ww . jav  a  2 s .  c om
    try {
        CMSSignedData csd = new CMSSignedData(scepmsg);
        SignerInformationStore infoStore = csd.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> signers = infoStore.getSigners();
        Iterator<SignerInformation> iter = signers.iterator();
        if (iter.hasNext()) {
            SignerInformation si = (SignerInformation) iter.next();
            preferredDigestAlg = si.getDigestAlgOID();
            log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP");
        }
    } catch (CMSException e) {
        // ignore, use default digest algo
        log.error("CMSException trying to get preferred digest algorithm: ", e);
    }
    // Parse and verify the integrity of the PKIOperation message PKCS#7
    /* If this would have been done using the newer CMS it would have made me so much happier... */
    ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg));
    ASN1Sequence seq = null;
    try {
        seq = (ASN1Sequence) seqAsn1InputStream.readObject();
    } finally {
        seqAsn1InputStream.close();
    }
    ContentInfo ci = ContentInfo.getInstance(seq);
    String ctoid = ci.getContentType().getId();

    if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) {
        // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned
        // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side
        // Try to find out what kind of message this is
        sd = SignedData.getInstance((ASN1Sequence) ci.getContent());
        // Get self signed cert to identify the senders public key
        ASN1Set certs = sd.getCertificates();
        if (certs.size() > 0) {
            // There should be only one...
            ASN1Encodable dercert = certs.getObjectAt(0);
            if (dercert != null) {
                // Requester's self-signed certificate is requestKeyInfo
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                DEROutputStream dOut = new DEROutputStream(bOut);
                dOut.writeObject(dercert);
                if (bOut.size() > 0) {
                    requestKeyInfo = bOut.toByteArray();
                    //Create Certificate used for debugging
                    try {
                        signercert = CertTools.getCertfromByteArray(requestKeyInfo);
                        if (log.isDebugEnabled()) {
                            log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert)
                                    + ", Serial=" + CertTools.getSerialNumberAsString(signercert)
                                    + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString());
                        }
                    } catch (CertificateException e) {
                        log.error("Error parsing requestKeyInfo : ", e);
                    }

                }
            }
        }

        Enumeration<?> sis = sd.getSignerInfos().getObjects();

        if (sis.hasMoreElements()) {
            SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement());
            Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects();

            while (attr.hasMoreElements()) {
                Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement());
                if (log.isDebugEnabled()) {
                    log.debug("Found attribute: " + a.getAttrType().getId());
                }
                if (a.getAttrType().getId().equals(id_senderNonce)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement());
                    senderNonce = new String(Base64.encode(str.getOctets(), false));
                    if (log.isDebugEnabled()) {
                        log.debug("senderNonce = " + senderNonce);
                    }
                }
                if (a.getAttrType().getId().equals(id_transId)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    transactionId = str.getString();
                    if (log.isDebugEnabled()) {
                        log.debug("transactionId = " + transactionId);
                    }
                }
                if (a.getAttrType().getId().equals(id_messageType)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    messageType = Integer.parseInt(str.getString());
                    if (log.isDebugEnabled()) {
                        log.debug("messagetype = " + messageType);
                    }
                }
            }
        }

        // If this is a PKCSReq
        if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) {
            // Extract the contents, which is an encrypted PKCS10 if messageType == 19
            // , and an encrypted issuer and subject if messageType == 20 (not extracted)
            // and an encrypted IssuerAndSerialNumber if messageType == 22
            ci = sd.getEncapContentInfo();
            ctoid = ci.getContentType().getId();

            if (ctoid.equals(CMSObjectIdentifiers.data.getId())) {
                ASN1OctetString content = (ASN1OctetString) ci.getContent();
                if (log.isDebugEnabled()) {
                    log.debug("envelopedData is " + content.getOctets().length + " bytes.");
                }
                ASN1InputStream seq1Asn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(content.getOctets()));
                ASN1Sequence seq1 = null;
                try {
                    seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject();
                } finally {
                    seq1Asn1InputStream.close();
                }
                envEncData = ContentInfo.getInstance(seq1);
                ctoid = envEncData.getContentType().getId();

                if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) {
                    envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent());
                    ASN1Set recipientInfos = envData.getRecipientInfos();
                    Enumeration<?> e = recipientInfos.getObjects();
                    while (e.hasMoreElements()) {
                        RecipientInfo ri = RecipientInfo.getInstance(e.nextElement());
                        KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo());
                        RecipientIdentifier rid = recipientInfo.getRecipientIdentifier();
                        IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId());
                        issuerDN = iasn.getName().toString();
                        serialNo = iasn.getSerialNumber().getValue();
                        if (log.isDebugEnabled()) {
                            log.debug("IssuerDN: " + issuerDN);
                            log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16));
                        }
                    }
                } else {
                    errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: ";
                    log.error(errorText + ctoid);
                    error = 2;
                }
            } else {
                errorText = "EncapsulatedContentInfo is not of type 'data': ";
                log.error(errorText + ctoid);
                error = 3;
            }
        } else {
            errorText = "This is not a certification request!";
            log.error(errorText);
            error = 4;
        }
    } else {
        errorText = "PKCSReq does not contain 'signedData': ";
        log.error(errorText + ctoid);
        error = 1;
    }

    log.trace("<init");
}

From source file:org.jmrtd.lds.SignedDataUtil.java

License:Open Source License

public static IssuerAndSerialNumber getIssuerAndSerialNumber(SignedData signedData) {
    SignerInfo signerInfo = getSignerInfo(signedData);
    SignerIdentifier signerIdentifier = signerInfo.getSID();
    IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signerIdentifier.getId());
    X500Name issuer = issuerAndSerialNumber.getName();
    BigInteger serialNumber = issuerAndSerialNumber.getSerialNumber().getValue();
    return new IssuerAndSerialNumber(issuer, serialNumber);
}

From source file:org.jmrtd.lds.SODFile.java

License:Open Source License

/**
 * Gets the issuer of the document signing certificate.
 *
 * @return a certificate issuer//from   www  . j  ava 2  s. co  m
 */
public X500Principal getIssuerX500Principal() {
    try {
        IssuerAndSerialNumber issuerAndSerialNumber = SignedDataUtil.getIssuerAndSerialNumber(signedData);
        X500Name name = issuerAndSerialNumber.getName();
        X500Principal x500Principal = new X500Principal(name.getEncoded(ASN1Encoding.DER));
        return x500Principal;
    } catch (IOException ioe) {
        LOGGER.severe("Could not get issuer: " + ioe.getMessage());
        return null;
    }
}

From source file:org.jscep.pkcs7.SignedDataUtil.java

License:Open Source License

private static boolean areEqual(IssuerAndSerialNumber one, IssuerAndSerialNumber two) {
    if (one.getSerialNumber().equals(two.getSerialNumber())) {
        return one.getName().equals(two.getName());
    } else {//www. j a v a2  s  .c o  m
        return false;
    }
}

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w  w.  j  av  a2s  . c o  m
 */
@SuppressWarnings("unchecked")
@Override
public final void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    byte[] body = getMessageBytes(req);

    final Operation op;
    try {
        op = getOperation(req);
        if (op == null) {
            // The operation parameter must be set.
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing \"operation\" parameter.");
            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid \"operation\" parameter.");
        return;
    }

    LOGGER.debug("Incoming Operation: " + op);

    final String reqMethod = req.getMethod();

    if (op == Operation.PKI_OPERATION) {
        if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) {
            // PKIOperation must be sent using GET or POST

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET + ", " + POST);

            return;
        }
    } else {
        if (!reqMethod.equals(GET)) {
            // Operations other than PKIOperation must be sent using GET

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET);

            return;
        }
    }

    LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op);

    if (op == Operation.GET_CA_CAPS) {
        try {
            LOGGER.debug("Invoking doGetCaCaps");
            doGetCaCaps(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetCaCert");
            doGetCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_NEXT_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetNextCaCert");
            doGetNextCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.PKI_OPERATION) {
        // PKIOperation

        res.setHeader("Content-Type", "application/x-pki-message");

        CMSSignedData sd;
        try {
            sd = new CMSSignedData(body);
        } catch (CMSException e) {
            throw new ServletException(e);
        }

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory;
        try {
            factory = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new ServletException(e);
        }
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert;
        try {
            reqCert = (X509Certificate) factory.generateCertificate(bais);
        } catch (CertificateException e) {
            throw new ServletException(e);
        }

        PkiMessage<?> msg;
        try {
            PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey());
            PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
            msg = decoder.decode(sd);
        } catch (MessageDecodingException e) {
            LOGGER.error("Error decoding request", e);
            throw new ServletException(e);
        }

        LOGGER.debug("Processing message {}", msg);

        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();

            try {
                List<X509Certificate> issued = doGetCert(principal, serial);
                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                LOGGER.debug("Invoking doGetCrl");
                CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (OperationFailureException e) {
                LOGGER.error("Error executing GetCRL request", e);
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                LOGGER.error("Error executing GetCRL request", e);
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                LOGGER.debug("Invoking doEnrol");
                List<X509Certificate> issued = doEnrol(certReq, reqCert, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            throw new ServletException("Unknown Message for Operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(),
                getSignerCertificateChain(), envEncoder);
        CMSSignedData signedData;
        try {
            signedData = encoder.encode(certRep);
        } catch (MessageEncodingException e) {
            LOGGER.error("Error decoding response", e);
            throw new ServletException(e);
        }

        res.getOutputStream().write(signedData.getEncoded());
        res.getOutputStream().close();
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
    }
}

From source file:org.signserver.module.mrtdsodsigner.jmrtd.SODFile.java

License:Open Source License

public X500Principal getIssuerX500Principal() throws IOException {
    IssuerAndSerialNumber issuerAndSerialNumber = getIssuerAndSerialNumber();
    X500Name name = issuerAndSerialNumber.getName();

    return new X500Principal(name.getEncoded(ASN1Encoding.DER));
}