001: package org.bouncycastle.asn1;
002:
003: import java.io.IOException;
004:
005: /**
006: * DER BMPString object.
007: */
008: public class DERBMPString extends ASN1Object implements DERString {
009: String string;
010:
011: /**
012: * return a BMP String from the given object.
013: *
014: * @param obj the object we want converted.
015: * @exception IllegalArgumentException if the object cannot be converted.
016: */
017: public static DERBMPString getInstance(Object obj) {
018: if (obj == null || obj instanceof DERBMPString) {
019: return (DERBMPString) obj;
020: }
021:
022: if (obj instanceof ASN1OctetString) {
023: return new DERBMPString(((ASN1OctetString) obj).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 BMP 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 DERBMPString getInstance(ASN1TaggedObject obj,
045: boolean explicit) {
046: return getInstance(obj.getObject());
047: }
048:
049: /**
050: * basic constructor - byte encoded string.
051: */
052: public DERBMPString(byte[] string) {
053: char[] cs = new char[string.length / 2];
054:
055: for (int i = 0; i != cs.length; i++) {
056: cs[i] = (char) ((string[2 * i] << 8) | (string[2 * i + 1] & 0xff));
057: }
058:
059: this .string = new String(cs);
060: }
061:
062: /**
063: * basic constructor
064: */
065: public DERBMPString(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 int hashCode() {
078: return this .getString().hashCode();
079: }
080:
081: protected boolean asn1Equals(DERObject o) {
082: if (!(o instanceof DERBMPString)) {
083: return false;
084: }
085:
086: DERBMPString s = (DERBMPString) o;
087:
088: return this .getString().equals(s.getString());
089: }
090:
091: void encode(DEROutputStream out) throws IOException {
092: char[] c = string.toCharArray();
093: byte[] b = new byte[c.length * 2];
094:
095: for (int i = 0; i != c.length; i++) {
096: b[2 * i] = (byte) (c[i] >> 8);
097: b[2 * i + 1] = (byte) c[i];
098: }
099:
100: out.writeEncoded(BMP_STRING, b);
101: }
102: }
|