1 19 20 package com.maverick.crypto.asn1; 21 22 import java.io.ByteArrayOutputStream ; 23 import java.io.IOException ; 24 25 28 public class DERUTF8String 29 extends DERObject 30 implements DERString 31 { 32 String string; 33 34 39 public static DERUTF8String getInstance( 40 Object obj) 41 { 42 if (obj == null || obj instanceof DERUTF8String) 43 { 44 return (DERUTF8String)obj; 45 } 46 47 if (obj instanceof ASN1OctetString) 48 { 49 return new DERUTF8String(((ASN1OctetString)obj).getOctets()); 50 } 51 52 if (obj instanceof ASN1TaggedObject) 53 { 54 return getInstance(((ASN1TaggedObject)obj).getObject()); 55 } 56 57 throw new IllegalArgumentException ("illegal object in getInstance: " + obj.getClass().getName()); 58 } 59 60 69 public static DERUTF8String getInstance( 70 ASN1TaggedObject obj, 71 boolean explicit) 72 { 73 return getInstance(obj.getObject()); 74 } 75 76 79 DERUTF8String( 80 byte[] string) 81 { 82 int i = 0; 83 int length = 0; 84 85 while (i < string.length) 86 { 87 length++; 88 if ((string[i] & 0xe0) == 0xe0) 89 { 90 i += 3; 91 } 92 else if ((string[i] & 0xc0) == 0xc0) 93 { 94 i += 2; 95 } 96 else 97 { 98 i += 1; 99 } 100 } 101 102 char[] cs = new char[length]; 103 104 i = 0; 105 length = 0; 106 107 while (i < string.length) 108 { 109 char ch; 110 111 if ((string[i] & 0xe0) == 0xe0) 112 { 113 ch = (char)(((string[i] & 0x1f) << 12) 114 | ((string[i + 1] & 0x3f) << 6) | (string[i + 2] & 0x3f)); 115 i += 3; 116 } 117 else if ((string[i] & 0xc0) == 0xc0) 118 { 119 ch = (char)(((string[i] & 0x3f) << 6) | (string[i + 1] & 0x3f)); 120 i += 2; 121 } 122 else 123 { 124 ch = (char)(string[i] & 0xff); 125 i += 1; 126 } 127 128 cs[length++] = ch; 129 } 130 131 this.string = new String (cs); 132 } 133 134 137 public DERUTF8String( 138 String string) 139 { 140 this.string = string; 141 } 142 143 public String getString() 144 { 145 return string; 146 } 147 148 public int hashCode() 149 { 150 return this.getString().hashCode(); 151 } 152 153 public boolean equals( 154 Object o) 155 { 156 if (!(o instanceof DERUTF8String)) 157 { 158 return false; 159 } 160 161 DERUTF8String s = (DERUTF8String)o; 162 163 return this.getString().equals(s.getString()); 164 } 165 166 void encode( 167 DEROutputStream out) 168 throws IOException 169 { 170 char[] c = string.toCharArray(); 171 ByteArrayOutputStream bOut = new ByteArrayOutputStream (); 172 173 for (int i = 0; i != c.length; i++) 174 { 175 char ch = c[i]; 176 177 if (ch < 0x0080) 178 { 179 bOut.write(ch); 180 } 181 else if (ch < 0x0800) 182 { 183 bOut.write(0xc0 | (ch >> 6)); 184 bOut.write(0x80 | (ch & 0x3f)); 185 } 186 else 187 { 188 bOut.write(0xe0 | (ch >> 12)); 189 bOut.write(0x80 | ((ch >> 6) & 0x3F)); 190 bOut.write(0x80 | (ch & 0x3F)); 191 } 192 } 193 194 out.writeEncoded(UTF8_STRING, bOut.toByteArray()); 195 } 196 } 197 | Popular Tags |