Example usage for org.bouncycastle.asn1.cms SignerInfo getDigestAlgorithm

List of usage examples for org.bouncycastle.asn1.cms SignerInfo getDigestAlgorithm

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms SignerInfo getDigestAlgorithm.

Prototype

public AlgorithmIdentifier getDigestAlgorithm() 

Source Link

Usage

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

License:Apache License

public CMSSignedData generate(ASN1ObjectIdentifier contentTypeOID, ASN1Encodable content)
        throws CMSException, IOException {
    digests.clear();//from  w  ww. j  a  va  2s .  c o m

    SignerInfo signerInfo;

    if (!_signers.isEmpty()) {
        signerInfo = ((SignerInformation) _signers.get(0)).toASN1Structure();
    } else {
        SignerInfoGenerator signerInfoGenerator = (SignerInfoGenerator) signerGens.get(0);

        byte[] signedContent = content.toASN1Primitive().getEncoded("DER");

        OutputStream out = signerInfoGenerator.getCalculatingOutputStream();
        out.write(signedContent, 2, signedContent.length - 2); // skip the first 2 bytes as specified
        out.flush();
        out.close();

        signerInfo = signerInfoGenerator.generate(contentTypeOID);

        byte[] calculatedDigest = signerInfoGenerator.getCalculatedDigest();
        digests.put(signerInfoGenerator.getDigestAlgorithm().getAlgorithm().getId(), calculatedDigest);
    }

    ContentInfo encInfo = new ContentInfo(contentTypeOID, content);
    ASN1Set certificates = new DERSet((ASN1Encodable[]) certs.toArray(new ASN1Encodable[0]));

    ASN1Encodable signedData = new AuthenticodeSignedData(signerInfo.getDigestAlgorithm(), encInfo,
            certificates, signerInfo);

    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);

    return new CMSSignedData(
            new CMSProcessableByteArray(contentTypeOID, content.toASN1Primitive().getEncoded("DER")),
            contentInfo);
}

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

License:Open Source License

public static String getSignerInfoDigestAlgorithm(SignedData signedData) {
    try {//w w  w.j  av a  2s  .c o  m
        SignerInfo signerInfo = getSignerInfo(signedData);
        String digestAlgOID = signerInfo.getDigestAlgorithm().getAlgorithm().getId();
        return SignedDataUtil.lookupMnemonicByOID(digestAlgOID);
    } catch (NoSuchAlgorithmException nsae) {
        LOGGER.severe("Exception: " + nsae.getMessage());
        return null; // throw new IllegalStateException(nsae.toString());
    }
}

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

License:Open Source License

/**
 * Gets the contents of the signed data over which the
 * signature is to be computed.//from   w ww .  j  a v  a  2s .c o m
 *
 * See RFC 3369, Cryptographic Message Syntax, August 2002,
 * Section 5.4 for details.
 *
 * FIXME: Maybe throw an exception instead of issuing warnings
 * on logger if signed attributes do not check out.
 *
 * @see #getDocSigningCertificate()
 * @see #getSignature()
 *
 * @return the contents of the security object over which the
 *         signature is to be computed
 */
public static byte[] getEContent(SignedData signedData) {
    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;
    }

    /* 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. */
    byte[] attributesBytes = null;
    String digAlg = signerInfo.getDigestAlgorithm().getAlgorithm().getId();

    try {
        attributesBytes = signedAttributesSet.getEncoded(ASN1Encoding.DER);

        checkEContent(getAttributes(signedAttributesSet), digAlg, contentBytes);

    } catch (NoSuchAlgorithmException nsae) {
        LOGGER.warning("Error checking signedAttributes in eContent! No such algorithm: \"" + digAlg + "\": "
                + nsae.getMessage());
    } catch (IOException ioe) {
        LOGGER.severe("Error getting signedAttributes: " + ioe.getMessage());
    }

    return attributesBytes;
}

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

License:Open Source License

/**
 * Checks if the provided signedData was signed by the entity represented
 * by the provided certificate./*  w w w .  j av  a 2 s  . c  om*/
 *  
 * @param signedData the signedData to verify.
 * @param signer the signing entity.
 * @return <code>true</code> if the signedData was signed by the entity, <code>false</code> otherwise.
 */
public static boolean isSignedBy(SignedData signedData, X509Certificate signer) {
    X509Name signerName = X509Util.toX509Name(signer.getIssuerX500Principal());
    BigInteger signerSerialNo = signer.getSerialNumber();
    IssuerAndSerialNumber issuerIasn = new IssuerAndSerialNumber(signerName, signerSerialNo);

    final ASN1Set signerInfos = signedData.getSignerInfos();
    @SuppressWarnings("unchecked")
    Enumeration<ASN1Sequence> seqs = signerInfos.getObjects();
    while (seqs.hasMoreElements()) {
        final ASN1Sequence seq = seqs.nextElement();
        SignerInfo signerInfo = new SignerInfo(seq);
        signerInfo.getAuthenticatedAttributes();
        SignerIdentifier signerId = signerInfo.getSID();
        IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(signerId.getId());

        if (areEqual(issuerIasn, iasn) == false) {
            continue;
        }
        // We've found the right issuer.
        ASN1OctetString signedDigest = signerInfo.getEncryptedDigest();
        String sigAlg = AlgorithmDictionary.lookup(signerInfo.getDigestAlgorithm());
        Signature sig;
        try {
            sig = Signature.getInstance(sigAlg);
        } catch (NoSuchAlgorithmException e) {
            return false;
        }
        try {
            sig.initVerify(signer);
        } catch (InvalidKeyException e) {
            return false;
        }
        try {
            sig.update(getHash(signerInfo));
            return sig.verify(signedDigest.getOctets());
        } catch (SignatureException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }

    return false;
}

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

License:Open Source License

/**
 * Gets the contents of the security object over which the
 * signature is to be computed. /*  www . j  a v  a2s.  c o  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
 */
private static byte[] getEContent(SignedData signedData) throws IOException {
    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. */
        byte[] attributesBytes = signedAttributesSet.getEncoded();
        String digAlg = signerInfo.getDigestAlgorithm().getAlgorithm().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 = Attribute.getInstance(attributes.nextElement());
                DERObjectIdentifier attrType = attribute.getAttrType();
                if (attrType.equals(RFC_3369_MESSAGE_DIGEST_OID)) {
                    ASN1Set attrValuesSet = attribute.getAttrValues();
                    if (attrValuesSet.size() != 1) {
                        LOGGER.warning(
                                "Expected only one attribute value in signedAttribute message digest in eContent!");
                    }
                    storedDigestedContent = ((DEROctetString) attrValuesSet.getObjectAt(0)).getOctets();
                }
            }
            if (storedDigestedContent == null) {
                LOGGER.warning("Error extracting signedAttribute message digest in eContent!");
            }
            MessageDigest dig = MessageDigest.getInstance(digAlg);
            byte[] computedDigestedContent = dig.digest(contentBytes);
            if (!Arrays.equals(storedDigestedContent, computedDigestedContent)) {
                LOGGER.warning("Error checking signedAttribute message digest in eContent!");
            }
        } catch (NoSuchAlgorithmException nsae) {
            LOGGER.warning("Error checking signedAttribute in eContent! No such algorithm " + digAlg);
        }
        return attributesBytes;
    }
}

From source file:org.votingsystem.signature.util.PDFContentSigner.java

License:Open Source License

public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate,
        Provider sigProvider, boolean addDefaultAttributes, List<SignerInfo> signerInfoList)
        throws NoSuchAlgorithmException, CMSException, Exception {
    // TODO if (signerInfs.isEmpty()){
    //            /* RFC 3852 5.2
    //             * "In the degenerate case where there are no signers, the
    //             * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
    //             * case, the content type within the EncapsulatedContentInfo value being
    //             * "signed" MUST be id-data (as defined in section 4), and the content
    //             * field of the EncapsulatedContentInfo value MUST be omitted."
    //             *//*  w  w w  . jav  a 2s .  c  o  m*/
    //            if (encapsulate) {
    //                throw new IllegalArgumentException("no signers, encapsulate must be false");
    //            } if (!DATA.equals(eContentType)) {
    //                throw new IllegalArgumentException("no signers, eContentType must be id-data");
    //            }
    //        }
    //        if (!DATA.equals(eContentType)) {
    //            /* RFC 3852 5.3
    //             * [The 'signedAttrs']...
    //             * field is optional, but it MUST be present if the content type of
    //             * the EncapsulatedContentInfo value being signed is not id-data.
    //             */
    //            // TODO signedAttrs must be present for all signers
    //        }
    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    digests.clear(); // clear the current preserved digest state
    Iterator it = _signers.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID()));
        signerInfos.add(signer.toSignerInfo());
    }
    boolean isCounterSignature = (eContentType == null);
    ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data
            : new ASN1ObjectIdentifier(eContentType);
    for (SignerInfo signerInfo : signerInfoList) {
        digestAlgs.add(signerInfo.getDigestAlgorithm());
        signerInfos.add(signerInfo);
    }
    ASN1Set certificates = null;
    if (!certs.isEmpty())
        certificates = CMSUtils.createBerSetFromList(certs);
    ASN1Set certrevlist = null;
    if (!crls.isEmpty())
        certrevlist = CMSUtils.createBerSetFromList(crls);
    ASN1OctetString octs = null;
    if (encapsulate && content != null) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        content.write(bOut);
        octs = new BERConstructedOctetString(bOut.toByteArray());
    }
    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}

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.// w  ww .ja v  a  2s  . c o 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;
    }
}