001: package org.bouncycastle.asn1;
002:
003: import java.io.ByteArrayOutputStream;
004: import java.io.IOException;
005:
006: /**
007: * DER UniversalString object.
008: */
009: public class DERUniversalString extends ASN1Object implements DERString {
010: private static final char[] table = { '0', '1', '2', '3', '4', '5',
011: '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
012: private byte[] string;
013:
014: /**
015: * return a Universal String from the passed in object.
016: *
017: * @exception IllegalArgumentException if the object cannot be converted.
018: */
019: public static DERUniversalString getInstance(Object obj) {
020: if (obj == null || obj instanceof DERUniversalString) {
021: return (DERUniversalString) obj;
022: }
023:
024: if (obj instanceof ASN1OctetString) {
025: return new DERUniversalString(((ASN1OctetString) obj)
026: .getOctets());
027: }
028:
029: throw new IllegalArgumentException(
030: "illegal object in getInstance: "
031: + obj.getClass().getName());
032: }
033:
034: /**
035: * return a Universal String from a tagged object.
036: *
037: * @param obj the tagged object holding the object we want
038: * @param explicit true if the object is meant to be explicitly
039: * tagged false otherwise.
040: * @exception IllegalArgumentException if the tagged object cannot
041: * be converted.
042: */
043: public static DERUniversalString getInstance(ASN1TaggedObject obj,
044: boolean explicit) {
045: return getInstance(obj.getObject());
046: }
047:
048: /**
049: * basic constructor - byte encoded string.
050: */
051: public DERUniversalString(byte[] string) {
052: this .string = string;
053: }
054:
055: public String getString() {
056: StringBuffer buf = new StringBuffer("#");
057: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
058: ASN1OutputStream aOut = new ASN1OutputStream(bOut);
059:
060: try {
061: aOut.writeObject(this );
062: } catch (IOException e) {
063: throw new RuntimeException(
064: "internal error encoding BitString");
065: }
066:
067: byte[] string = bOut.toByteArray();
068:
069: for (int i = 0; i != string.length; i++) {
070: buf.append(table[(string[i] >>> 4) & 0xf]);
071: buf.append(table[string[i] & 0xf]);
072: }
073:
074: return buf.toString();
075: }
076:
077: public String toString() {
078: return getString();
079: }
080:
081: public byte[] getOctets() {
082: return string;
083: }
084:
085: void encode(DEROutputStream out) throws IOException {
086: out.writeEncoded(UNIVERSAL_STRING, this .getOctets());
087: }
088:
089: boolean asn1Equals(DERObject o) {
090: if (!(o instanceof DERUniversalString)) {
091: return false;
092: }
093:
094: return this .getString().equals(
095: ((DERUniversalString) o).getString());
096: }
097:
098: public int hashCode() {
099: return this.getString().hashCode();
100: }
101: }
|