KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > util > cert > PrintableStringEntryConverter


1 package org.ejbca.util.cert;
2
3 import java.io.IOException JavaDoc;
4
5 import org.bouncycastle.asn1.DERBMPString;
6 import org.bouncycastle.asn1.DERIA5String;
7 import org.bouncycastle.asn1.DERObject;
8 import org.bouncycastle.asn1.DERObjectIdentifier;
9 import org.bouncycastle.asn1.DERPrintableString;
10 import org.bouncycastle.asn1.DERUTF8String;
11 import org.bouncycastle.asn1.x509.X509Name;
12 import org.bouncycastle.asn1.x509.X509NameEntryConverter;
13
14 /**
15  * A converter for X509 DN entries that uses PrintableString where possible.
16  * Default encoding is UTF-8, so this one is used when the default encoding is not desired.
17  */

18 public class PrintableStringEntryConverter
19     extends X509NameEntryConverter
20 {
21     
22     /**
23      * return true if the passed in String can be represented without
24      * loss as a UTF8String, false otherwise.
25      */

26     private boolean canBeUTF8(
27         String JavaDoc str)
28     {
29         for (int i = str.length() - 1; i >= 0; i--)
30         {
31             if (str.charAt(i) > 0x00ff)
32             {
33                 return false;
34             }
35         }
36
37         return true;
38     }
39     
40     /**
41      * Apply default coversion for the given value depending on the oid
42      * and the character range of the value.
43      *
44      * @param oid the object identifier for the DN entry
45      * @param value the value associated with it
46      * @return the ASN.1 equivalent for the string value.
47      */

48     public DERObject getConvertedValue(
49         DERObjectIdentifier oid,
50         String JavaDoc value)
51     {
52         if (value.length() != 0 && value.charAt(0) == '#')
53         {
54             try
55             {
56                 return convertHexEncoded(value, 1);
57             }
58             catch (IOException JavaDoc e)
59             {
60                 throw new RuntimeException JavaDoc("can't recode value for oid " + oid.getId());
61             }
62         }
63         else if (oid.equals(X509Name.EmailAddress) || oid.equals(X509Name.DC))
64         {
65             return new DERIA5String(value);
66         }
67         else if (canBePrintable(value))
68         {
69             return new DERPrintableString(value);
70         }
71         else if (canBeUTF8(value))
72         {
73             return new DERUTF8String(value);
74         }
75
76         return new DERBMPString(value);
77     }
78 }
79
Popular Tags