001: package org.bouncycastle.asn1;
002:
003: import java.io.IOException;
004:
005: /**
006: * DER VisibleString object.
007: */
008: public class DERVisibleString extends ASN1Object implements DERString {
009: String string;
010:
011: /**
012: * return a Visible String from the passed in object.
013: *
014: * @exception IllegalArgumentException if the object cannot be converted.
015: */
016: public static DERVisibleString getInstance(Object obj) {
017: if (obj == null || obj instanceof DERVisibleString) {
018: return (DERVisibleString) obj;
019: }
020:
021: if (obj instanceof ASN1OctetString) {
022: return new DERVisibleString(((ASN1OctetString) obj)
023: .getOctets());
024: }
025:
026: if (obj instanceof ASN1TaggedObject) {
027: return getInstance(((ASN1TaggedObject) obj).getObject());
028: }
029:
030: throw new IllegalArgumentException(
031: "illegal object in getInstance: "
032: + obj.getClass().getName());
033: }
034:
035: /**
036: * return a Visible String from a tagged object.
037: *
038: * @param obj the tagged object holding the object we want
039: * @param explicit true if the object is meant to be explicitly
040: * tagged false otherwise.
041: * @exception IllegalArgumentException if the tagged object cannot
042: * be converted.
043: */
044: public static DERVisibleString getInstance(ASN1TaggedObject obj,
045: boolean explicit) {
046: return getInstance(obj.getObject());
047: }
048:
049: /**
050: * basic constructor - byte encoded string.
051: */
052: public DERVisibleString(byte[] string) {
053: char[] cs = new char[string.length];
054:
055: for (int i = 0; i != cs.length; i++) {
056: cs[i] = (char) (string[i] & 0xff);
057: }
058:
059: this .string = new String(cs);
060: }
061:
062: /**
063: * basic constructor
064: */
065: public DERVisibleString(String string) {
066: this .string = string;
067: }
068:
069: public String getString() {
070: return string;
071: }
072:
073: public String toString() {
074: return string;
075: }
076:
077: public byte[] getOctets() {
078: char[] cs = string.toCharArray();
079: byte[] bs = new byte[cs.length];
080:
081: for (int i = 0; i != cs.length; i++) {
082: bs[i] = (byte) cs[i];
083: }
084:
085: return bs;
086: }
087:
088: void encode(DEROutputStream out) throws IOException {
089: out.writeEncoded(VISIBLE_STRING, this .getOctets());
090: }
091:
092: boolean asn1Equals(DERObject o) {
093: if (!(o instanceof DERVisibleString)) {
094: return false;
095: }
096:
097: return this .getString().equals(
098: ((DERVisibleString) o).getString());
099: }
100:
101: public int hashCode() {
102: return this.getString().hashCode();
103: }
104: }
|