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:be.fedict.eid.tsl.Tsl2PdfExporter.java

License:Open Source License

private static List<String> getCrlDistributionPoints(final X509Certificate cert) throws IOException {
    final byte[] extValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (extValue != null) {
        final ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(extValue));
        final DERObject derObj = oAsnInStream.readObject();
        final DEROctetString dos = (DEROctetString) derObj;
        final byte[] val2 = dos.getOctets();
        final ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
        final DERObject derObj2 = oAsnInStream2.readObject();
        return getDERValue(derObj2);
    } else {//w  w w  .j  av a  2s.co  m
        return Collections.emptyList();
    }
}

From source file:be.fedict.trust.constraints.CertificatePoliciesCertificateConstraint.java

License:Open Source License

@Override
public void check(X509Certificate certificate) throws TrustLinkerResultException, Exception {
    byte[] extensionValue = certificate.getExtensionValue(Extension.certificatePolicies.getId());
    if (null == extensionValue) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "missing certificate policies X509 extension");
    }// w  w  w . ja v  a 2  s  .  co m
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extensionValue))
            .readObject());
    ASN1Sequence certPolicies = (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject();
    Enumeration<?> certPoliciesEnum = certPolicies.getObjects();
    while (certPoliciesEnum.hasMoreElements()) {
        PolicyInformation policyInfo = PolicyInformation.getInstance(certPoliciesEnum.nextElement());
        ASN1ObjectIdentifier policyOid = policyInfo.getPolicyIdentifier();
        String policyId = policyOid.getId();
        LOG.debug("present policy OID: " + policyId);
        if (this.certificatePolicies.contains(policyId)) {
            LOG.debug("matching certificate policy OID: " + policyId);
            return;
        }
    }
    throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
            "required policy OID not present");
}

From source file:be.fedict.trust.constraints.CodeSigningCertificateConstraint.java

License:Open Source License

@Override
public void check(X509Certificate certificate) throws TrustLinkerResultException, Exception {
    byte[] extension = certificate.getExtensionValue(Extension.extendedKeyUsage.getId());
    if (null == extension) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "missing ExtendedKeyUsage extension");
    }/*w w w .  ja  v  a 2 s  .co m*/
    if (false == certificate.getCriticalExtensionOIDs().contains(Extension.extendedKeyUsage.getId())) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "ExtendedKeyUsage should be critical");
    }
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extension));
    asn1InputStream = new ASN1InputStream(
            new ByteArrayInputStream(((ASN1OctetString) asn1InputStream.readObject()).getOctets()));
    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(asn1InputStream.readObject());
    if (false == extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_codeSigning)) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "missing codeSigning ExtendedKeyUsage");
    }
    if (1 != extendedKeyUsage.size()) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "ExtendedKeyUsage not solely codeSigning");
    }
}

From source file:be.fedict.trust.constraints.QCStatementsCertificateConstraint.java

License:Open Source License

@Override
public void check(X509Certificate certificate) throws TrustLinkerResultException, Exception {
    byte[] extensionValue = certificate.getExtensionValue(Extension.qCStatements.getId());
    if (null == extensionValue) {
        throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                "missing QCStatements extension");
    }//from  w ww  .  j  a  v  a 2  s.c om
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extensionValue))
            .readObject());
    ASN1Sequence qcStatements = (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject();
    Enumeration<?> qcStatementEnum = qcStatements.getObjects();
    boolean qcCompliance = false;
    boolean qcSSCD = false;
    while (qcStatementEnum.hasMoreElements()) {
        QCStatement qcStatement = QCStatement.getInstance(qcStatementEnum.nextElement());
        ASN1ObjectIdentifier statementId = qcStatement.getStatementId();
        LOG.debug("statement Id: " + statementId.getId());
        if (QCStatement.id_etsi_qcs_QcCompliance.equals(statementId)) {
            qcCompliance = true;
        }
        if (QCStatement.id_etsi_qcs_QcSSCD.equals(statementId)) {
            qcSSCD = true;
        }
    }

    if (null != this.qcComplianceFilter) {
        if (qcCompliance != this.qcComplianceFilter) {
            LOG.error("qcCompliance QCStatements error");
            throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                    "QCStatements not matching");
        }
    }

    if (null != this.qcSSCDFilter) {
        if (qcSSCD != this.qcSSCDFilter) {
            LOG.error("qcSSCD QCStatements error");
            throw new TrustLinkerResultException(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
                    "QCStatements not matching");
        }
    }
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {

    URI crlUri = getCrlUri(childCertificate);
    if (null == crlUri) {
        LOG.debug("no CRL uri in certificate: " + childCertificate.getSubjectX500Principal());
        return TrustLinkerResult.UNDECIDED;
    }//from   w ww . j av a  2  s  .  c o  m

    LOG.debug("CRL URI: " + crlUri);
    X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate);
    if (null == x509crl) {
        LOG.debug("CRL not found");
        return TrustLinkerResult.UNDECIDED;
    }

    // check CRL integrity
    boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate);
    if (false == crlIntegrityResult) {
        LOG.debug("CRL integrity check failed");
        return TrustLinkerResult.UNDECIDED;
    }

    // check CRL signature algorithm
    algorithmPolicy.checkSignatureAlgorithm(x509crl.getSigAlgOID(), validationDate);

    // we don't support indirect CRLs
    if (isIndirectCRL(x509crl)) {
        LOG.debug("indirect CRL detected");
        return TrustLinkerResult.UNDECIDED;
    }

    LOG.debug("CRL number: " + getCrlNumber(x509crl));

    // fill up revocation data if not null with this valid CRL
    if (null != revocationData) {
        try {
            CRLRevocationData crlRevocationData = new CRLRevocationData(x509crl.getEncoded(),
                    crlUri.toString());
            revocationData.getCrlRevocationData().add(crlRevocationData);
        } catch (CRLException e) {
            LOG.error("CRLException: " + e.getMessage(), e);
            throw new TrustLinkerResultException(TrustLinkerResultReason.UNSPECIFIED,
                    "CRLException : " + e.getMessage(), e);
        }
    }

    X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber());
    if (null == crlEntry) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal());
        return TrustLinkerResult.TRUSTED;
    } else if (crlEntry.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        return TrustLinkerResult.TRUSTED;
    }

    LOG.debug("certificate revoked/suspended at: " + crlEntry.getRevocationDate());
    if (crlEntry.hasExtensions()) {
        LOG.debug("critical extensions: " + crlEntry.getCriticalExtensionOIDs());
        LOG.debug("non-critical extensions: " + crlEntry.getNonCriticalExtensionOIDs());
        byte[] reasonCodeExtension = crlEntry.getExtensionValue(Extension.reasonCode.getId());
        if (null != reasonCodeExtension) {
            try {
                DEROctetString octetString = (DEROctetString) (new ASN1InputStream(
                        new ByteArrayInputStream(reasonCodeExtension)).readObject());
                byte[] octets = octetString.getOctets();
                CRLReason crlReason = CRLReason
                        .getInstance(ASN1Enumerated.getInstance(new ASN1InputStream(octets).readObject()));
                BigInteger crlReasonValue = crlReason.getValue();
                LOG.debug("CRL reason value: " + crlReasonValue);
                switch (crlReasonValue.intValue()) {
                case CRLReason.certificateHold:
                    throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                            "certificate suspended by CRL=" + crlEntry.getSerialNumber());
                }
            } catch (IOException e) {
                throw new TrustLinkerResultException(TrustLinkerResultReason.UNSPECIFIED,
                        "IO error: " + e.getMessage(), e);
            }
        }
    }

    throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by CRL=" + crlEntry.getSerialNumber());

}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

License:Open Source License

/**
 * Gives back the CRL URI meta-data found within the given X509 certificate.
 * //from   www .j av  a  2s .  c om
 * @param certificate
 *            the X509 certificate.
 * @return the CRL URI, or <code>null</code> if the extension is not
 *         present.
 */
public static URI getCrlUri(X509Certificate certificate) {
    byte[] crlDistributionPointsValue = certificate.getExtensionValue(Extension.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.debug("not a uniform resource identifier");
                continue;
            }
            DERIA5String derStr = DERIA5String.getInstance(name.getName());
            String str = derStr.getString();
            if (false == str.startsWith("http")) {
                /*
                 * skip ldap:// protocols
                 */
                LOG.debug("not HTTP/HTTPS: " + str);
                continue;
            }
            URI uri = toURI(str);
            return uri;
        }
    }
    return null;
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

License:Open Source License

private static BigInteger getCrlNumber(X509CRL crl) {
    byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId());
    if (null == crlNumberExtensionValue) {
        return null;
    }/*www.ja  v a2  s  . c  om*/
    try {
        ASN1OctetString octetString = (ASN1OctetString) (new ASN1InputStream(
                new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
        byte[] octets = octetString.getOctets();
        ASN1Integer integer = (ASN1Integer) new ASN1InputStream(octets).readObject();
        BigInteger crlNumber = integer.getPositiveValue();
        return crlNumber;
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

private URI getAccessLocation(X509Certificate certificate, ASN1ObjectIdentifier accessMethod)
        throws IOException, URISyntaxException {
    byte[] authInfoAccessExtensionValue = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
    if (null == authInfoAccessExtensionValue) {
        return null;
    }/*from w ww  .  j  a v a  2s  . c  o  m*/
    AuthorityInformationAccess authorityInformationAccess;
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(
            new ByteArrayInputStream(authInfoAccessExtensionValue)).readObject());
    authorityInformationAccess = AuthorityInformationAccess
            .getInstance(new ASN1InputStream(oct.getOctets()).readObject());
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        LOG.debug("access method: " + accessDescription.getAccessMethod());
        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;
        }
        DERIA5String str = DERIA5String.getInstance(gn.getName());
        String accessLocation = str.getString();
        LOG.debug("access location: " + accessLocation);
        URI uri = toURI(accessLocation);
        LOG.debug("access location URI: " + uri);
        return uri;
    }
    return null;
}

From source file:be.fedict.trust.service.bean.HarvesterMDB.java

License:Open Source License

private BigInteger getCrlNumber(X509CRL crl) {
    byte[] crlNumberExtensionValue = crl.getExtensionValue("2.5.29.20");
    if (null == crlNumberExtensionValue) {
        return null;
    }//ww w  . ja  v  a 2s. c o m
    try {
        DEROctetString octetString = (DEROctetString) (new ASN1InputStream(
                new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
        byte[] octets = octetString.getOctets();
        DERInteger integer = (DERInteger) new ASN1InputStream(octets).readObject();
        return integer.getPositiveValue();
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
}

From source file:beta01.SimpleGenCert.java

private void generateRoot() throws Exception {
    KeyPair keyRoot = JcaUtils.generateRSAKeyPair();
    BcCredential rootCredential;/*from w w w.  ja  va  2s  . c  o  m*/
    rootCredential = BcUtils.createRootCredential();
    X509Certificate holderRoot = JcaUtils.buildRootCert(keyRoot);

    Certificate[] chain = new Certificate[1];

    chain[0] = holderRoot;

    KeyStore pkcs12 = KeyStore.getInstance("PKCS12", "BC");
    pkcs12.load(null, null);
    //pkcs12.setCertificateEntry("r2oot", holderRoot);
    pkcs12.setKeyEntry("root", keyRoot.getPrivate(), null, chain);

    //store
    char[] password = "pass".toCharArray();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    pkcs12.store(bOut, password);

    System.out.println("Public Key: " + keyRoot.getPublic());
    ASN1InputStream asnInput = new ASN1InputStream(bOut.toByteArray());
    bOut.reset();
    //        DEROutputStream derOut = new BEROutputStream(bOut);
    //derOut.writeObject(asnInput.readObject());
    byte[] derFormat = bOut.toByteArray();
    try {
        File file = new File("D:\\rootPrivateKeySS.p12");
        FileOutputStream fos = new FileOutputStream(file);
        bOut.close();
        fos.write(derFormat);
        fos.flush();
        fos.close();
    } catch (IOException ex) {

    }
    // reload from scratch
    pkcs12 = KeyStore.getInstance("PKCS12", "BC");

    pkcs12.load(new ByteArrayInputStream(bOut.toByteArray()), password);
    Enumeration en = pkcs12.aliases();
    while (en.hasMoreElements()) {
        String alias = (String) en.nextElement();
        System.out.println("found " + alias + ", isCertificate? " + pkcs12.isCertificateEntry(alias));
    }

}