1package org.bouncycastle.asn1.x509;
2
3import java.util.Enumeration;
4import java.util.Vector;
5
6import org.bouncycastle.asn1.ASN1Encodable;
7import org.bouncycastle.asn1.ASN1EncodableVector;
8import org.bouncycastle.asn1.ASN1Sequence;
9import org.bouncycastle.asn1.ASN1TaggedObject;
10import org.bouncycastle.asn1.DERObject;
11import org.bouncycastle.asn1.DERSequence;
12import org.bouncycastle.asn1.DERTaggedObject;
13
14public class NameConstraints
15    extends ASN1Encodable
16{
17    private ASN1Sequence permitted, excluded;
18
19    public NameConstraints(ASN1Sequence seq)
20    {
21        Enumeration e = seq.getObjects();
22        while (e.hasMoreElements())
23        {
24            ASN1TaggedObject o = ASN1TaggedObject.getInstance(e.nextElement());
25            switch (o.getTagNo())
26            {
27            case 0:
28                permitted = ASN1Sequence.getInstance(o, false);
29                break;
30            case 1:
31                excluded = ASN1Sequence.getInstance(o, false);
32                break;
33            }
34        }
35    }
36
37    /**
38     * Constructor from a given details.
39     *
40     * <p>
41     * permitted and excluded are Vectors of GeneralSubtree objects.
42     *
43     * @param permitted
44     *            Permitted subtrees
45     * @param excluded
46     *            Excludes subtrees
47     */
48    public NameConstraints(
49        Vector permitted,
50        Vector excluded)
51    {
52        if (permitted != null)
53        {
54            this.permitted = createSequence(permitted);
55        }
56        if (excluded != null)
57        {
58            this.excluded = createSequence(excluded);
59        }
60    }
61
62    private DERSequence createSequence(Vector subtree)
63    {
64        ASN1EncodableVector vec = new ASN1EncodableVector();
65        Enumeration e = subtree.elements();
66        while (e.hasMoreElements())
67        {
68            vec.add((GeneralSubtree)e.nextElement());
69        }
70
71        return new DERSequence(vec);
72    }
73
74    public ASN1Sequence getPermittedSubtrees()
75    {
76        return permitted;
77    }
78
79    public ASN1Sequence getExcludedSubtrees()
80    {
81        return excluded;
82    }
83
84    /*
85     * NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees
86     * OPTIONAL, excludedSubtrees [1] GeneralSubtrees OPTIONAL }
87     */
88    public DERObject toASN1Object()
89    {
90        ASN1EncodableVector v = new ASN1EncodableVector();
91
92        if (permitted != null)
93        {
94            v.add(new DERTaggedObject(false, 0, permitted));
95        }
96
97        if (excluded != null)
98        {
99            v.add(new DERTaggedObject(false, 1, excluded));
100        }
101
102        return new DERSequence(v);
103    }
104}
105