1 package org.bouncycastle.asn1.x509; 2 3 import java.util.Enumeration; 4 5 import org.bouncycastle.asn1.ASN1EncodableVector; 6 import org.bouncycastle.asn1.ASN1Object; 7 import org.bouncycastle.asn1.ASN1Primitive; 8 import org.bouncycastle.asn1.ASN1Sequence; 9 import org.bouncycastle.asn1.ASN1TaggedObject; 10 import org.bouncycastle.asn1.DERSequence; 11 import org.bouncycastle.asn1.DERTaggedObject; 12 13 public class NameConstraints 14 extends ASN1Object 15 { 16 private GeneralSubtree[] permitted, excluded; 17 18 public static NameConstraints getInstance(Object obj) 19 { 20 if (obj instanceof NameConstraints) 21 { 22 return (NameConstraints)obj; 23 } 24 if (obj != null) 25 { 26 return new NameConstraints(ASN1Sequence.getInstance(obj)); 27 } 28 29 return null; 30 } 31 32 private NameConstraints(ASN1Sequence seq) 33 { 34 Enumeration e = seq.getObjects(); 35 while (e.hasMoreElements()) 36 { 37 ASN1TaggedObject o = ASN1TaggedObject.getInstance(e.nextElement()); 38 switch (o.getTagNo()) 39 { 40 case 0: 41 permitted = createArray(ASN1Sequence.getInstance(o, false)); 42 break; 43 case 1: 44 excluded = createArray(ASN1Sequence.getInstance(o, false)); 45 break; 46 default: 47 throw new IllegalArgumentException("Unknown tag encountered: " + o.getTagNo()); 48 } 49 } 50 } 51 52 /** 53 * Constructor from a given details. 54 * 55 * <p> 56 * permitted and excluded are arrays of GeneralSubtree objects. 57 * 58 * @param permitted 59 * Permitted subtrees 60 * @param excluded 61 * Excludes subtrees 62 */ 63 public NameConstraints( 64 GeneralSubtree[] permitted, 65 GeneralSubtree[] excluded) 66 { 67 this.permitted = cloneSubtree(permitted); 68 this.excluded = cloneSubtree(excluded); 69 } 70 71 private GeneralSubtree[] createArray(ASN1Sequence subtree) 72 { 73 GeneralSubtree[] ar = new GeneralSubtree[subtree.size()]; 74 75 for (int i = 0; i != ar.length; i++) 76 { 77 ar[i] = GeneralSubtree.getInstance(subtree.getObjectAt(i)); 78 } 79 80 return ar; 81 } 82 83 public GeneralSubtree[] getPermittedSubtrees() 84 { 85 return cloneSubtree(permitted); 86 } 87 88 public GeneralSubtree[] getExcludedSubtrees() 89 { 90 return cloneSubtree(excluded); 91 } 92 93 /* 94 * NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees 95 * OPTIONAL, excludedSubtrees [1] GeneralSubtrees OPTIONAL } 96 */ 97 public ASN1Primitive toASN1Primitive() 98 { 99 ASN1EncodableVector v = new ASN1EncodableVector(); 100 101 if (permitted != null) 102 { 103 v.add(new DERTaggedObject(false, 0, new DERSequence(permitted))); 104 } 105 106 if (excluded != null) 107 { 108 v.add(new DERTaggedObject(false, 1, new DERSequence(excluded))); 109 } 110 111 return new DERSequence(v); 112 } 113 114 private static GeneralSubtree[] cloneSubtree(GeneralSubtree[] subtrees) 115 { 116 if (subtrees != null) 117 { 118 GeneralSubtree[] rv = new GeneralSubtree[subtrees.length]; 119 120 System.arraycopy(subtrees, 0, rv, 0, rv.length); 121 122 return rv; 123 } 124 125 return null; 126 } 127 } 128