Example usage for org.bouncycastle.asn1 DEROctetString getOctets

List of usage examples for org.bouncycastle.asn1 DEROctetString getOctets

Introduction

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

Prototype

public byte[] getOctets() 

Source Link

Document

Return the content of the OCTET STRING as a byte array.

Usage

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

License:Open Source License

/**
 * Reads the security object (containing the hashes
 * of the data groups) found in the SignedData field.
 *
 * @return the security object//www. j  a v  a2s. c  om
 *
 * @throws IOException
 */
private static LDSSecurityObject getLDSSecurityObject(SignedData signedData) {
    try {
        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        String contentType = encapContentInfo.getContentType().getId();
        DEROctetString eContent = (DEROctetString) encapContentInfo.getContent();
        if (!(ICAO_LDS_SOD_OID.equals(contentType) || SDU_LDS_SOD_OID.equals(contentType)
                || ICAO_LDS_SOD_ALT_OID.equals(contentType))) {
            LOGGER.warning("SignedData does not appear to contain an LDS SOd. (content type is " + contentType
                    + ", was expecting " + ICAO_LDS_SOD_OID + ")");
        }
        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(eContent.getOctets()));

        Object firstObject = inputStream.readObject();
        if (!(firstObject instanceof ASN1Sequence)) {
            throw new IllegalStateException(
                    "Expected ASN1Sequence, found " + firstObject.getClass().getSimpleName());
        }
        LDSSecurityObject sod = LDSSecurityObject.getInstance(firstObject);
        Object nextObject = inputStream.readObject();
        if (nextObject != null) {
            LOGGER.warning("Ignoring extra object found after LDSSecurityObject...");
        }
        return sod;
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not read security object in signedData");
    }
}

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

License:Open Source License

/**
 * Checks the correctness of the data for this instance of SecurityInfo
 *//*from   w w  w .  ja  v  a  2 s. c  om*/
private void checkFields() {
    try {
        if (!checkRequiredIdentifier(oid)) {
            throw new IllegalArgumentException("Wrong identifier: " + oid);
        }
        if (version != VERSION_NUM_1 && version != VERSION_NUM_2) {
            throw new IllegalArgumentException("Wrong version. Was expecting " + VERSION_NUM_1 + " or "
                    + VERSION_NUM_2 + ", found " + version);
        }
        if (efCVCA != null) {
            DEROctetString fid = (DEROctetString) efCVCA.getObjectAt(0);
            if (fid.getOctets().length != 2) {
                throw new IllegalArgumentException("Malformed FID.");
            }
            if (efCVCA.size() == 2) {
                DEROctetString sfi = (DEROctetString) efCVCA.getObjectAt(1);
                if (sfi.getOctets().length != 1) {
                    throw new IllegalArgumentException("Malformed SFI.");
                }
            }
        }
    } catch (Exception e) {
        LOGGER.severe("Exception: " + e.getMessage());
        throw new IllegalArgumentException("Malformed TerminalAuthenticationInfo.");
    }
}

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

License:Open Source License

private static short getFileId(ASN1Sequence efCVCA) {
    if (efCVCA == null) {
        return -1;
    }/*from  w  ww.ja  va  2s .co m*/
    ASN1Sequence s = (ASN1Sequence) efCVCA;
    DEROctetString fid = (DEROctetString) s.getObjectAt(0);
    byte[] bytes = fid.getOctets();
    return (short) (((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF));
}

From source file:org.jnotary.crypto.CRLLoader.java

License:Open Source License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list. //w  w  w.jav  a2  s  .com
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(X509Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return Collections.emptyList();
    }
    ASN1InputStream oAsnInStream = null;
    ASN1InputStream oAsnInStream2 = null;
    List<String> crlUrls = new ArrayList<String>();

    try {
        oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
        ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
        DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
        byte[] crldpExtOctets = dosCrlDP.getOctets();
        oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
        ASN1Primitive derObj2 = oAsnInStream2.readObject();
        CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
        for (DistributionPoint dp : distPoint.getDistributionPoints()) {
            DistributionPointName dpn = dp.getDistributionPoint();
            // Look for URIs in fullName
            if (dpn != null) {
                if (dpn.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                    // Look for an URI
                    for (int j = 0; j < genNames.length; j++) {
                        if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                            String url = DERIA5String.getInstance(genNames[j].getName()).getString();
                            crlUrls.add(url);
                        }
                    }
                }
            }
        }
    } finally {
        if (oAsnInStream != null)
            oAsnInStream.close();
        if (oAsnInStream2 != null)
            oAsnInStream2.close();
    }
    return crlUrls;
}

From source file:org.jruby.ext.openssl.x509store.X509Utils.java

License:LGPL

/**
 * c: X509_check_issued//w w  w  .ja  va 2s  .c  om
 */
public static int checkIfIssuedBy(X509AuxCertificate issuer, X509AuxCertificate subject) throws Exception {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }

    if (subject.getExtensionValue("2.5.29.35") != null) { //authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence)) {
            key = get(key);
        }

        ASN1Sequence seq = (ASN1Sequence) key;
        AuthorityKeyIdentifier sakid = null;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier
                    .getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }

        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                if (der.getOctets().length > 20) {
                    der = (DEROctetString) get(der.getOctets());
                }
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(der);
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        if (sakid.getAuthorityCertSerialNumber() != null
                && !sakid.getAuthorityCertSerialNumber().equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name nm = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable nameTmp = gens[i].getName();
                    if (nameTmp instanceof X500Name) {
                        nm = (X500Name) nameTmp;
                    } else if (nameTmp instanceof ASN1Sequence) {
                        nm = X500Name.getInstance((ASN1Sequence) nameTmp);
                    } else {
                        throw new RuntimeException("unknown name type in X509Utils: " + nameTmp);
                    }
                    break;
                }
            }
            if (nm != null) {
                if (!(new Name(nm).isEqual(issuer.getIssuerX500Principal()))) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }

    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[0]) { // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[5]) { // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}

From source file:org.keycloak.common.util.CRLUtils.java

License:Apache License

/**
 * Retrieves a list of CRL distribution points from CRLDP v3 certificate extension
 * See <a href="www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-cchain-and-verify-clr-with-bouncy-castle/">CRL validation</a>
 * @param cert/*  ww  w . java2  s  .  c o m*/
 * @return
 * @throws IOException
 */
public static List<String> getCRLDistributionPoints(X509Certificate cert) throws IOException {
    byte[] data = cert.getExtensionValue(CRL_DISTRIBUTION_POINTS_OID);
    if (data == null) {
        return Collections.emptyList();
    }

    List<String> distributionPointUrls = new LinkedList<>();
    DEROctetString octetString;
    try (ASN1InputStream crldpExtensionInputStream = new ASN1InputStream(new ByteArrayInputStream(data))) {
        octetString = (DEROctetString) crldpExtensionInputStream.readObject();
    }
    byte[] octets = octetString.getOctets();

    CRLDistPoint crlDP;
    try (ASN1InputStream crldpInputStream = new ASN1InputStream(new ByteArrayInputStream(octets))) {
        crlDP = CRLDistPoint.getInstance(crldpInputStream.readObject());
    }

    for (DistributionPoint dp : crlDP.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            GeneralName[] names = GeneralNames.getInstance(dpn.getName()).getNames();
            for (GeneralName gn : names) {
                if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = DERIA5String.getInstance(gn.getName()).getString();
                    distributionPointUrls.add(url);
                }
            }
        }
    }

    return distributionPointUrls;
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * Get the authority key identifier from a certificate extensions
 *
 * @param cert certificate containing the extension
 * @return byte[] containing the authority key identifier
 * @throws IOException if extension can not be parsed
 */// w  w w . j  a  v  a  2  s .  com
public static byte[] getAuthorityKeyId(X509Certificate cert) throws IOException {
    byte[] extvalue = cert.getExtensionValue("2.5.29.35");
    if (extvalue == null) {
        return null;
    }
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
            .readObject());
    AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
    return keyId.getKeyIdentifier();
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * Get a certificate policy ID from a certificate policies extension
 *
 * @param cert certificate containing the extension
 * @param pos position of the policy id, if several exist, the first is as pos 0
 * @return String with the certificate policy OID
 * @throws IOException if extension can not be parsed
 *///from   w  w  w  .j a va 2  s .c om
public static String getCertificatePolicyId(X509Certificate cert, int pos) throws IOException {
    byte[] extvalue = cert.getExtensionValue(X509Extensions.CertificatePolicies.getId());
    if (extvalue == null) {
        return null;
    }
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
            .readObject());
    ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()))
            .readObject();

    // Check the size so we don't ArrayIndexOutOfBounds
    if (seq.size() < (pos + 1)) {
        return null;
    }
    PolicyInformation pol = new PolicyInformation((ASN1Sequence) seq.getObjectAt(pos));
    String id = pol.getPolicyIdentifier().getId();
    return id;
}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public AuthorityKeyIdentifier getAuthorityKeyIdentifier(X509Certificate cert) {
    try {/*from  w w w  . ja v  a2 s  . co  m*/
        byte[] value = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
        if (value == null) {
            return null;
        }
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(value))
                .readObject());
        return new AuthorityKeyIdentifier(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to extract AuthorityKeyIdentifier from X509Certificate extensions", ex);
    }
}

From source file:org.signserver.server.ValidityTimeUtils.java

License:Open Source License

private static PrivateKeyUsagePeriod getPrivateKeyUsagePeriod(final X509Certificate cert) throws IOException {
    PrivateKeyUsagePeriod res = null;//from   www .j a v a 2 s .  c  o  m
    final byte[] extvalue = cert.getExtensionValue(PRIVATE_KEY_USAGE_PERIOD.getId());

    if ((extvalue != null) && (extvalue.length > 0)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found a PrivateKeyUsagePeriod in the signer certificate.");
        }
        final DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
                .readObject());

        res = PrivateKeyUsagePeriod.getInstance(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
    }
    return res;
}