Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

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

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

private void findOcsp(ASN1Sequence seq) throws IOException {
    basicResp = null;//www. j  av  a2 s.  com
    boolean ret = false;
    while (true) {
        if ((seq.getObjectAt(0) instanceof DERObjectIdentifier) && ((DERObjectIdentifier) seq.getObjectAt(0))
                .getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
            break;
        }
        ret = true;
        for (int k = 0; k < seq.size(); ++k) {
            if (seq.getObjectAt(k) instanceof ASN1Sequence) {
                seq = (ASN1Sequence) seq.getObjectAt(0);
                ret = false;
                break;
            }
            if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
                ASN1TaggedObject tag = (ASN1TaggedObject) seq.getObjectAt(k);
                if (tag.getObject() instanceof ASN1Sequence) {
                    seq = (ASN1Sequence) tag.getObject();
                    ret = false;
                    break;
                } else
                    return;
            }
        }
        if (ret)
            return;
    }
    DEROctetString os = (DEROctetString) seq.getObjectAt(1);
    ASN1InputStream inp = new ASN1InputStream(os.getOctets());
    BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
    basicResp = new BasicOCSPResp(resp);
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

/**                                                                                                                        
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or                                                        
 * adbe.pkcs7.sha1.                                                                                                        
 * @param contentsKey the /Contents key                                                                                    
 * @param provider the provider or <code>null</code> for the default provider                                              
 *//*from w ww  . jav a  2 s . c  o  m*/
public PdfPKCS7TSA(byte[] contentsKey, Provider provider) {
    try {
        this.provider = provider;
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey));

        //
        // Basic checks to make sure it's a PKCS#7 SignedData Object
        //                                                          
        DERObject pkcs;

        try {
            pkcs = din.readObject();
        } catch (IOException e) {
            throw new IllegalArgumentException("can't decode PKCS7SignedData object");
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException("Not a valid PKCS#7 object - not a sequence");
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        DERObjectIdentifier objId = (DERObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException("Not a valid PKCS#7 object - not signed data");
        ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject();
        // the positions that we care are:                                                            
        //     0 - version                                                                            
        //     1 - digestAlgorithms                                                                   
        //     2 - possible ID_PKCS7_DATA                                                             
        //     (the certificates and crls are taken out by other means)                               
        //     last - signerInfos                                                                     

        // the version
        version = ((DERInteger) content.getObjectAt(0)).getValue().intValue();

        // the digestAlgorithms
        digestalgos = new HashSet();
        Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = (ASN1Sequence) e.nextElement();
            DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0);
            digestalgos.add(o.getId());
        }

        // the certificates and crls
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(contentsKey));
        certs = cr.engineReadAll();
        X509CRLParser cl = new X509CRLParser();
        cl.engineInit(new ByteArrayInputStream(contentsKey));
        crls = cl.engineReadAll();

        // the possible ID_PKCS7_DATA
        ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2);
        if (rsaData.size() > 1) {
            DEROctetString rsaDataContent = (DEROctetString) ((DERTaggedObject) rsaData.getObjectAt(1))
                    .getObject();
            RSAdata = rsaDataContent.getOctets();
        }

        // the signerInfos
        int next = 3;
        while (content.getObjectAt(next) instanceof DERTaggedObject)
            ++next;
        ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next);
        if (signerInfos.size() != 1)
            throw new IllegalArgumentException(
                    "This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
        ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0);
        // the positions that we care are                                                                                  
        //     0 - version                                                                                                 
        //     1 - the signing certificate serial number                                                                   
        //     2 - the digest algorithm                                                                                    
        //     3 or 4 - digestEncryptionAlgorithm                                                                          
        //     4 or 5 - encryptedDigest                                                                                    
        signerversion = ((DERInteger) signerInfo.getObjectAt(0)).getValue().intValue();
        // Get the signing certificate                                                                                     
        ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
        BigInteger serialNumber = ((DERInteger) issuerAndSerialNumber.getObjectAt(1)).getValue();
        for (Iterator i = certs.iterator(); i.hasNext();) {
            X509Certificate cert = (X509Certificate) i.next();
            if (serialNumber.equals(cert.getSerialNumber())) {
                signCert = cert;
                break;
            }
        }
        if (signCert == null) {
            throw new IllegalArgumentException(
                    "Can't find signing certificate with serial " + serialNumber.toString(16));
        }
        signCertificateChain();
        digestAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0))
                .getId();
        next = 3;
        if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set sseq = ASN1Set.getInstance(tagsig, false);
            sigAttr = sseq.getEncoded(ASN1Encodable.DER);

            for (int k = 0; k < sseq.size(); ++k) {
                ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
                if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) {
                    ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
                    digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets();
                } else if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    for (int j = 0; j < seqout.size(); ++j) {
                        ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j);
                        if (tg.getTagNo() != 1)
                            continue;
                        ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                        findOcsp(seqin);
                    }
                }
            }
            if (digestAttr == null)
                throw new IllegalArgumentException("Authenticated attribute is missing the digest.");
            ++next;
        }
        digestEncryptionAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++))
                .getObjectAt(0)).getId();
        digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets();
        if (next < signerInfo.size() && (signerInfo.getObjectAt(next) instanceof DERTaggedObject)) {
            DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next);
            ASN1Set unat = ASN1Set.getInstance(taggedObject, false);
            AttributeTable attble = new AttributeTable(unat);
            Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
            if (ts != null) {
                ASN1Set attributeValues = ts.getAttrValues();
                ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0));
                ContentInfo contentInfo = new ContentInfo(tokenSequence);
                this.timeStampToken = new TimestampToken(contentInfo.getEncoded());
            }
        }
        if (RSAdata != null || digestAttr != null) {
            if (provider == null || provider.getName().startsWith("SunPKCS11"))
                messageDigest = MessageDigest.getInstance(getHashAlgorithm());
            else
                messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider);
        }
        if (provider == null)
            sig = Signature.getInstance(getDigestAlgorithm());
        else
            sig = Signature.getInstance(getDigestAlgorithm(), provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client                  
 * may be provided.                                                                     
 * @param secondDigest the digest in the authenticatedAttributes                        
 * @param signingTime the signing time in the authenticatedAttributes                   
 * @param tsaUrl TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object                              
 * @since   2.1.6                                                                       
 *///from  ww w  .  j  a v a 2  s . c o  m
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, String tsaUrl, byte[] ocsp) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }

        // Create the set of Hash algorithms                                                                
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Iterator it = digestalgos.iterator(); it.hasNext();) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new DERObjectIdentifier((String) it.next()));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.                                                                          
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);

        // Get all the certificates                                                                         
        //                                                                                                  
        v = new ASN1EncodableVector();
        for (Iterator i = certs.iterator(); i.hasNext();) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.                                                                                    
        //                                                                                                                 
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version                                                                                      
        //                                                                                                                 
        signerinfo.add(new DERInteger(signerversion));

        v = new ASN1EncodableVector();
        v.add(getIssuer(signCert.getTBSCertificate()));
        v.add(new DERInteger(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm                                                                                         
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(digestAlgorithm));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present                                                                      
        if (secondDigest != null && signingTime != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
        }
        // Add the digestEncryptionAlgorithm                                                                               
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(digestEncryptionAlgorithm));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the digest                                                                                                  
        signerinfo.add(new DEROctetString(digest));

        // When requested, go get and add the timestamp. May throw an exception.                                           
        // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15                                             
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest                                             
        if (tsaUrl != null) {
            byte[] tsImprint = MessageDigest.getInstance("SHA-1").digest(digest);

            TSResponse response = TimeStampFactory.getTimeStampResponse(tsaUrl, tsImprint, false);
            byte[] tsToken = response.getEncodedToken();

            //Strip the status code out of the response, the adobe validator requieres it. 
            //TODO: Research about this.
            byte[] status = { 0x30, (byte) 0x82, 0x03, (byte) 0xA7, 0x30, 0x03, 0x02, 0x01, 0x00 };
            byte[] modTsToken = new byte[tsToken.length - status.length];
            System.arraycopy(tsToken, status.length, modTsToken, 0, tsToken.length - status.length);

            if (modTsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(modTsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }

        // Finally build the body out of all the components above                                                          
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        if (!crls.isEmpty()) {
            v = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext();) {
                ASN1InputStream t = new ASN1InputStream(
                        new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
                v.add(t.readObject());
            }
            DERSet dercrls = new DERSet(v);
            body.add(new DERTaggedObject(false, 1, dercrls));
        }

        // Only allow one signerInfo                                                                                       
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell                                                         
        // and return it                                                                                                   
        //                                                                                                                 
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp) {
    try {//from   w ww  .ja va 2 s. c om
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
        v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        if (ocsp != null) {
            v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION));
            DEROctetString doctet = new DEROctetString(ocsp);
            ASN1EncodableVector vo1 = new ASN1EncodableVector();
            ASN1EncodableVector v2 = new ASN1EncodableVector();
            v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
            v2.add(doctet);
            DEREnumerated den = new DEREnumerated(0);
            ASN1EncodableVector v3 = new ASN1EncodableVector();
            v3.add(den);
            v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            vo1.add(new DERSequence(v3));
            v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1)))));
            attribute.add(new DERSequence(v));
        } else if (!crls.isEmpty()) {
            v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION));
            ASN1EncodableVector v2 = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext();) {
                ASN1InputStream t = new ASN1InputStream(
                        new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
                v2.add(t.readObject());
            }
            v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 0, new DERSequence(v2)))));
            attribute.add(new DERSequence(v));
        }
        return new DERSet(attribute);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:es.unican.meteo.esgf.myproxyclient.MyProxyLogon.java

License:Open Source License

private static void printKey(PrivateKey paramPrivateKey, PrintStream paramPrintStream) throws IOException {
    paramPrintStream.println("-----BEGIN RSA PRIVATE KEY-----");
    ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramPrivateKey.getEncoded());
    ASN1InputStream localASN1InputStream = new ASN1InputStream(localByteArrayInputStream);
    DERObject localDERObject1 = localASN1InputStream.readObject();
    PrivateKeyInfo localPrivateKeyInfo = new PrivateKeyInfo((ASN1Sequence) localDERObject1);
    DERObject localDERObject2 = localPrivateKeyInfo.getPrivateKey();
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    DEROutputStream localDEROutputStream = new DEROutputStream(localByteArrayOutputStream);
    localDEROutputStream.writeObject(localDERObject2);
    printB64(localByteArrayOutputStream.toByteArray(), paramPrintStream);
    paramPrintStream.println("-----END RSA PRIVATE KEY-----");
    localASN1InputStream.close();
    localDEROutputStream.close();//  w  w w. j  av  a 2  s.c o  m
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkNameConstraints() {
    X509Certificate cert = null;//from  w  w  w. j a  v a 2  s. co m

    //
    // Setup
    //

    // (b)  and (c)
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();

    //
    // process each certificate except the self issued which are not last in the path
    //
    int index;

    try {
        for (index = certs.size() - 1; index >= 0; index--) {
            //
            // certificate processing
            //    

            cert = (X509Certificate) certs.get(index);

            // b),c)

            if (!(isSelfIssued(cert) && index != 0)) {
                X500Principal principal = getSubjectPrincipal(cert);
                ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded()));
                ASN1Sequence dns;

                try {
                    dns = (ASN1Sequence) aIn.readObject();
                } catch (IOException e) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncSubjectNameError",
                            new Object[] { new UntrustedInput(principal) });
                    throw new CertPathReviewerException(msg, e, certPath, index);
                }

                try {
                    nameConstraintValidator.checkPermittedDN(dns);
                } catch (PKIXNameConstraintValidatorException cpve) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN",
                            new Object[] { new UntrustedInput(principal.getName()) });
                    throw new CertPathReviewerException(msg, cpve, certPath, index);
                }

                try {
                    nameConstraintValidator.checkExcludedDN(dns);
                } catch (PKIXNameConstraintValidatorException cpve) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN",
                            new Object[] { new UntrustedInput(principal.getName()) });
                    throw new CertPathReviewerException(msg, cpve, certPath, index);
                }

                //FIX (missing in orig cert path reviewer)
                Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress);
                for (Enumeration e = emails.elements(); e.hasMoreElements();) {
                    String email = (String) e.nextElement();
                    GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email);
                    try {
                        nameConstraintValidator.checkPermitted(emailAsGeneralName);
                    } catch (PKIXNameConstraintValidatorException cpve) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN",
                                new Object[] { new UntrustedInput(principal.getName()) });
                        throw new CertPathReviewerException(msg, cpve, certPath, index);
                    }

                    try {
                        nameConstraintValidator.checkExcluded(emailAsGeneralName);
                    } catch (PKIXNameConstraintValidatorException cpve) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN",
                                new Object[] { new UntrustedInput(principal.getName()) });
                        throw new CertPathReviewerException(msg, cpve, certPath, index);
                    }
                }

                ASN1Sequence altName;
                try {
                    altName = (ASN1Sequence) getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME);
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.subjAltNameExtError");
                    throw new CertPathReviewerException(msg, ae, certPath, index);
                }

                if (altName != null) {
                    for (int j = 0; j < altName.size(); j++) {
                        GeneralName name = GeneralName.getInstance(altName.getObjectAt(j));

                        try {
                            nameConstraintValidator.checkPermitted(name);
                            nameConstraintValidator.checkExcluded(name);
                        } catch (PKIXNameConstraintValidatorException cpve) {
                            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                    "CertPathReviewer.notPermittedEmail",
                                    new Object[] { new UntrustedInput(name) });
                            throw new CertPathReviewerException(msg, cpve, certPath, index);
                        }
                    }
                }

            }

            //
            // prepare for next certificate
            //

            //
            // (g) handle the name constraints extension
            //
            ASN1Sequence ncSeq;
            try {
                ncSeq = (ASN1Sequence) getExtensionValue(cert, NAME_CONSTRAINTS);
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncExtError");
                throw new CertPathReviewerException(msg, ae, certPath, index);
            }

            if (ncSeq != null) {
                NameConstraints nc = NameConstraints.getInstance(ncSeq);

                //
                // (g) (1) permitted subtrees
                //
                GeneralSubtree[] permitted = nc.getPermittedSubtrees();
                if (permitted != null) {
                    nameConstraintValidator.intersectPermittedSubtree(permitted);
                }

                //
                // (g) (2) excluded subtrees
                //
                GeneralSubtree[] excluded = nc.getExcludedSubtrees();
                if (excluded != null) {
                    for (int c = 0; c != excluded.length; c++) {
                        nameConstraintValidator.addExcludedSubtree(excluded[c]);
                    }
                }
            }

        } // for
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage(), cpre.getIndex());
    }
}

From source file:eu.europa.ec.markt.dss.applet.io.RemoteOCSPSource.java

License:Open Source License

@Override
public BasicOCSPResp getOCSPResponse(X509Certificate certificate, X509Certificate issuerCertificate)
        throws IOException {

    try {/*from w  w w.j av a  2  s.  c  om*/
        OCSPRequestMessage request = new OCSPRequestMessage();
        request.setCertificate(certificate.getEncoded());
        request.setIssuerCert(issuerCertificate.getEncoded());

        OCSPResponseMessage response = sendAndReceive(request);

        if (response.getOcspResponse() == null) {
            return null;
        } else {
            ASN1InputStream input = new ASN1InputStream(response.getOcspResponse());
            ASN1Sequence sequence = (ASN1Sequence) input.readObject().toASN1Object();
            return new BasicOCSPResp(new BasicOCSPResponse(sequence));
        }
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}

From source file:eu.europa.ec.markt.dss.DSSRevocationUtils.java

License:Open Source License

/**
 * This method returns the reason of the revocation of the certificate extracted from the given CRL.
 *
 * @param crlEntry An object for a revoked certificate in a CRL (Certificate Revocation List).
 * @return//w w  w  . ja  va2 s  . co  m
 * @throws DSSException
 */
public static String getRevocationReason(final X509CRLEntry crlEntry) throws DSSException {

    final String reasonId = Extension.reasonCode.getId();
    final byte[] extensionBytes = crlEntry.getExtensionValue(reasonId);
    ASN1InputStream asn1InputStream = null;
    try {

        asn1InputStream = new ASN1InputStream(extensionBytes);
        final ASN1Enumerated asn1Enumerated = ASN1Enumerated.getInstance(asn1InputStream.readObject());
        final CRLReason reason = CRLReason.getInstance(asn1Enumerated);
        return reason.toString();
    } catch (IllegalArgumentException e) {
        // In the test case XAdESTest003 testTRevoked() there is an error in the revocation reason.
        //LOG.warn("Error when revocation reason decoding from CRL: " + e.toString());
        final CRLReason reason = CRLReason.lookup(7); // 7 -> unknown
        return reason.toString(); // unknown
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(asn1InputStream);
    }
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

License:Open Source License

private static String getAccessLocation(final X509Certificate certificate,
        final ASN1ObjectIdentifier accessMethod) {

    try {//from   w w  w  .  jav  a  2 s.c o m

        final byte[] authInfoAccessExtensionValue = certificate
                .getExtensionValue(Extension.authorityInfoAccess.getId());
        if (null == authInfoAccessExtensionValue) {
            return null;
        }
        /* Parse the extension */
        final ASN1InputStream asn1InputStream = new ASN1InputStream(
                new ByteArrayInputStream(authInfoAccessExtensionValue));
        final DEROctetString oct = (DEROctetString) (asn1InputStream.readObject());
        asn1InputStream.close();
        final ASN1InputStream asn1InputStream2 = new ASN1InputStream(oct.getOctets());
        final AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(asn1InputStream2.readObject());
        asn1InputStream2.close();

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

            // LOG.debug("access method: " + accessDescription.getAccessMethod());
            final boolean correctAccessMethod = accessDescription.getAccessMethod().equals(accessMethod);
            if (!correctAccessMethod) {
                continue;
            }
            GeneralName gn = accessDescription.getAccessLocation();
            if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {

                // LOG.debug("not a uniform resource identifier");
                continue;
            }
            final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
            accessLocation = str.getString();
            // The HTTP protocol is preferred.
            if (Protocol.isHttpUrl(accessLocation)) {
                // LOG.debug("access location: " + accessLocation);
                break;
            }
        }
        return accessLocation;
    } catch (final IOException e) {

        // we do nothing
        // LOG.("IO error: " + e.getMessage(), e);
    }
    return null;
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

License:Open Source License

public static List<String> getPolicyIdentifiers(final X509Certificate cert) {

    final byte[] certificatePolicies = cert.getExtensionValue(X509Extension.certificatePolicies.getId());
    if (certificatePolicies == null) {

        return Collections.emptyList();
    }/*from   w  w  w . ja  v  a2  s .c  om*/
    ASN1InputStream input = null;
    ASN1Sequence seq = null;
    try {

        input = new ASN1InputStream(certificatePolicies);
        final DEROctetString s = (DEROctetString) input.readObject();
        final byte[] content = s.getOctets();
        input.close();
        input = new ASN1InputStream(content);
        seq = (ASN1Sequence) input.readObject();
    } catch (IOException e) {

        throw new DSSException("Error when computing certificate's extensions.", e);
    } finally {

        closeQuietly(input);
    }
    final List<String> policyIdentifiers = new ArrayList<String>();
    for (int ii = 0; ii < seq.size(); ii++) {

        final PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(ii));
        // System.out.println("\t----> PolicyIdentifier: " + policyInfo.getPolicyIdentifier().getId());
        policyIdentifiers.add(policyInfo.getPolicyIdentifier().getId());

    }
    return policyIdentifiers;
}