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

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

Introduction

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

Prototype

public ASN1Encodable getContent() 

Source Link

Usage

From source file:org.xipki.pki.scep.message.DecodedNextCaMessage.java

License:Open Source License

@SuppressWarnings("unchecked")
public static DecodedNextCaMessage decode(final CMSSignedData pkiMessage,
        final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);

    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }//w ww  .  j av a 2s  . com

    SignerInformation signerInfo = signerInfos.iterator().next();

    SignerId sid = signerInfo.getSID();

    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }

    if (signedDataCerts == null || signedDataCerts.isEmpty()) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }

    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }

    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing signed attributes");
    }

    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = Time.getInstance(attrValue).getDate();
    }

    DecodedNextCaMessage ret = new DecodedNextCaMessage();
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }

    ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
    ret.setDigestAlgorithm(digestAlgOid);

    String sigAlgOid = signerInfo.getEncryptionAlgOID();
    if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
        ASN1ObjectIdentifier tmpDigestAlgOid;
        try {
            tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(),
                    signerInfo.getEncryptionAlgParams());
        } catch (Exception ex) {
            final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: "
                    + ex.getMessage();
            LOG.error(msg);
            LOG.debug(msg, ex);
            ret.setFailureMessage(msg);
            return ret;
        }
        if (!digestAlgOid.equals(tmpDigestAlgOid)) {
            ret.setFailureMessage(
                    "digestAlgorithm and encryptionAlgorithm do not use" + " the same digestAlgorithm");
            return ret;
        }
    } // end if

    X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    X509Certificate signerCert;
    try {
        signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
    } catch (CertificateException ex) {
        final String msg = "could not construct X509CertificateObject: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureCert(signerCert);

    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey());
    } catch (OperatorCreationException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }

    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.signedData.equals(signedContentType)) {
        // fall back: some SCEP client use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage(
                    "either id-signedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }

    ContentInfo contentInfo = ContentInfo.getInstance((byte[]) signedContent.getContent());
    SignedData signedData = SignedData.getInstance(contentInfo.getContent());

    List<X509Certificate> certs;
    try {
        certs = ScepUtil.getCertsFromSignedData(signedData);
    } catch (CertificateException ex) {
        final String msg = "could not extract Certificates from the message: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    final int n = certs.size();

    X509Certificate caCert = null;
    List<X509Certificate> raCerts = new LinkedList<X509Certificate>();
    for (int i = 0; i < n; i++) {
        X509Certificate cert = certs.get(i);
        if (cert.getBasicConstraints() > -1) {
            if (caCert != null) {
                final String msg = "multiple CA certificates is returned, but exactly 1 is expected";
                LOG.error(msg);
                ret.setFailureMessage(msg);
                return ret;
            }
            caCert = cert;
        } else {
            raCerts.add(cert);
        }
    } // end for

    if (caCert == null) {
        final String msg = "no CA certificate is returned";
        LOG.error(msg);
        ret.setFailureMessage(msg);
        return ret;
    }

    X509Certificate[] locaRaCerts;
    if (raCerts.isEmpty()) {
        locaRaCerts = null;
    } else {
        locaRaCerts = raCerts.toArray(new X509Certificate[0]);
    }

    AuthorityCertStore authorityCertStore = AuthorityCertStore.getInstance(caCert, locaRaCerts);
    ret.setAuthorityCertStore(authorityCertStore);

    return ret;
}

From source file:passwdmanager.hig.no.lds.DG_SOD.java

/**
 * Reads the security object (containing the hashes of the data groups)
 * found in the SOD on the card./*from ww  w  .  j a  v  a2 s. c om*/
 * 
 * @return the security object
 * 
 * @throws IOException
 */
private static LDSSecurityObject getSecurityObject(SignedData signedData) {
    try {
        ContentInfo contentInfo = signedData.getEncapContentInfo();
        byte[] content = ((DEROctetString) contentInfo.getContent()).getOctets();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(content));

        LDSSecurityObject sod = new LDSSecurityObject((DERSequence) in.readObject());
        Object nextObject = in.readObject();

        if (nextObject != null) {
            System.err.println("WARNING: extra object found after LDSSecurityObject...");
        }
        return sod;
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not read security object in signedData");
    }
}

From source file:passwdmanager.hig.no.lds.DG_SOD.java

/**
 * Gets the contents of the security object over which the signature is to
 * be computed./*from  w  w w .j a v a 2s.co m*/
 * 
 * See RFC 3369, Cryptographic Message Syntax, August 2002, Section 5.4 for
 * details.
 * 
 * FIXME: Maybe throw an exception instead of issuing warnings on stderr if
 * signed attributes don't check out.
 * 
 * @see #getDocSigningCertificate()
 * @see #getSignature()
 * 
 * @return the contents of the security object over which the signature is
 *         to be computed
 */
public byte[] getEContent() {
    SignerInfo signerInfo = getSignerInfo(signedData);
    ASN1Set signedAttributesSet = signerInfo.getAuthenticatedAttributes();

    ContentInfo contentInfo = signedData.getEncapContentInfo();
    byte[] contentBytes = ((DEROctetString) contentInfo.getContent()).getOctets();

    if (signedAttributesSet.size() == 0) {
        /* Signed attributes absent, return content to be signed... */
        return contentBytes;
    } else {
        /*
         * Signed attributes present (i.e. a structure containing a hash of
         * the content), return that structure to be signed...
         */
        /*
         * This option is taken by ICAO passports and assumingly by ISO18013
         * license? TODO: ?
         */
        byte[] attributesBytes = signedAttributesSet.getDEREncoded();
        String digAlg = signerInfo.getDigestAlgorithm().getObjectId().getId();
        try {
            /*
             * We'd better check that the content actually digests to the
             * hash value contained! ;)
             */
            Enumeration<?> attributes = signedAttributesSet.getObjects();
            byte[] storedDigestedContent = null;
            while (attributes.hasMoreElements()) {
                Attribute attribute = new Attribute((DERSequence) attributes.nextElement());
                DERObjectIdentifier attrType = attribute.getAttrType();
                if (attrType.equals(RFC_3369_MESSAGE_DIGEST_OID)) {
                    ASN1Set attrValuesSet = attribute.getAttrValues();
                    if (attrValuesSet.size() != 1) {
                        System.err.println(
                                "WARNING: expected only one attribute value in signedAttribute message digest in eContent!");
                    }
                    storedDigestedContent = ((DEROctetString) attrValuesSet.getObjectAt(0)).getOctets();
                }
            }
            if (storedDigestedContent == null) {
                System.err.println("WARNING: error extracting signedAttribute message digest in eContent!");
            }
            MessageDigest dig = MessageDigest.getInstance(digAlg);
            byte[] computedDigestedContent = dig.digest(contentBytes);
            if (!Arrays.equals(storedDigestedContent, computedDigestedContent)) {
                System.err.println("WARNING: error checking signedAttribute message digest in eContent!");
            }
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println(
                    "WARNING: error checking signedAttribute in eContent! No such algorithm " + digAlg);
        }
        return attributesBytes;
    }
}

From source file:passwdmanager.hig.no.lds.DG_SOD.java

private static SignedData createSignedData(String digestAlgorithm, String digestEncryptionAlgorithm,
        Map<Integer, byte[]> dataGroupHashes, byte[] encryptedDigest, X509Certificate docSigningCertificate)
        throws NoSuchAlgorithmException, CertificateException {
    ASN1Set digestAlgorithmsSet = createSingletonSet(createDigestAlgorithms(digestAlgorithm));
    ContentInfo contentInfo = createContentInfo(digestAlgorithm, dataGroupHashes);
    byte[] content = ((DEROctetString) contentInfo.getContent()).getOctets();
    ASN1Set certificates = createSingletonSet(createCertificate(docSigningCertificate));
    ASN1Set crls = null;//ww w . j  a va 2  s  .  c  o m
    ASN1Set signerInfos = createSingletonSet(createSignerInfo(digestAlgorithm, digestEncryptionAlgorithm,
            content, encryptedDigest, docSigningCertificate).toASN1Object());
    return new SignedData(digestAlgorithmsSet, contentInfo, certificates, crls, signerInfos);
}

From source file:passwdmanager.hig.no.lds.DG_SOD.java

private static SignedData createSignedData(String digestAlgorithm, String digestEncryptionAlgorithm,
        Map<Integer, byte[]> dataGroupHashes, DocumentSigner signer, X509Certificate docSigningCertificate)
        throws NoSuchAlgorithmException, CertificateException {
    ASN1Set digestAlgorithmsSet = createSingletonSet(createDigestAlgorithms(digestAlgorithm));
    ContentInfo contentInfo = createContentInfo(digestAlgorithm, dataGroupHashes);
    byte[] content = ((DEROctetString) contentInfo.getContent()).getOctets();

    byte[] encryptedDigest = null;
    byte[] dataToBeSigned = createAuthenticatedAttributes(digestAlgorithm, content).getDEREncoded();
    // FIXME should not really be necessary
    signer.setCertificate(docSigningCertificate);
    encryptedDigest = signer.signData(dataToBeSigned);
    if (encryptedDigest == null)
        return null;
    ASN1Set certificates = createSingletonSet(createCertificate(docSigningCertificate));
    ASN1Set crls = null;//from ww  w  . j a v a  2  s.c  o m
    ASN1Set signerInfos = createSingletonSet(createSignerInfo(digestAlgorithm, digestEncryptionAlgorithm,
            content, encryptedDigest, docSigningCertificate).toASN1Object());
    return new SignedData(digestAlgorithmsSet, contentInfo, certificates, crls, signerInfos);
}