Example usage for org.bouncycastle.asn1 ASN1Sequence getObjectAt

List of usage examples for org.bouncycastle.asn1 ASN1Sequence getObjectAt

Introduction

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

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java

License:Open Source License

private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception {
    final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size()
            + certInfo.commonNames.size();
    assertEquals(expectedCount, subjAltNames.getNames().length);
    Collections.sort(certInfo.dnsNames);
    Collections.sort(certInfo.ipAddresses);
    for (GeneralName generalName : subjAltNames.getNames()) {
        if (generalName.getTagNo() == GeneralName.dNSName) {
            String dns = ((ASN1String) generalName.getName()).getString();
            assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals));
        } else if (generalName.getTagNo() == GeneralName.iPAddress) {
            byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets();
            String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes));
            assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals));
        } else if (generalName.getTagNo() == GeneralName.otherName) {
            ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName());
            assertThat(seq.size(), equalTo(2));
            assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class));
            assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID));
            assertThat(seq.getObjectAt(1), instanceOf(DERTaggedObject.class));
            DERTaggedObject taggedName = (DERTaggedObject) seq.getObjectAt(1);
            assertThat(taggedName.getTagNo(), equalTo(0));
            assertThat(taggedName.getObject(), instanceOf(ASN1String.class));
            assertThat(taggedName.getObject().toString(), Matchers.isIn(certInfo.commonNames));
        } else {//w  ww .  j  av  a 2  s.c om
            fail("unknown general name with tag " + generalName.getTagNo());
        }
    }
}

From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java

License:Open Source License

private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception {
    final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size()
            + certInfo.commonNames.size();
    assertEquals(expectedCount, subjAltNames.getNames().length);
    Collections.sort(certInfo.dnsNames);
    Collections.sort(certInfo.ipAddresses);
    for (GeneralName generalName : subjAltNames.getNames()) {
        if (generalName.getTagNo() == GeneralName.dNSName) {
            String dns = ((ASN1String) generalName.getName()).getString();
            assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals));
        } else if (generalName.getTagNo() == GeneralName.iPAddress) {
            byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets();
            String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes));
            assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals));
        } else if (generalName.getTagNo() == GeneralName.otherName) {
            ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName());
            assertThat(seq.size(), equalTo(2));
            assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class));
            assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID));
            assertThat(seq.getObjectAt(1), instanceOf(ASN1TaggedObject.class));
            ASN1TaggedObject tagged = (ASN1TaggedObject) seq.getObjectAt(1);
            assertThat(tagged.getObject(), instanceOf(ASN1String.class));
            assertThat(tagged.getObject().toString(), Matchers.isIn(certInfo.commonNames));
        } else {// w  w  w .  j a  v  a 2s.co m
            fail("unknown general name with tag " + generalName.getTagNo());
        }
    }
}

From source file:org.fdroid.enigtext.crypto.IdentityKeyUtil.java

License:Open Source License

public static IdentityKey verifySignedKeyExchange(byte[] keyExchangeBytes) throws InvalidKeyException {
    try {//from w ww  . j  a v a 2  s  . co  m
        byte[] messageBytes = new byte[1 + PublicKey.KEY_SIZE];
        System.arraycopy(keyExchangeBytes, 0, messageBytes, 0, messageBytes.length);

        byte[] publicKeyBytes = new byte[IdentityKey.SIZE];
        System.arraycopy(keyExchangeBytes, messageBytes.length, publicKeyBytes, 0, publicKeyBytes.length);

        int signatureLength = Conversions.byteArrayToShort(keyExchangeBytes,
                messageBytes.length + publicKeyBytes.length);
        byte[] signatureBytes = new byte[signatureLength];
        System.arraycopy(keyExchangeBytes, messageBytes.length + publicKeyBytes.length + 2, signatureBytes, 0,
                signatureBytes.length);

        byte[] messageHash = getMessageHash(messageBytes, publicKeyBytes);
        IdentityKey identityKey = new IdentityKey(publicKeyBytes, 0);
        ECDSASigner verifier = new ECDSASigner();

        verifier.init(false, identityKey.getPublicKeyParameters());

        ASN1Sequence sequence = (ASN1Sequence) ASN1Object.fromByteArray(signatureBytes);
        BigInteger[] signatureIntegers = new BigInteger[] { ((DERInteger) sequence.getObjectAt(0)).getValue(),
                ((DERInteger) sequence.getObjectAt(1)).getValue() };

        if (!verifier.verifySignature(messageHash, signatureIntegers[0], signatureIntegers[1]))
            throw new InvalidKeyException("Invalid signature!");
        else
            return identityKey;

    } catch (IOException ioe) {
        throw new InvalidKeyException(ioe);
    }

}

From source file:org.glite.authz.pep.pip.provider.ExtractorX509GenericPIP.java

License:Apache License

/**
 * Gets the policy OIDs from a {@link X509Certificate} and returns a list of
 * policy OIds in String object format./*from   ww  w . jav  a 2 s.com*/
 * 
 * @param cert
 *            The x509Certificate where the Policy OID(s) are extracted
 *            from.
 * @return a List of String instance. The list is filled with Policy OIDs
 *         strings.
 * 
 * @throws IOException
 *             Thrown when readObject method does not work.
 */
@SuppressWarnings("resource") // Added to supres errors that are not useful
protected List<String> getPolicyOIDs(X509Certificate cert) throws IOException {
    List<String> oidList = new LazyList<String>();

    String certPolicies = null;
    try {
        Class<?> extension = Class.forName("org.bouncycastle.asn1.x509.Extension");
        //          java.lang.reflect.Field field = extension.getField("certificatePolicies");
        //          Object fieldvalue = field.get(extension);
        //          certPolicies = ((org.bouncycastle.asn1.ASN1ObjectIdentifier)fieldvalue).toString();
        certPolicies = extension.getField("certificatePolicies").get(extension).toString();
    } catch (Exception e) { // NoSuchFieldException or ClassNotFoundException
        certPolicies = org.bouncycastle.asn1.x509.X509Extension.certificatePolicies.toString();
    }
    byte[] extvalue = cert.getExtensionValue(certPolicies);

    if (extvalue == null) {
        log.warn("No valid certificate policies found!");
        return null;
    }

    // Convert extension blob into DER octet string
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
            .readObject());
    // ANS1 sequence generated from the DER octet string
    ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()))
            .readObject();

    /* Loop over all policy OIDs */
    for (int pos = 0; pos < seq.size(); pos++) {
        if (PolicyInformation.getInstance(seq.getObjectAt(pos)).getPolicyIdentifier().getId() != null) {
            oidList.add(PolicyInformation.getInstance(seq.getObjectAt(pos)).getPolicyIdentifier().getId());
        } else {
            throw new IOException("Policy does not exist!");
        }
    }

    return oidList;
}

From source file:org.glite.security.util.proxy.ProxyCertificateGenerator.java

License:Apache License

/**
 * Guesses the value of the CN based on the basename DN. See generateDN for the logic.
 * /*  ww  w  .j a  v a 2  s.com*/
 * @param basename the DN to use as the base of the guessing.
 * @param addLimited whether the new proxy will be limited or not in case the guess is olds style proxy.
 * @return the new CN string.
 */
private String guessCN(X509Name basename, boolean addLimited) {
    String newCN;
    ASN1Sequence subjectSequence = (ASN1Sequence) basename.getDERObject();
    int rdns = subjectSequence.size();
    DERSet rdn = (DERSet) subjectSequence.getObjectAt(rdns - 1);
    DERSequence rdnSequence = (DERSequence) rdn.getObjectAt(0);
    DERObjectIdentifier oid = (DERObjectIdentifier) rdnSequence.getObjectAt(0);
    if (oid.equals(X509Name.CN)) {
        String cn = rdnSequence.getObjectAt(1).toString();
        if (cn.equals("proxy")) { // old style unlimited proxy
            if (addLimited) { // new proxy will be limited
                newCN = "limited proxy";
            } else { // new proxy will still be unlimited
                newCN = "proxy";
            }
        } else {
            if (cn.equals("limited proxy")) { // in case the proxy is old
                // style limited proxy, new
                // one will be old style
                // limited too
                newCN = "limited proxy";
            } else { // otherwise generate new random number to use as CN.
                newCN = getSerialNumber().toString();
            }
        }
    } else { // in case the DN doesn't end with a CN, assume new style proxy
        newCN = getSerialNumber().toString();
    }
    return newCN;
}

From source file:org.glite.security.util.proxy.ProxyCertInfoExtension.java

License:Apache License

/**
 * Read a proxyCertInfoExtension from the ASN1 sequence.
 * //  w  w w  .  j  a  v a 2s .c  o m
 * @param seq The sequence containing the extension.
 */
public ProxyCertInfoExtension(ASN1Sequence seq) {
    int index = 0;
    if (seq != null && seq.size() > 0) {
        if (seq.getObjectAt(0) instanceof DERInteger) {
            m_pathLen = ((DERInteger) seq.getObjectAt(0)).getValue().intValue();
            index = 1;
        }
        if (seq.size() <= index) {
            throw new IllegalArgumentException(
                    "ProxyCertInfoExtension parser error, expected policy, but it was not found");
        }
        if (seq.getObjectAt(index) instanceof DERSequence) {
            m_policy = new ProxyPolicy((ASN1Sequence) seq.getObjectAt(index));
        } else {
            throw new IllegalArgumentException(
                    "ProxyCertInfoExtension parser error, expected policy sequence, but got: "
                            + seq.getObjectAt(index).getClass());
        }
        index++;
        if (seq.size() > index) {
            throw new IllegalArgumentException(
                    "ProxyCertInfoExtension parser error, sequence contains too many items");
        }
    }
}

From source file:org.glite.security.util.proxy.ProxyPolicy.java

License:Apache License

/**
 * Read a new proxy policy object from the ASN1 sequence.
 * /* w  ww  .  j a  v a  2s  .  c o m*/
 * @param seq The proxy policy ASN1 sequence.
 */
public ProxyPolicy(ASN1Sequence seq) {
    if (seq != null && seq.size() > 0) {
        if (seq.getObjectAt(0) instanceof DERObjectIdentifier) {
            m_oid = seq.getObjectAt(0).toString();
        } else {
            throw new IllegalArgumentException("ProxyPolicy parser error, expected object identifier, but got:"
                    + seq.getObjectAt(0).getClass());
        }
    } else {
        throw new IllegalArgumentException(
                "ProxyPolicy parser error, expected nonempty sequence, but not no sequence or an empty sequence");
    }
    if (seq.size() > 1) {
        if (seq.getObjectAt(1) instanceof DEROctetString) {
            this.m_policy = (ASN1OctetString) seq.getObjectAt(1);
        } else {
            throw new IllegalArgumentException(
                    "ProxyPolicy parser error, expected octetstring but got: " + seq.getObjectAt(1).getClass());
        }
    }
    if (seq.size() > 2) {
        throw new IllegalArgumentException(
                "ProxyPolicy parser error, proxy policy can only have two items, got: " + seq.size()
                        + "items.");
    }

}

From source file:org.glite.security.util.proxy.ProxyRestrictionData.java

License:Apache License

/**
 * Parses the restriction data from byte array.
 * /*from w  w  w  .java2 s . co  m*/
 * @param bytes The byte array to parse.
 * @throws IOException In case there is a problem parsing the structure.
 */
public ProxyRestrictionData(byte[] bytes) throws IOException {
    ASN1Sequence nameSpaceRestrictionsSeq = (ASN1Sequence) ASN1Object.fromByteArray(bytes);
    switch (nameSpaceRestrictionsSeq.size()) {
    case 0:
        return;
    case 1:
        DERTaggedObject taggedSequence = (DERTaggedObject) nameSpaceRestrictionsSeq.getObjectAt(0);
        if (taggedSequence.getTagNo() == 0) {
            copyCondSequenceToVector((DERSequence) taggedSequence.getObject(), m_permittedGeneralSubtrees);
        } else {
            if (taggedSequence.getTagNo() == 1) {
                copyCondSequenceToVector((DERSequence) taggedSequence.getObject(), m_excludedGeneralSubtrees);
            } else {
                LOGGER.error("Illegal tag number in the proxy restriction NameConstraints data structure: "
                        + taggedSequence.getTagNo() + ", should have been 0 or 1");
                throw new IllegalArgumentException(
                        "Illegal tag number in the proxy restriction NameConstraints data structure: "
                                + taggedSequence.getTagNo() + ", should have been 0 or 1");
            }
        }
        break;
    case 2:
        taggedSequence = (DERTaggedObject) nameSpaceRestrictionsSeq.getObjectAt(0);
        if (taggedSequence.getTagNo() == 0) {
            copyCondSequenceToVector((DERSequence) taggedSequence.getObject(), m_permittedGeneralSubtrees);
        } else {
            LOGGER.error("Illegal tag number in the proxy restriction NameConstraints data structure: "
                    + taggedSequence.getTagNo() + ", should have been 0");
            throw new IllegalArgumentException(
                    "Illegal tag number in the proxy restriction NameConstraints data structure: "
                            + taggedSequence.getTagNo() + ", should have been 0");
        }
        taggedSequence = (DERTaggedObject) nameSpaceRestrictionsSeq.getObjectAt(1);
        if (taggedSequence.getTagNo() == 1) {
            copyCondSequenceToVector((DERSequence) taggedSequence.getObject(), m_excludedGeneralSubtrees);
        } else {
            LOGGER.error("Illegal tag number in the proxy restriction NameConstraints data structure: "
                    + taggedSequence.getTagNo() + ", should have been 1");
            throw new IllegalArgumentException(
                    "Illegal tag number in the proxy restriction NameConstraints data structure: "
                            + taggedSequence.getTagNo() + ", should have been 1");
        }
        break;
    default:
        LOGGER.error("Illegal number of items in the proxy restriction NameConstraints data structure: "
                + nameSpaceRestrictionsSeq.size() + ", should have been 0 to 2");
        throw new IllegalArgumentException(
                "Illegal number of items in the proxy restriction NameConstraints data structure: "
                        + nameSpaceRestrictionsSeq.size() + ", should have been 0 to 2");
    }
}

From source file:org.glite.voms.ac.ACCerts.java

License:Open Source License

/**
 * Creates an ACCerts starting from a sequence.
 *
 * @param seq the Sequence./*from  w w  w.j av a  2  s. com*/
 *
 * @throws IllegalArgumentException if Certificates are not supported
 * or if there is an encoding error.
 */
public ACCerts(ASN1Sequence seq) {
    l = new Vector();
    seq = (ASN1Sequence) seq.getObjectAt(0);
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X.509", "BC");
    } catch (NoSuchProviderException e) {
        throw new ExceptionInInitializerError("Cannot find BouncyCastle provider: " + e.getMessage());
    } catch (CertificateException e) {
        throw new ExceptionInInitializerError("X.509 Certificates unsupported. " + e.getMessage());
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error in setting up ACCerts reader. " + ex.getMessage());
    }

    for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
        Object o = e.nextElement();
        //            System.out.println("O CLASS: " + o.getClass());
        if (o instanceof DLSequence) {
            ASN1Sequence s = ASN1Sequence.getInstance(o);
            byte[] data = null;
            try {
                data = new X509CertificateObject(Certificate.getInstance(s)).getEncoded();
                l.add((X509Certificate) cf.generateCertificate(new ByteArrayInputStream(data)));
                //                      X509CertificateObject obj  = null;
                //                      obj = new X509CertificateObject(X509CertificateStructure.getInstance(s));
                //                      l.add(obj);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Error in encoding ACCerts. " + ex.getMessage());
            }

            //X509CertificateStructure.getInstance(s));
        } else
            throw new IllegalArgumentException("Incorrect encoding for ACCerts");
    }
}

From source file:org.glite.voms.ac.AttributeCertificate.java

License:eu-egee.org license

public AttributeCertificate(ASN1Sequence seq) throws IOException {
    signedObj = ((ASN1Sequence) seq.getObjectAt(0)).toASN1Primitive();
    acInfo = new AttributeCertificateInfo((ASN1Sequence) seq.getObjectAt(0));
    signatureAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
    signatureValue = (DERBitString) seq.getObjectAt(2);
}