1package org.bouncycastle.asn1.x509; 2 3import java.io.IOException; 4import java.util.Hashtable; 5import java.util.Vector; 6 7import org.bouncycastle.asn1.ASN1Encodable; 8import org.bouncycastle.asn1.ASN1Encoding; 9import org.bouncycastle.asn1.ASN1ObjectIdentifier; 10import org.bouncycastle.asn1.DEROctetString; 11 12/** 13 * Generator for X.509 extensions 14 */ 15public class ExtensionsGenerator 16{ 17 private Hashtable extensions = new Hashtable(); 18 private Vector extOrdering = new Vector(); 19 20 /** 21 * Reset the generator 22 */ 23 public void reset() 24 { 25 extensions = new Hashtable(); 26 extOrdering = new Vector(); 27 } 28 29 /** 30 * Add an extension with the given oid and the passed in value to be included 31 * in the OCTET STRING associated with the extension. 32 * 33 * @param oid OID for the extension. 34 * @param critical true if critical, false otherwise. 35 * @param value the ASN.1 object to be included in the extension. 36 */ 37 public void addExtension( 38 ASN1ObjectIdentifier oid, 39 boolean critical, 40 ASN1Encodable value) 41 throws IOException 42 { 43 this.addExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); 44 } 45 46 /** 47 * Add an extension with the given oid and the passed in byte array to be wrapped in the 48 * OCTET STRING associated with the extension. 49 * 50 * @param oid OID for the extension. 51 * @param critical true if critical, false otherwise. 52 * @param value the byte array to be wrapped. 53 */ 54 public void addExtension( 55 ASN1ObjectIdentifier oid, 56 boolean critical, 57 byte[] value) 58 { 59 if (extensions.containsKey(oid)) 60 { 61 throw new IllegalArgumentException("extension " + oid + " already added"); 62 } 63 64 extOrdering.addElement(oid); 65 extensions.put(oid, new Extension(oid, critical, new DEROctetString(value))); 66 } 67 68 /** 69 * Add a given extension. 70 * 71 * @param extension the full extension value. 72 */ 73 public void addExtension( 74 Extension extension) 75 { 76 if (extensions.containsKey(extension.getExtnId())) 77 { 78 throw new IllegalArgumentException("extension " + extension.getExtnId() + " already added"); 79 } 80 81 extOrdering.addElement(extension.getExtnId()); 82 extensions.put(extension.getExtnId(), extension); 83 } 84 85 /** 86 * Return true if there are no extension present in this generator. 87 * 88 * @return true if empty, false otherwise 89 */ 90 public boolean isEmpty() 91 { 92 return extOrdering.isEmpty(); 93 } 94 95 /** 96 * Generate an Extensions object based on the current state of the generator. 97 * 98 * @return an X09Extensions object. 99 */ 100 public Extensions generate() 101 { 102 Extension[] exts = new Extension[extOrdering.size()]; 103 104 for (int i = 0; i != extOrdering.size(); i++) 105 { 106 exts[i] = (Extension)extensions.get(extOrdering.elementAt(i)); 107 } 108 109 return new Extensions(exts); 110 } 111} 112