Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java

License:Open Source License

/**
 * Gives back the CRL URI meta-data found within the given X509 certificate.
 * /*from  w  w  w  .j ava  2 s . c o m*/
 * @param certificate the X509 certificate.
 * @return the CRL URI, or <code>null</code> if the extension is not present.
 * @throws MalformedURLException
 */
@SuppressWarnings("deprecation")
public String getCrlUri(X509Certificate certificate) throws MalformedURLException {
    byte[] crlDistributionPointsValue = certificate
            .getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (null == crlDistributionPointsValue) {
        return null;
    }
    ASN1Sequence seq;
    try {
        DEROctetString oct;
        oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(crlDistributionPointsValue))
                .readObject());
        seq = (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject();
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    CRLDistPoint distPoint = CRLDistPoint.getInstance(seq);
    DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
    for (DistributionPoint distributionPoint : distributionPoints) {
        DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
        if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
            continue;
        }
        GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
        GeneralName[] names = generalNames.getNames();
        for (GeneralName name : names) {
            if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
                LOG.fine("not a uniform resource identifier");
                continue;
            }
            String str = null;
            if (name.getDERObject() instanceof DERTaggedObject) {
                DERTaggedObject taggedObject = (DERTaggedObject) name.getDERObject();
                DERIA5String derStr = DERIA5String.getInstance(taggedObject.getObject());
                str = derStr.getString();
            } else {
                DERIA5String derStr = DERIA5String.getInstance(name.getDERObject());
                str = derStr.getString();
            }
            if (str != null && (str.startsWith("http://") || str.startsWith("https://"))) {
                return str;
            } else {
                LOG.info("Supports only http:// and https:// protocol for CRL");
            }
        }
    }
    return null;
}

From source file:eu.europa.ec.markt.dss.validation.ocsp.OnlineOCSPSource.java

License:Open Source License

@SuppressWarnings("deprecation")
private String getAccessLocation(X509Certificate certificate, DERObjectIdentifier accessMethod)
        throws IOException {
    byte[] authInfoAccessExtensionValue = certificate
            .getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (null == authInfoAccessExtensionValue) {
        return null;
    }// w  ww  .  j  a v  a2s.  c  om
    AuthorityInformationAccess authorityInformationAccess;

    DEROctetString oct = (DEROctetString) (new ASN1InputStream(
            new ByteArrayInputStream(authInfoAccessExtensionValue)).readObject());
    authorityInformationAccess = new AuthorityInformationAccess(
            (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject());

    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        LOG.fine("access method: " + accessDescription.getAccessMethod());
        boolean correctAccessMethod = accessDescription.getAccessMethod().equals(accessMethod);
        if (!correctAccessMethod) {
            continue;
        }
        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {
            LOG.fine("not a uniform resource identifier");
            continue;
        }
        DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.getDERObject()).getObject();
        String accessLocation = str.getString();
        LOG.fine("access location: " + accessLocation);
        return accessLocation;
    }
    return null;

}

From source file:eu.europa.ec.markt.dss.validation.tsl.PolicyIdCondition.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*from ww  w  .  j a v  a2s. co  m*/
public boolean check(CertificateAndContext cert) {
    byte[] certificatePolicies = cert.getCertificate()
            .getExtensionValue(X509Extensions.CertificatePolicies.getId());
    if (certificatePolicies != null) {
        try {
            ASN1InputStream input = new ASN1InputStream(certificatePolicies);
            DEROctetString s = (DEROctetString) input.readObject();
            byte[] content = s.getOctets();
            input = new ASN1InputStream(content);
            DERSequence seq = (DERSequence) input.readObject();
            for (int i = 0; i < seq.size(); i++) {
                PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(i));
                if (policyInfo.getPolicyIdentifier().getId().equals(policyOid)) {
                    return true;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return false;
}

From source file:eu.europa.ec.markt.dss.validation.tsl.QcStatementCondition.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*from   w w  w  .j a va  2s.c  om*/
public boolean check(CertificateAndContext cert) {
    byte[] qcStatement = cert.getCertificate().getExtensionValue(X509Extensions.QCStatements.getId());
    if (qcStatement != null) {
        try {
            ASN1InputStream input = new ASN1InputStream(qcStatement);
            DEROctetString s = (DEROctetString) input.readObject();
            byte[] content = s.getOctets();
            input = new ASN1InputStream(content);
            DERSequence seq = (DERSequence) input.readObject();
            /* Sequence of QCStatment */
            for (int i = 0; i < seq.size(); i++) {
                QCStatement statement = QCStatement.getInstance(seq.getObjectAt(i));
                if (statement.getStatementId().getId().equals(qcStatementId)) {
                    return true;
                }
            }
            return false;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return false;
}

From source file:eu.europa.ec.markt.dss.validation102853.crl.OnlineCRLSource.java

License:Open Source License

/**
 * Gives back the CRL URI meta-data found within the given X509 certificate.
 *
 * @param certificateToken the X509 certificate.
 * @return the CRL URI, or {@code null} if the extension is not present.
 * @throws DSSException/*w  ww  . j av a2 s.  c  o m*/
 */
public String getCrlUrl(final CertificateToken certificateToken) throws DSSException {

    final byte[] crlDistributionPointsValue = certificateToken.getCRLDistributionPoints();
    if (null == crlDistributionPointsValue) {

        return null;
    }
    ASN1InputStream ais1 = null;
    ASN1InputStream ais2 = null;
    try {

        List<String> urls = new ArrayList<String>();
        final ByteArrayInputStream bais = new ByteArrayInputStream(crlDistributionPointsValue);
        ais1 = new ASN1InputStream(bais);
        final DEROctetString oct = (DEROctetString) (ais1.readObject());
        ais2 = new ASN1InputStream(oct.getOctets());
        final ASN1Sequence seq = (ASN1Sequence) ais2.readObject();
        final CRLDistPoint distPoint = CRLDistPoint.getInstance(seq);
        final DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
        for (final DistributionPoint distributionPoint : distributionPoints) {

            final DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
            if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {

                continue;
            }
            final GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
            final GeneralName[] names = generalNames.getNames();
            for (final GeneralName name : names) {

                if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {

                    LOG.debug("Not a uniform resource identifier");
                    continue;
                }
                final String urlStr;
                if (name.toASN1Primitive() instanceof DERTaggedObject) {

                    final DERTaggedObject taggedObject = (DERTaggedObject) name.toASN1Primitive();
                    final DERIA5String derStr = DERIA5String.getInstance(taggedObject.getObject());
                    urlStr = derStr.getString();
                } else {

                    final DERIA5String derStr = DERIA5String.getInstance(name.toASN1Primitive());
                    urlStr = derStr.getString();
                }
                urls.add(urlStr);
            }
        }
        if (preferredProtocol != null) {

            for (final String url : urls) {

                if (preferredProtocol.isTheSame(url)) {
                    return url;
                }
            }
        }
        if (urls.size() > 0) {

            final String url = urls.get(0);
            return url;
        }
        return null;
    } catch (IOException e) {

        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(ais1);
        DSSUtils.closeQuietly(ais2);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.CRLCertificateVerifier.java

License:Open Source License

@Override
public RevocationToken check(final CertificateToken toCheckToken) {

    String crlUri = null;//from   ww w  .  jav  a  2  s .co m
    try {

        if (crlSource == null) {

            toCheckToken.extraInfo().infoCRLSourceIsNull();
            return null;
        }
        final X509Certificate toCheckCert = toCheckToken.getCertificate();
        final X509Certificate issuerCert = toCheckToken.getIssuerToken().getCertificate();
        final X509CRL x509crl = crlSource.findCrl(toCheckCert, issuerCert);
        if (crlSource instanceof OnlineCRLSource) {

            crlUri = ((OnlineCRLSource) crlSource).getCrlUri(toCheckCert);
        }
        if (x509crl == null) {

            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("No CRL found for " + toCheckToken.getDSSIdAsString());
            }
            if (crlSource instanceof OnlineCRLSource) {

                toCheckToken.extraInfo().infoNoCRLInfoFound(crlUri);
            }
            return null;
        }
        final CRLToken crlToken = new CRLToken(x509crl);
        if (crlSource instanceof OnlineCRLSource) {

            crlToken.setSourceURI(crlUri);
        }
        if (!isCRLTokenValid(crlToken, toCheckToken.getIssuerToken())) {

            LOG.warning("The CRL is not valid !");
            toCheckToken.extraInfo().infoCRLIsNotValid();
            return null;
        }
        final X509CRLEntry crlEntry = x509crl.getRevokedCertificate(toCheckCert.getSerialNumber());
        if (null == crlEntry) {

            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("CRL OK for: " + toCheckToken.getDSSIdAsString());
            }
            /*
             * If there is no entry in the CRL, the certificate is more likely to be valid
             */
            crlToken.setStatus(true);
        } else {

            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("CRL reports certificate: " + toCheckToken.getDSSIdAsString() + " as revoked since "
                        + crlEntry.getRevocationDate());
            }
            crlToken.setStatus(false);
            crlToken.setRevocationDate(crlEntry.getRevocationDate());
            final byte[] extensionBytes = crlEntry.getExtensionValue(X509Extension.reasonCode.getId());
            ASN1InputStream dIn = null;
            try {

                dIn = new ASN1InputStream(extensionBytes);
                CRLReason reason = new CRLReason(DEREnumerated.getInstance(dIn.readObject()));
                crlToken.setReason(reason.toString());
            } catch (IllegalArgumentException e) {
                // In the test case XAdESTest003 testTRevoked() there is an error in the revocation reason.
                LOG.warning("Error when revocation reason decoding from CRL: " + e.toString());
                crlToken.setReason(new CRLReason(7).toString()); // unknown
            } finally {

                DSSUtils.closeQuietly(dIn);
            }
        }
        toCheckToken.setRevocationToken(crlToken);
        return crlToken;
    } catch (final Exception e) {

        LOG.log(Level.SEVERE, "Exception when accessing CRL for " + toCheckToken.getDSSIdAsString(), e);
        toCheckToken.extraInfo().infoCRLException(crlUri, e);
        return null;
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.ocsp.OnlineOCSPSource.java

License:Open Source License

/**
 * Gives back the OCSP URI meta-data found within the given X509 cert.
 *
 * @param certificate the X509 cert./*from w  ww.  jav  a2  s  .c o m*/
 * @return the OCSP URI, or <code>null</code> if the extension is not present.
 * @throws DSSException
 */
public String getAccessLocation(final X509Certificate certificate) throws DSSException {

    final ASN1ObjectIdentifier ocspAccessMethod = X509ObjectIdentifiers.ocspAccessMethod;
    final byte[] authInfoAccessExtensionValue = certificate
            .getExtensionValue(X509Extension.authorityInfoAccess.getId());
    if (null == authInfoAccessExtensionValue) {

        return null;
    }
    ASN1InputStream ais1 = null;
    ASN1InputStream ais2 = null;
    try {

        final ByteArrayInputStream bais = new ByteArrayInputStream(authInfoAccessExtensionValue);
        ais1 = new ASN1InputStream(bais);
        final DEROctetString oct = (DEROctetString) (ais1.readObject());
        ais2 = new ASN1InputStream(oct.getOctets());
        final AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(ais2.readObject());

        final AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
        for (AccessDescription accessDescription : accessDescriptions) {

            if (LOG.isDebugEnabled()) {
                LOG.debug("Access method: " + accessDescription.getAccessMethod());
            }
            final boolean correctAccessMethod = accessDescription.getAccessMethod().equals(ocspAccessMethod);
            if (!correctAccessMethod) {

                continue;
            }
            final GeneralName gn = accessDescription.getAccessLocation();
            if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Not a uniform resource identifier");
                }
                continue;
            }
            final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
            final String accessLocation = str.getString();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Access location: " + accessLocation);
            }
            return accessLocation;
        }
        return null;
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(ais1);
        DSSUtils.closeQuietly(ais2);
    }
}

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

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*from  w  w  w.ja v  a 2s .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.CAdESLevelBExternalSignatureTest.java

License:Open Source License

private ExternalSignatureResult simulateExternalSignature(ToBeSigned toBeSigned) {
    ExternalSignatureResult externalSignatureResult = new ExternalSignatureResult();

    // Get hold of signature certificate.
    CertificateToken signingCertificate = getSigningCert();
    externalSignatureResult.setSigningCertificate(signingCertificate);

    DigestAlgorithm digestAlgo = signatureParameters.getDigestAlgorithm();

    // Add the signing-certificate/signing-certificate-v2 attribute to DER encoded SignedAttributes.
    try (ASN1InputStream asn1InputStream = new ASN1InputStream(toBeSigned.getBytes())) {
        DLSet dlSet = (DLSet) asn1InputStream.readObject();
        AttributeTable signedAttribute = new AttributeTable(dlSet);
        ASN1EncodableVector signedAttributeEncodableVector = signedAttribute.toASN1EncodableVector();

        CMSUtils.addSigningCertificateAttribute(signedAttributeEncodableVector, digestAlgo, signingCertificate);

        DERSet signedAttributesData = new DERSet(signedAttributeEncodableVector);

        // Update toBeSigned
        toBeSigned.setBytes(signedAttributesData.getEncoded());
        externalSignatureResult.setSignedData(toBeSigned.getBytes());
    } catch (Exception e) {
        LOG.error("Error while simulating external CAdES signature", e);
    }//from  www  .  j a v  a 2  s. c o  m

    SignatureValue signatureValue = getToken().sign(toBeSigned, getSignatureParameters().getDigestAlgorithm(),
            getSignatureParameters().getMaskGenerationFunction(), getPrivateKeyEntry());
    externalSignatureResult.setSignatureValue(signatureValue);

    return externalSignatureResult;
}

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

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {//w  w w.  j  ava2  s. c  o 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());
            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());
    }
}