001 package org.apache.commons.ssl.asn1;
002
003 import java.io.IOException;
004
005 /** DER BMPString object. */
006 public class DERBMPString
007 extends ASN1Object
008 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 * @throws IllegalArgumentException if the object cannot be converted.
016 */
017 public static DERBMPString getInstance(
018 Object obj) {
019 if (obj == null || obj instanceof DERBMPString) {
020 return (DERBMPString) obj;
021 }
022
023 if (obj instanceof ASN1OctetString) {
024 return new DERBMPString(((ASN1OctetString) obj).getOctets());
025 }
026
027 if (obj instanceof ASN1TaggedObject) {
028 return getInstance(((ASN1TaggedObject) obj).getObject());
029 }
030
031 throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
032 }
033
034 /**
035 * return a BMP 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 * @throws IllegalArgumentException if the tagged object cannot
041 * be converted.
042 */
043 public static DERBMPString getInstance(
044 ASN1TaggedObject obj,
045 boolean explicit) {
046 return getInstance(obj.getObject());
047 }
048
049
050 /** basic constructor - byte encoded string. */
051 public DERBMPString(
052 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 /** basic constructor */
063 public DERBMPString(
064 String string) {
065 this.string = string;
066 }
067
068 public String getString() {
069 return string;
070 }
071
072 public String toString() {
073 return string;
074 }
075
076 public int hashCode() {
077 return this.getString().hashCode();
078 }
079
080 protected boolean asn1Equals(
081 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(
092 DEROutputStream out)
093 throws IOException {
094 char[] c = string.toCharArray();
095 byte[] b = new byte[c.length * 2];
096
097 for (int i = 0; i != c.length; i++) {
098 b[2 * i] = (byte) (c[i] >> 8);
099 b[2 * i + 1] = (byte) c[i];
100 }
101
102 out.writeEncoded(BMP_STRING, b);
103 }
104 }