Source Code Cross Referenced for AVA.java in  » 6.0-JDK-Modules-sun » security » sun » security » x509 » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules sun » security » sun.security.x509 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
0003:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004:         *
0005:         * This code is free software; you can redistribute it and/or modify it
0006:         * under the terms of the GNU General Public License version 2 only, as
0007:         * published by the Free Software Foundation.  Sun designates this
0008:         * particular file as subject to the "Classpath" exception as provided
0009:         * by Sun in the LICENSE file that accompanied this code.
0010:         *
0011:         * This code is distributed in the hope that it will be useful, but WITHOUT
0012:         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013:         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
0014:         * version 2 for more details (a copy is included in the LICENSE file that
0015:         * accompanied this code).
0016:         *
0017:         * You should have received a copy of the GNU General Public License version
0018:         * 2 along with this work; if not, write to the Free Software Foundation,
0019:         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020:         *
0021:         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022:         * CA 95054 USA or visit www.sun.com if you need additional information or
0023:         * have any questions.
0024:         */
0025:
0026:        package sun.security.x509;
0027:
0028:        import java.io.ByteArrayOutputStream;
0029:        import java.io.IOException;
0030:        import java.io.OutputStream;
0031:        import java.io.Reader;
0032:        import java.security.AccessController;
0033:        import java.text.Normalizer;
0034:        import java.util.*;
0035:
0036:        import sun.security.action.GetBooleanAction;
0037:        import sun.security.util.*;
0038:        import sun.security.pkcs.PKCS9Attribute;
0039:
0040:        /**
0041:         * X.500 Attribute-Value-Assertion (AVA):  an attribute, as identified by
0042:         * some attribute ID, has some particular value.  Values are as a rule ASN.1
0043:         * printable strings.  A conventional set of type IDs is recognized when
0044:         * parsing (and generating) RFC 1779 or RFC 2253 syntax strings.
0045:         *
0046:         * <P>AVAs are components of X.500 relative names.  Think of them as being
0047:         * individual fields of a database record.  The attribute ID is how you
0048:         * identify the field, and the value is part of a particular record.
0049:         * <p>
0050:         * Note that instances of this class are immutable.
0051:         *
0052:         * @see X500Name
0053:         * @see RDN
0054:         *
0055:         * @version 1.58, 05/05/07
0056:         *
0057:         * @author David Brownell
0058:         * @author Amit Kapoor
0059:         * @author Hemma Prafullchandra
0060:         */
0061:        public class AVA implements  DerEncoder {
0062:
0063:            private static final Debug debug = Debug.getInstance("x509",
0064:                    "\t[AVA]");
0065:            // See CR 6391482: if enabled this flag preserves the old but incorrect
0066:            // PrintableString encoding for DomainComponent. It may need to be set to
0067:            // avoid breaking preexisting certificates generated with sun.security APIs.
0068:            private static final boolean PRESERVE_OLD_DC_ENCODING = AccessController
0069:                    .doPrivileged(new GetBooleanAction(
0070:                            "com.sun.security.preserveOldDCEncoding"));
0071:
0072:            /**
0073:             * DEFAULT format allows both RFC1779 and RFC2253 syntax and
0074:             * additional keywords.
0075:             */
0076:            final static int DEFAULT = 1;
0077:            /**
0078:             * RFC1779 specifies format according to RFC1779.
0079:             */
0080:            final static int RFC1779 = 2;
0081:            /**
0082:             * RFC2253 specifies format according to RFC2253.
0083:             */
0084:            final static int RFC2253 = 3;
0085:
0086:            // currently not private, accessed directly from RDN
0087:            final ObjectIdentifier oid;
0088:            final DerValue value;
0089:
0090:            /*
0091:             * If the value has any of these characters in it, it must be quoted.
0092:             * Backslash and quote characters must also be individually escaped.
0093:             * Leading and trailing spaces, also multiple internal spaces, also
0094:             * call for quoting the whole string.
0095:             */
0096:            private static final String specialChars = ",+=\n<>#;";
0097:
0098:            /*
0099:             * In RFC2253, if the value has any of these characters in it, it
0100:             * must be quoted by a preceding \.
0101:             */
0102:            private static final String specialChars2253 = ",+\"\\<>;";
0103:
0104:            /*
0105:             * includes special chars from RFC1779 and RFC2253, as well as ' '
0106:             */
0107:            private static final String specialCharsAll = ",=\n+<>#;\\\" ";
0108:
0109:            /*
0110:             * Values that aren't printable strings are emitted as BER-encoded
0111:             * hex data.
0112:             */
0113:            private static final String hexDigits = "0123456789ABCDEF";
0114:
0115:            public AVA(ObjectIdentifier type, DerValue val) {
0116:                if ((type == null) || (val == null)) {
0117:                    throw new NullPointerException();
0118:                }
0119:                oid = type;
0120:                value = val;
0121:            }
0122:
0123:            /**
0124:             * Parse an RFC 1779 or RFC 2253 style AVA string:  CN=fee fie foe fum
0125:             * or perhaps with quotes.  Not all defined AVA tags are supported;
0126:             * of current note are X.400 related ones (PRMD, ADMD, etc).
0127:             *
0128:             * This terminates at unescaped AVA separators ("+") or RDN
0129:             * separators (",", ";"), or DN terminators (">"), and removes
0130:             * cosmetic whitespace at the end of values.
0131:             */
0132:            AVA(Reader in) throws IOException {
0133:                this (in, DEFAULT);
0134:            }
0135:
0136:            /**
0137:             * Parse an RFC 1779 or RFC 2253 style AVA string:  CN=fee fie foe fum
0138:             * or perhaps with quotes. Additional keywords can be specified in the
0139:             * keyword/OID map. 
0140:             *
0141:             * This terminates at unescaped AVA separators ("+") or RDN
0142:             * separators (",", ";"), or DN terminators (">"), and removes
0143:             * cosmetic whitespace at the end of values.
0144:             */
0145:            AVA(Reader in, Map<String, String> keywordMap) throws IOException {
0146:                this (in, DEFAULT, keywordMap);
0147:            }
0148:
0149:            /**
0150:             * Parse an AVA string formatted according to format.
0151:             *
0152:             * XXX format RFC1779 should only allow RFC1779 syntax but is
0153:             * actually DEFAULT with RFC1779 keywords.
0154:             */
0155:            AVA(Reader in, int format) throws IOException {
0156:                this (in, format, Collections.<String, String> emptyMap());
0157:            }
0158:
0159:            /**
0160:             * Parse an AVA string formatted according to format. 
0161:             *
0162:             * XXX format RFC1779 should only allow RFC1779 syntax but is
0163:             * actually DEFAULT with RFC1779 keywords.
0164:             *
0165:             * @param in Reader containing AVA String
0166:             * @param format parsing format
0167:             * @param keywordMap a Map where a keyword String maps to a corresponding
0168:             *   OID String. Each AVA keyword will be mapped to the corresponding OID.
0169:             *   If an entry does not exist, it will fallback to the builtin 
0170:             *   keyword/OID mapping.
0171:             * @throws IOException if the AVA String is not valid in the specified 
0172:             *   standard or an OID String from the keywordMap is improperly formatted
0173:             */
0174:            AVA(Reader in, int format, Map<String, String> keywordMap)
0175:                    throws IOException {
0176:                // assume format is one of DEFAULT, RFC1779, RFC2253
0177:
0178:                StringBuilder temp = new StringBuilder();
0179:                int c;
0180:
0181:                /*
0182:                 * First get the keyword indicating the attribute's type,
0183:                 * and map it to the appropriate OID.
0184:                 */
0185:                while (true) {
0186:                    c = readChar(in, "Incorrect AVA format");
0187:                    if (c == '=') {
0188:                        break;
0189:                    }
0190:                    temp.append((char) c);
0191:                }
0192:
0193:                oid = AVAKeyword.getOID(temp.toString(), format, keywordMap);
0194:
0195:                /*
0196:                 * Now parse the value.  "#hex", a quoted string, or a string
0197:                 * terminated by "+", ",", ";", ">".  Whitespace before or after
0198:                 * the value is stripped away unless format is RFC2253.
0199:                 */
0200:                temp.setLength(0);
0201:                if (format == RFC2253) {
0202:                    // read next character
0203:                    c = in.read();
0204:                    if (c == ' ') {
0205:                        throw new IOException("Incorrect AVA RFC2253 format - "
0206:                                + "leading space must be escaped");
0207:                    }
0208:                } else {
0209:                    // read next character skipping whitespace
0210:                    do {
0211:                        c = in.read();
0212:                    } while ((c == ' ') || (c == '\n'));
0213:                }
0214:                if (c == -1) {
0215:                    // empty value
0216:                    value = new DerValue("");
0217:                    return;
0218:                }
0219:
0220:                if (c == '#') {
0221:                    value = parseHexString(in, format);
0222:                } else if ((c == '"') && (format != RFC2253)) {
0223:                    value = parseQuotedString(in, temp);
0224:                } else {
0225:                    value = parseString(in, c, format, temp);
0226:                }
0227:            }
0228:
0229:            /**
0230:             * Get the ObjectIdentifier of this AVA.
0231:             */
0232:            public ObjectIdentifier getObjectIdentifier() {
0233:                return oid;
0234:            }
0235:
0236:            /**
0237:             * Get the value of this AVA as a DerValue.
0238:             */
0239:            public DerValue getDerValue() {
0240:                return value;
0241:            }
0242:
0243:            /**
0244:             * Get the value of this AVA as a String.
0245:             *
0246:             * @exception RuntimeException if we could not obtain the string form
0247:             *    (should not occur)
0248:             */
0249:            public String getValueString() {
0250:                try {
0251:                    String s = value.getAsString();
0252:                    if (s == null) {
0253:                        throw new RuntimeException("AVA string is null");
0254:                    }
0255:                    return s;
0256:                } catch (IOException e) {
0257:                    // should not occur
0258:                    throw new RuntimeException("AVA error: " + e, e);
0259:                }
0260:            }
0261:
0262:            private static DerValue parseHexString(Reader in, int format)
0263:                    throws IOException {
0264:
0265:                int c;
0266:                ByteArrayOutputStream baos = new ByteArrayOutputStream();
0267:                byte b = 0;
0268:                int cNdx = 0;
0269:                while (true) {
0270:                    c = in.read();
0271:
0272:                    if (isTerminator(c, format)) {
0273:                        break;
0274:                    }
0275:
0276:                    int cVal = hexDigits.indexOf(Character
0277:                            .toUpperCase((char) c));
0278:
0279:                    if (cVal == -1) {
0280:                        throw new IOException("AVA parse, invalid hex "
0281:                                + "digit: " + (char) c);
0282:                    }
0283:
0284:                    if ((cNdx % 2) == 1) {
0285:                        b = (byte) ((b * 16) + (byte) (cVal));
0286:                        baos.write(b);
0287:                    } else {
0288:                        b = (byte) (cVal);
0289:                    }
0290:                    cNdx++;
0291:                }
0292:
0293:                // throw exception if no hex digits
0294:                if (cNdx == 0) {
0295:                    throw new IOException("AVA parse, zero hex digits");
0296:                }
0297:
0298:                // throw exception if odd number of hex digits
0299:                if (cNdx % 2 == 1) {
0300:                    throw new IOException("AVA parse, odd number of hex digits");
0301:                }
0302:
0303:                return new DerValue(baos.toByteArray());
0304:            }
0305:
0306:            private DerValue parseQuotedString(Reader in, StringBuilder temp)
0307:                    throws IOException {
0308:
0309:                // RFC1779 specifies that an entire RDN may be enclosed in double 
0310:                // quotes. In this case the syntax is any sequence of 
0311:                // backslash-specialChar, backslash-backslash,
0312:                // backslash-doublequote, or character other than backslash or
0313:                // doublequote.
0314:                int c = readChar(in, "Quoted string did not end in quote");
0315:
0316:                List<Byte> embeddedHex = new ArrayList<Byte>();
0317:                boolean isPrintableString = true;
0318:                while (c != '"') {
0319:                    if (c == '\\') {
0320:                        c = readChar(in, "Quoted string did not end in quote");
0321:
0322:                        // check for embedded hex pairs
0323:                        Byte hexByte = null;
0324:                        if ((hexByte = getEmbeddedHexPair(c, in)) != null) {
0325:
0326:                            // always encode AVAs with embedded hex as UTF8
0327:                            isPrintableString = false;
0328:
0329:                            // append consecutive embedded hex
0330:                            // as single string later
0331:                            embeddedHex.add(hexByte);
0332:                            c = in.read();
0333:                            continue;
0334:                        }
0335:
0336:                        if (c != '\\' && c != '"'
0337:                                && specialChars.indexOf((char) c) < 0) {
0338:                            throw new IOException(
0339:                                    "Invalid escaped character in AVA: "
0340:                                            + (char) c);
0341:                        }
0342:                    }
0343:
0344:                    // add embedded hex bytes before next char
0345:                    if (embeddedHex.size() > 0) {
0346:                        String hexString = getEmbeddedHexString(embeddedHex);
0347:                        temp.append(hexString);
0348:                        embeddedHex.clear();
0349:                    }
0350:
0351:                    // check for non-PrintableString chars
0352:                    isPrintableString &= DerValue
0353:                            .isPrintableStringChar((char) c);
0354:                    temp.append((char) c);
0355:                    c = readChar(in, "Quoted string did not end in quote");
0356:                }
0357:
0358:                // add trailing embedded hex bytes
0359:                if (embeddedHex.size() > 0) {
0360:                    String hexString = getEmbeddedHexString(embeddedHex);
0361:                    temp.append(hexString);
0362:                    embeddedHex.clear();
0363:                }
0364:
0365:                do {
0366:                    c = in.read();
0367:                } while ((c == '\n') || (c == ' '));
0368:                if (c != -1) {
0369:                    throw new IOException("AVA had characters other than "
0370:                            + "whitespace after terminating quote");
0371:                }
0372:
0373:                // encode as PrintableString unless value contains
0374:                // non-PrintableString chars
0375:                if (this .oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID)
0376:                        || (this .oid.equals(X500Name.DOMAIN_COMPONENT_OID) && PRESERVE_OLD_DC_ENCODING == false)) {
0377:                    // EmailAddress and DomainComponent must be IA5String
0378:                    return new DerValue(DerValue.tag_IA5String, temp.toString()
0379:                            .trim());
0380:                } else if (isPrintableString) {
0381:                    return new DerValue(temp.toString().trim());
0382:                } else {
0383:                    return new DerValue(DerValue.tag_UTF8String, temp
0384:                            .toString().trim());
0385:                }
0386:            }
0387:
0388:            private DerValue parseString(Reader in, int c, int format,
0389:                    StringBuilder temp) throws IOException {
0390:
0391:                List<Byte> embeddedHex = new ArrayList<Byte>();
0392:                boolean isPrintableString = true;
0393:                boolean escape = false;
0394:                boolean leadingChar = true;
0395:                int spaceCount = 0;
0396:                do {
0397:                    escape = false;
0398:                    if (c == '\\') {
0399:                        escape = true;
0400:                        c = readChar(in, "Invalid trailing backslash");
0401:
0402:                        // check for embedded hex pairs
0403:                        Byte hexByte = null;
0404:                        if ((hexByte = getEmbeddedHexPair(c, in)) != null) {
0405:
0406:                            // always encode AVAs with embedded hex as UTF8
0407:                            isPrintableString = false;
0408:
0409:                            // append consecutive embedded hex
0410:                            // as single string later
0411:                            embeddedHex.add(hexByte);
0412:                            c = in.read();
0413:                            leadingChar = false;
0414:                            continue;
0415:                        }
0416:
0417:                        // check if character was improperly escaped
0418:                        if ((format == DEFAULT && specialCharsAll
0419:                                .indexOf((char) c) == -1)
0420:                                || (format == RFC1779
0421:                                        && specialChars.indexOf((char) c) == -1
0422:                                        && c != '\\' && c != '\"')) {
0423:
0424:                            throw new IOException(
0425:                                    "Invalid escaped character in AVA: '"
0426:                                            + (char) c + "'");
0427:
0428:                        } else if (format == RFC2253) {
0429:                            if (c == ' ') {
0430:                                // only leading/trailing space can be escaped
0431:                                if (!leadingChar && !trailingSpace(in)) {
0432:                                    throw new IOException(
0433:                                            "Invalid escaped space character "
0434:                                                    + "in AVA.  Only a leading or trailing "
0435:                                                    + "space character can be escaped.");
0436:                                }
0437:                            } else if (c == '#') {
0438:                                // only leading '#' can be escaped
0439:                                if (!leadingChar) {
0440:                                    throw new IOException(
0441:                                            "Invalid escaped '#' character in AVA.  "
0442:                                                    + "Only a leading '#' can be escaped.");
0443:                                }
0444:                            } else if (specialChars2253.indexOf((char) c) == -1) {
0445:                                throw new IOException(
0446:                                        "Invalid escaped character in AVA: '"
0447:                                                + (char) c + "'");
0448:
0449:                            }
0450:                        }
0451:
0452:                    } else {
0453:                        // check if character should have been escaped
0454:                        if (format == RFC2253) {
0455:                            if (specialChars2253.indexOf((char) c) != -1) {
0456:                                throw new IOException("Character '" + (char) c
0457:                                        + "' in AVA appears without escape");
0458:                            }
0459:                        }
0460:                    }
0461:
0462:                    // add embedded hex bytes before next char
0463:                    if (embeddedHex.size() > 0) {
0464:                        // add space(s) before embedded hex bytes
0465:                        for (int i = 0; i < spaceCount; i++) {
0466:                            temp.append(" ");
0467:                        }
0468:                        spaceCount = 0;
0469:
0470:                        String hexString = getEmbeddedHexString(embeddedHex);
0471:                        temp.append(hexString);
0472:                        embeddedHex.clear();
0473:                    }
0474:
0475:                    // check for non-PrintableString chars
0476:                    isPrintableString &= DerValue
0477:                            .isPrintableStringChar((char) c);
0478:                    if (c == ' ' && escape == false) {
0479:                        // do not add non-escaped spaces yet
0480:                        // (non-escaped trailing spaces are ignored)
0481:                        spaceCount++;
0482:                    } else {
0483:                        // add space(s)
0484:                        for (int i = 0; i < spaceCount; i++) {
0485:                            temp.append(" ");
0486:                        }
0487:                        spaceCount = 0;
0488:                        temp.append((char) c);
0489:                    }
0490:                    c = in.read();
0491:                    leadingChar = false;
0492:                } while (isTerminator(c, format) == false);
0493:
0494:                if (format == RFC2253 && spaceCount > 0) {
0495:                    throw new IOException("Incorrect AVA RFC2253 format - "
0496:                            + "trailing space must be escaped");
0497:                }
0498:
0499:                // add trailing embedded hex bytes
0500:                if (embeddedHex.size() > 0) {
0501:                    String hexString = getEmbeddedHexString(embeddedHex);
0502:                    temp.append(hexString);
0503:                    embeddedHex.clear();
0504:                }
0505:
0506:                // encode as PrintableString unless value contains
0507:                // non-PrintableString chars
0508:                if (this .oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID)
0509:                        || (this .oid.equals(X500Name.DOMAIN_COMPONENT_OID) && PRESERVE_OLD_DC_ENCODING == false)) {
0510:                    // EmailAddress and DomainComponent must be IA5String
0511:                    return new DerValue(DerValue.tag_IA5String, temp.toString());
0512:                } else if (isPrintableString) {
0513:                    return new DerValue(temp.toString());
0514:                } else {
0515:                    return new DerValue(DerValue.tag_UTF8String, temp
0516:                            .toString());
0517:                }
0518:            }
0519:
0520:            private static Byte getEmbeddedHexPair(int c1, Reader in)
0521:                    throws IOException {
0522:
0523:                if (hexDigits.indexOf(Character.toUpperCase((char) c1)) >= 0) {
0524:                    int c2 = readChar(in, "unexpected EOF - "
0525:                            + "escaped hex value must include two valid digits");
0526:
0527:                    if (hexDigits.indexOf(Character.toUpperCase((char) c2)) >= 0) {
0528:                        int hi = Character.digit((char) c1, 16);
0529:                        int lo = Character.digit((char) c2, 16);
0530:                        return new Byte((byte) ((hi << 4) + lo));
0531:                    } else {
0532:                        throw new IOException(
0533:                                "escaped hex value must include two valid digits");
0534:                    }
0535:                }
0536:                return null;
0537:            }
0538:
0539:            private static String getEmbeddedHexString(List<Byte> hexList)
0540:                    throws IOException {
0541:                int n = hexList.size();
0542:                byte[] hexBytes = new byte[n];
0543:                for (int i = 0; i < n; i++) {
0544:                    hexBytes[i] = hexList.get(i).byteValue();
0545:                }
0546:                return new String(hexBytes, "UTF8");
0547:            }
0548:
0549:            private static boolean isTerminator(int ch, int format) {
0550:                switch (ch) {
0551:                case -1:
0552:                case '+':
0553:                case ',':
0554:                    return true;
0555:                case ';':
0556:                case '>':
0557:                    return format != RFC2253;
0558:                default:
0559:                    return false;
0560:                }
0561:            }
0562:
0563:            private static int readChar(Reader in, String errMsg)
0564:                    throws IOException {
0565:                int c = in.read();
0566:                if (c == -1) {
0567:                    throw new IOException(errMsg);
0568:                }
0569:                return c;
0570:            }
0571:
0572:            private static boolean trailingSpace(Reader in) throws IOException {
0573:
0574:                boolean trailing = false;
0575:
0576:                if (!in.markSupported()) {
0577:                    // oh well
0578:                    return true;
0579:                } else {
0580:                    // make readAheadLimit huge -
0581:                    // in practice, AVA was passed a StringReader from X500Name,
0582:                    // and StringReader ignores readAheadLimit anyways
0583:                    in.mark(9999);
0584:                    while (true) {
0585:                        int nextChar = in.read();
0586:                        if (nextChar == -1) {
0587:                            trailing = true;
0588:                            break;
0589:                        } else if (nextChar == ' ') {
0590:                            continue;
0591:                        } else if (nextChar == '\\') {
0592:                            int followingChar = in.read();
0593:                            if (followingChar != ' ') {
0594:                                trailing = false;
0595:                                break;
0596:                            }
0597:                        } else {
0598:                            trailing = false;
0599:                            break;
0600:                        }
0601:                    }
0602:
0603:                    in.reset();
0604:                    return trailing;
0605:                }
0606:            }
0607:
0608:            AVA(DerValue derval) throws IOException {
0609:                // Individual attribute value assertions are SEQUENCE of two values.
0610:                // That'd be a "struct" outside of ASN.1.
0611:                if (derval.tag != DerValue.tag_Sequence) {
0612:                    throw new IOException("AVA not a sequence");
0613:                }
0614:                oid = X500Name.intern(derval.data.getOID());
0615:                value = derval.data.getDerValue();
0616:
0617:                if (derval.data.available() != 0) {
0618:                    throw new IOException("AVA, extra bytes = "
0619:                            + derval.data.available());
0620:                }
0621:            }
0622:
0623:            AVA(DerInputStream in) throws IOException {
0624:                this (in.getDerValue());
0625:            }
0626:
0627:            public boolean equals(Object obj) {
0628:                if (this  == obj) {
0629:                    return true;
0630:                }
0631:                if (obj instanceof  AVA == false) {
0632:                    return false;
0633:                }
0634:                AVA other = (AVA) obj;
0635:                return this .toRFC2253CanonicalString().equals(
0636:                        other.toRFC2253CanonicalString());
0637:            }
0638:
0639:            /**
0640:             * Returns a hashcode for this AVA.
0641:             *
0642:             * @return a hashcode for this AVA.
0643:             */
0644:            public int hashCode() {
0645:                return toRFC2253CanonicalString().hashCode();
0646:            }
0647:
0648:            /*
0649:             * AVAs are encoded as a SEQUENCE of two elements.
0650:             */
0651:            public void encode(DerOutputStream out) throws IOException {
0652:                derEncode(out);
0653:            }
0654:
0655:            /**
0656:             * DER encode this object onto an output stream.
0657:             * Implements the <code>DerEncoder</code> interface.
0658:             *
0659:             * @param out
0660:             * the output stream on which to write the DER encoding.
0661:             *
0662:             * @exception IOException on encoding error.
0663:             */
0664:            public void derEncode(OutputStream out) throws IOException {
0665:                DerOutputStream tmp = new DerOutputStream();
0666:                DerOutputStream tmp2 = new DerOutputStream();
0667:
0668:                tmp.putOID(oid);
0669:                value.encode(tmp);
0670:                tmp2.write(DerValue.tag_Sequence, tmp);
0671:                out.write(tmp2.toByteArray());
0672:            }
0673:
0674:            private String toKeyword(int format, Map<String, String> oidMap) {
0675:                return AVAKeyword.getKeyword(oid, format, oidMap);
0676:            }
0677:
0678:            /**
0679:             * Returns a printable form of this attribute, using RFC 1779
0680:             * syntax for individual attribute/value assertions.
0681:             */
0682:            public String toString() {
0683:                return toKeywordValueString(toKeyword(DEFAULT, Collections
0684:                        .<String, String> emptyMap()));
0685:            }
0686:
0687:            /**
0688:             * Returns a printable form of this attribute, using RFC 1779
0689:             * syntax for individual attribute/value assertions. It only
0690:             * emits standardised keywords.
0691:             */
0692:            public String toRFC1779String() {
0693:                return toRFC1779String(Collections.<String, String> emptyMap());
0694:            }
0695:
0696:            /**
0697:             * Returns a printable form of this attribute, using RFC 1779
0698:             * syntax for individual attribute/value assertions. It 
0699:             * emits standardised keywords, as well as keywords contained in the
0700:             * OID/keyword map.
0701:             */
0702:            public String toRFC1779String(Map<String, String> oidMap) {
0703:                return toKeywordValueString(toKeyword(RFC1779, oidMap));
0704:            }
0705:
0706:            /**
0707:             * Returns a printable form of this attribute, using RFC 2253
0708:             * syntax for individual attribute/value assertions. It only
0709:             * emits standardised keywords.
0710:             */
0711:            public String toRFC2253String() {
0712:                return toRFC2253String(Collections.<String, String> emptyMap());
0713:            }
0714:
0715:            /**
0716:             * Returns a printable form of this attribute, using RFC 2253
0717:             * syntax for individual attribute/value assertions. It 
0718:             * emits standardised keywords, as well as keywords contained in the
0719:             * OID/keyword map.
0720:             */
0721:            public String toRFC2253String(Map<String, String> oidMap) {
0722:                /*
0723:                 * Section 2.3: The AttributeTypeAndValue is encoded as the string 
0724:                 * representation of the AttributeType, followed by an equals character 
0725:                 * ('=' ASCII 61), followed by the string representation of the 
0726:                 * AttributeValue. The encoding of the AttributeValue is given in 
0727:                 * section 2.4.
0728:                 */
0729:                StringBuilder typeAndValue = new StringBuilder(100);
0730:                typeAndValue.append(toKeyword(RFC2253, oidMap));
0731:                typeAndValue.append('=');
0732:
0733:                /*
0734:                 * Section 2.4: Converting an AttributeValue from ASN.1 to a String.
0735:                 * If the AttributeValue is of a type which does not have a string
0736:                 * representation defined for it, then it is simply encoded as an
0737:                 * octothorpe character ('#' ASCII 35) followed by the hexadecimal
0738:                 * representation of each of the bytes of the BER encoding of the X.500
0739:                 * AttributeValue.  This form SHOULD be used if the AttributeType is of
0740:                 * the dotted-decimal form.
0741:                 */
0742:                if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9')
0743:                        || !isDerString(value, false)) {
0744:                    byte[] data = null;
0745:                    try {
0746:                        data = value.toByteArray();
0747:                    } catch (IOException ie) {
0748:                        throw new IllegalArgumentException(
0749:                                "DER Value conversion");
0750:                    }
0751:                    typeAndValue.append('#');
0752:                    for (int j = 0; j < data.length; j++) {
0753:                        byte b = data[j];
0754:                        typeAndValue.append(Character.forDigit(0xF & (b >>> 4),
0755:                                16));
0756:                        typeAndValue.append(Character.forDigit(0xF & b, 16));
0757:                    }
0758:                } else {
0759:                    /*
0760:                     * 2.4 (cont): Otherwise, if the AttributeValue is of a type which 
0761:                     * has a string representation, the value is converted first to a 
0762:                     * UTF-8 string according to its syntax specification.
0763:                     *
0764:                     * NOTE: this implementation only emits DirectoryStrings of the
0765:                     * types returned by isDerString().
0766:                     */
0767:                    String valStr = null;
0768:                    try {
0769:                        valStr = new String(value.getDataBytes(), "UTF8");
0770:                    } catch (IOException ie) {
0771:                        throw new IllegalArgumentException(
0772:                                "DER Value conversion");
0773:                    }
0774:
0775:                    /* 
0776:                     * 2.4 (cont): If the UTF-8 string does not have any of the 
0777:                     * following characters which need escaping, then that string can be
0778:                     * used as the string representation of the value.
0779:                     *
0780:                     *   o   a space or "#" character occurring at the beginning of the
0781:                     *       string
0782:                     *   o   a space character occurring at the end of the string
0783:                     *   o   one of the characters ",", "+", """, "\", "<", ">" or ";"
0784:                     *
0785:                     * Implementations MAY escape other characters.
0786:                     *
0787:                     * NOTE: this implementation also recognizes "=" and "#" as 
0788:                     * characters which need escaping.
0789:                     *
0790:                     * If a character to be escaped is one of the list shown above, then
0791:                     * it is prefixed by a backslash ('\' ASCII 92).
0792:                     *
0793:                     * Otherwise the character to be escaped is replaced by a backslash 
0794:                     * and two hex digits, which form a single byte in the code of the
0795:                     * character.
0796:                     */
0797:                    final String escapees = ",=+<>#;\"\\";
0798:                    StringBuilder sbuffer = new StringBuilder();
0799:
0800:                    for (int i = 0; i < valStr.length(); i++) {
0801:                        char c = valStr.charAt(i);
0802:                        if (DerValue.isPrintableStringChar(c)
0803:                                || escapees.indexOf(c) >= 0) {
0804:
0805:                            // escape escapees
0806:                            if (escapees.indexOf(c) >= 0) {
0807:                                sbuffer.append('\\');
0808:                            }
0809:
0810:                            // append printable/escaped char
0811:                            sbuffer.append(c);
0812:
0813:                        } else if (debug != null && Debug.isOn("ava")) {
0814:
0815:                            // embed non-printable/non-escaped char
0816:                            // as escaped hex pairs for debugging
0817:                            byte[] valueBytes = null;
0818:                            try {
0819:                                valueBytes = Character.toString(c).getBytes(
0820:                                        "UTF8");
0821:                            } catch (IOException ie) {
0822:                                throw new IllegalArgumentException(
0823:                                        "DER Value conversion");
0824:                            }
0825:                            for (int j = 0; j < valueBytes.length; j++) {
0826:                                sbuffer.append('\\');
0827:                                char hexChar = Character.forDigit(
0828:                                        0xF & (valueBytes[j] >>> 4), 16);
0829:                                sbuffer.append(Character.toUpperCase(hexChar));
0830:                                hexChar = Character.forDigit(
0831:                                        0xF & (valueBytes[j]), 16);
0832:                                sbuffer.append(Character.toUpperCase(hexChar));
0833:                            }
0834:                        } else {
0835:
0836:                            // append non-printable/non-escaped char
0837:                            sbuffer.append(c);
0838:                        }
0839:                    }
0840:
0841:                    char[] chars = sbuffer.toString().toCharArray();
0842:                    sbuffer = new StringBuilder();
0843:
0844:                    // Find leading and trailing whitespace.
0845:                    int lead; // index of first char that is not leading whitespace
0846:                    for (lead = 0; lead < chars.length; lead++) {
0847:                        if (chars[lead] != ' ' && chars[lead] != '\r') {
0848:                            break;
0849:                        }
0850:                    }
0851:                    int trail; // index of last char that is not trailing whitespace
0852:                    for (trail = chars.length - 1; trail >= 0; trail--) {
0853:                        if (chars[trail] != ' ' && chars[trail] != '\r') {
0854:                            break;
0855:                        }
0856:                    }
0857:
0858:                    // escape leading and trailing whitespace
0859:                    for (int i = 0; i < chars.length; i++) {
0860:                        char c = chars[i];
0861:                        if (i < lead || i > trail) {
0862:                            sbuffer.append('\\');
0863:                        }
0864:                        sbuffer.append(c);
0865:                    }
0866:                    typeAndValue.append(sbuffer.toString());
0867:                }
0868:                return typeAndValue.toString();
0869:            }
0870:
0871:            public String toRFC2253CanonicalString() {
0872:                /*
0873:                 * Section 2.3: The AttributeTypeAndValue is encoded as the string 
0874:                 * representation of the AttributeType, followed by an equals character 
0875:                 * ('=' ASCII 61), followed by the string representation of the 
0876:                 * AttributeValue. The encoding of the AttributeValue is given in 
0877:                 * section 2.4.
0878:                 */
0879:                StringBuilder typeAndValue = new StringBuilder(40);
0880:                typeAndValue.append(toKeyword(RFC2253, Collections
0881:                        .<String, String> emptyMap()));
0882:                typeAndValue.append('=');
0883:
0884:                /*
0885:                 * Section 2.4: Converting an AttributeValue from ASN.1 to a String.
0886:                 * If the AttributeValue is of a type which does not have a string
0887:                 * representation defined for it, then it is simply encoded as an
0888:                 * octothorpe character ('#' ASCII 35) followed by the hexadecimal
0889:                 * representation of each of the bytes of the BER encoding of the X.500
0890:                 * AttributeValue.  This form SHOULD be used if the AttributeType is of
0891:                 * the dotted-decimal form.
0892:                 */
0893:                if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9')
0894:                        || !isDerString(value, true)) {
0895:                    byte[] data = null;
0896:                    try {
0897:                        data = value.toByteArray();
0898:                    } catch (IOException ie) {
0899:                        throw new IllegalArgumentException(
0900:                                "DER Value conversion");
0901:                    }
0902:                    typeAndValue.append('#');
0903:                    for (int j = 0; j < data.length; j++) {
0904:                        byte b = data[j];
0905:                        typeAndValue.append(Character.forDigit(0xF & (b >>> 4),
0906:                                16));
0907:                        typeAndValue.append(Character.forDigit(0xF & b, 16));
0908:                    }
0909:                } else {
0910:                    /*
0911:                     * 2.4 (cont): Otherwise, if the AttributeValue is of a type which 
0912:                     * has a string representation, the value is converted first to a 
0913:                     * UTF-8 string according to its syntax specification.
0914:                     *
0915:                     * NOTE: this implementation only emits DirectoryStrings of the
0916:                     * types returned by isDerString().
0917:                     */
0918:                    String valStr = null;
0919:                    try {
0920:                        valStr = new String(value.getDataBytes(), "UTF8");
0921:                    } catch (IOException ie) {
0922:                        throw new IllegalArgumentException(
0923:                                "DER Value conversion");
0924:                    }
0925:
0926:                    /* 
0927:                     * 2.4 (cont): If the UTF-8 string does not have any of the 
0928:                     * following characters which need escaping, then that string can be
0929:                     * used as the string representation of the value.
0930:                     *
0931:                     *   o   a space or "#" character occurring at the beginning of the
0932:                     *       string
0933:                     *   o   a space character occurring at the end of the string
0934:                     *
0935:                     *   o   one of the characters ",", "+", """, "\", "<", ">" or ";"
0936:                     *
0937:                     * If a character to be escaped is one of the list shown above, then
0938:                     * it is prefixed by a backslash ('\' ASCII 92).
0939:                     *
0940:                     * Otherwise the character to be escaped is replaced by a backslash 
0941:                     * and two hex digits, which form a single byte in the code of the
0942:                     * character.
0943:                     */
0944:                    final String escapees = ",+<>;\"\\";
0945:                    StringBuilder sbuffer = new StringBuilder();
0946:                    boolean previousWhite = false;
0947:
0948:                    for (int i = 0; i < valStr.length(); i++) {
0949:                        char c = valStr.charAt(i);
0950:
0951:                        if (DerValue.isPrintableStringChar(c)
0952:                                || escapees.indexOf(c) >= 0
0953:                                || (i == 0 && c == '#')) {
0954:
0955:                            // escape leading '#' and escapees
0956:                            if ((i == 0 && c == '#')
0957:                                    || escapees.indexOf(c) >= 0) {
0958:                                sbuffer.append('\\');
0959:                            }
0960:
0961:                            // convert multiple whitespace to single whitespace
0962:                            if (!Character.isWhitespace(c)) {
0963:                                previousWhite = false;
0964:                                sbuffer.append(c);
0965:                            } else {
0966:                                if (previousWhite == false) {
0967:                                    // add single whitespace
0968:                                    previousWhite = true;
0969:                                    sbuffer.append(c);
0970:                                } else {
0971:                                    // ignore subsequent consecutive whitespace
0972:                                    continue;
0973:                                }
0974:                            }
0975:
0976:                        } else if (debug != null && Debug.isOn("ava")) {
0977:
0978:                            // embed non-printable/non-escaped char
0979:                            // as escaped hex pairs for debugging
0980:
0981:                            previousWhite = false;
0982:
0983:                            byte valueBytes[] = null;
0984:                            try {
0985:                                valueBytes = Character.toString(c).getBytes(
0986:                                        "UTF8");
0987:                            } catch (IOException ie) {
0988:                                throw new IllegalArgumentException(
0989:                                        "DER Value conversion");
0990:                            }
0991:                            for (int j = 0; j < valueBytes.length; j++) {
0992:                                sbuffer.append('\\');
0993:                                sbuffer.append(Character.forDigit(
0994:                                        0xF & (valueBytes[j] >>> 4), 16));
0995:                                sbuffer.append(Character.forDigit(
0996:                                        0xF & (valueBytes[j]), 16));
0997:                            }
0998:                        } else {
0999:
1000:                            // append non-printable/non-escaped char
1001:
1002:                            previousWhite = false;
1003:                            sbuffer.append(c);
1004:                        }
1005:                    }
1006:
1007:                    // remove leading and trailing whitespace from value
1008:                    typeAndValue.append(sbuffer.toString().trim());
1009:                }
1010:
1011:                String canon = typeAndValue.toString();
1012:                canon = canon.toUpperCase(Locale.US).toLowerCase(Locale.US);
1013:                return Normalizer.normalize(canon, Normalizer.Form.NFKD);
1014:            }
1015:
1016:            /*
1017:             * Return true if DerValue can be represented as a String.
1018:             */
1019:            private static boolean isDerString(DerValue value, boolean canonical) {
1020:                if (canonical) {
1021:                    switch (value.tag) {
1022:                    case DerValue.tag_PrintableString:
1023:                    case DerValue.tag_UTF8String:
1024:                        return true;
1025:                    default:
1026:                        return false;
1027:                    }
1028:                } else {
1029:                    switch (value.tag) {
1030:                    case DerValue.tag_PrintableString:
1031:                    case DerValue.tag_T61String:
1032:                    case DerValue.tag_IA5String:
1033:                    case DerValue.tag_GeneralString:
1034:                    case DerValue.tag_BMPString:
1035:                    case DerValue.tag_UTF8String:
1036:                        return true;
1037:                    default:
1038:                        return false;
1039:                    }
1040:                }
1041:            }
1042:
1043:            boolean hasRFC2253Keyword() {
1044:                return AVAKeyword.hasKeyword(oid, RFC2253);
1045:            }
1046:
1047:            private String toKeywordValueString(String keyword) {
1048:                /*
1049:                 * Construct the value with as little copying and garbage
1050:                 * production as practical.  First the keyword (mandatory),
1051:                 * then the equals sign, finally the value.
1052:                 */
1053:                StringBuilder retval = new StringBuilder(40);
1054:
1055:                retval.append(keyword);
1056:                retval.append("=");
1057:
1058:                try {
1059:                    String valStr = value.getAsString();
1060:
1061:                    if (valStr == null) {
1062:
1063:                        // rfc1779 specifies that attribute values associated
1064:                        // with non-standard keyword attributes may be represented
1065:                        // using the hex format below.  This will be used only
1066:                        // when the value is not a string type
1067:
1068:                        byte data[] = value.toByteArray();
1069:
1070:                        retval.append('#');
1071:                        for (int i = 0; i < data.length; i++) {
1072:                            retval.append(hexDigits
1073:                                    .charAt((data[i] >> 4) & 0x0f));
1074:                            retval.append(hexDigits.charAt(data[i] & 0x0f));
1075:                        }
1076:
1077:                    } else {
1078:
1079:                        boolean quoteNeeded = false;
1080:                        StringBuilder sbuffer = new StringBuilder();
1081:                        boolean previousWhite = false;
1082:                        final String escapees = ",+=\n<>#;\\\"";
1083:
1084:                        /*
1085:                         * Special characters (e.g. AVA list separators) cause strings
1086:                         * to need quoting, or at least escaping.  So do leading or
1087:                         * trailing spaces, and multiple internal spaces.
1088:                         */
1089:                        for (int i = 0; i < valStr.length(); i++) {
1090:                            char c = valStr.charAt(i);
1091:                            if (DerValue.isPrintableStringChar(c)
1092:                                    || escapees.indexOf(c) >= 0) {
1093:
1094:                                // quote if leading whitespace or special chars
1095:                                if (!quoteNeeded
1096:                                        && ((i == 0 && (c == ' ' || c == '\n')) || escapees
1097:                                                .indexOf(c) >= 0)) {
1098:                                    quoteNeeded = true;
1099:                                }
1100:
1101:                                // quote if multiple internal whitespace
1102:                                if (!(c == ' ' || c == '\n')) {
1103:                                    // escape '"' and '\'
1104:                                    if (c == '"' || c == '\\') {
1105:                                        sbuffer.append('\\');
1106:                                    }
1107:                                    previousWhite = false;
1108:                                } else {
1109:                                    if (!quoteNeeded && previousWhite) {
1110:                                        quoteNeeded = true;
1111:                                    }
1112:                                    previousWhite = true;
1113:                                }
1114:
1115:                                sbuffer.append(c);
1116:
1117:                            } else if (debug != null && Debug.isOn("ava")) {
1118:
1119:                                // embed non-printable/non-escaped char
1120:                                // as escaped hex pairs for debugging
1121:
1122:                                previousWhite = false;
1123:
1124:                                // embed escaped hex pairs
1125:                                byte[] valueBytes = Character.toString(c)
1126:                                        .getBytes("UTF8");
1127:                                for (int j = 0; j < valueBytes.length; j++) {
1128:                                    sbuffer.append('\\');
1129:                                    char hexChar = Character.forDigit(
1130:                                            0xF & (valueBytes[j] >>> 4), 16);
1131:                                    sbuffer.append(Character
1132:                                            .toUpperCase(hexChar));
1133:                                    hexChar = Character.forDigit(
1134:                                            0xF & (valueBytes[j]), 16);
1135:                                    sbuffer.append(Character
1136:                                            .toUpperCase(hexChar));
1137:                                }
1138:                            } else {
1139:
1140:                                // append non-printable/non-escaped char
1141:
1142:                                previousWhite = false;
1143:                                sbuffer.append(c);
1144:                            }
1145:                        }
1146:
1147:                        // quote if trailing whitespace
1148:                        if (sbuffer.length() > 0) {
1149:                            char trailChar = sbuffer
1150:                                    .charAt(sbuffer.length() - 1);
1151:                            if (trailChar == ' ' || trailChar == '\n') {
1152:                                quoteNeeded = true;
1153:                            }
1154:                        }
1155:
1156:                        // Emit the string ... quote it if needed
1157:                        if (quoteNeeded) {
1158:                            retval.append("\"" + sbuffer.toString() + "\"");
1159:                        } else {
1160:                            retval.append(sbuffer.toString());
1161:                        }
1162:                    }
1163:                } catch (IOException e) {
1164:                    throw new IllegalArgumentException("DER Value conversion");
1165:                }
1166:
1167:                return retval.toString();
1168:            }
1169:
1170:        }
1171:
1172:        /**
1173:         * Helper class that allows conversion from String to ObjectIdentifier and
1174:         * vice versa according to RFC1779, RFC2253, and an augmented version of
1175:         * those standards.
1176:         */
1177:        class AVAKeyword {
1178:
1179:            private static final Map<ObjectIdentifier, AVAKeyword> oidMap;
1180:            private static final Map<String, AVAKeyword> keywordMap;
1181:
1182:            private String keyword;
1183:            private ObjectIdentifier oid;
1184:            private boolean rfc1779Compliant, rfc2253Compliant;
1185:
1186:            private AVAKeyword(String keyword, ObjectIdentifier oid,
1187:                    boolean rfc1779Compliant, boolean rfc2253Compliant) {
1188:                this .keyword = keyword;
1189:                this .oid = oid;
1190:                this .rfc1779Compliant = rfc1779Compliant;
1191:                this .rfc2253Compliant = rfc2253Compliant;
1192:
1193:                // register it
1194:                oidMap.put(oid, this );
1195:                keywordMap.put(keyword, this );
1196:            }
1197:
1198:            private boolean isCompliant(int standard) {
1199:                switch (standard) {
1200:                case AVA.RFC1779:
1201:                    return rfc1779Compliant;
1202:                case AVA.RFC2253:
1203:                    return rfc2253Compliant;
1204:                case AVA.DEFAULT:
1205:                    return true;
1206:                default:
1207:                    // should not occur, internal error
1208:                    throw new IllegalArgumentException("Invalid standard "
1209:                            + standard);
1210:                }
1211:            }
1212:
1213:            /**
1214:             * Get an object identifier representing the specified keyword (or
1215:             * string encoded object identifier) in the given standard.
1216:             *
1217:             * @throws IOException If the keyword is not valid in the specified standard
1218:             */
1219:            static ObjectIdentifier getOID(String keyword, int standard)
1220:                    throws IOException {
1221:                return getOID(keyword, standard, Collections
1222:                        .<String, String> emptyMap());
1223:            }
1224:
1225:            /**
1226:             * Get an object identifier representing the specified keyword (or
1227:             * string encoded object identifier) in the given standard.
1228:             *
1229:             * @param keywordMap a Map where a keyword String maps to a corresponding
1230:             *   OID String. Each AVA keyword will be mapped to the corresponding OID.
1231:             *   If an entry does not exist, it will fallback to the builtin 
1232:             *   keyword/OID mapping.
1233:             * @throws IOException If the keyword is not valid in the specified standard
1234:             *   or the OID String to which a keyword maps to is improperly formatted.
1235:             */
1236:            static ObjectIdentifier getOID(String keyword, int standard,
1237:                    Map<String, String> extraKeywordMap) throws IOException {
1238:
1239:                keyword = keyword.toUpperCase();
1240:                if (standard == AVA.RFC2253) {
1241:                    if (keyword.startsWith(" ") || keyword.endsWith(" ")) {
1242:                        throw new IOException(
1243:                                "Invalid leading or trailing space "
1244:                                        + "in keyword \"" + keyword + "\"");
1245:                    }
1246:                } else {
1247:                    keyword = keyword.trim();
1248:                }
1249:
1250:                // check user-specified keyword map first, then fallback to built-in
1251:                // map
1252:                String oidString = extraKeywordMap.get(keyword);
1253:                if (oidString == null) {
1254:                    AVAKeyword ak = keywordMap.get(keyword);
1255:                    if ((ak != null) && ak.isCompliant(standard)) {
1256:                        return ak.oid;
1257:                    }
1258:                } else {
1259:                    return new ObjectIdentifier(oidString);
1260:                }
1261:
1262:                // no keyword found or not standard compliant, check if OID string
1263:
1264:                // RFC1779 requires, DEFAULT allows OID. prefix
1265:                if (standard == AVA.RFC1779) {
1266:                    if (keyword.startsWith("OID.") == false) {
1267:                        throw new IOException("Invalid RFC1779 keyword: "
1268:                                + keyword);
1269:                    }
1270:                    keyword = keyword.substring(4);
1271:                } else if (standard == AVA.DEFAULT) {
1272:                    if (keyword.startsWith("OID.")) {
1273:                        keyword = keyword.substring(4);
1274:                    }
1275:                }
1276:                boolean number = false;
1277:                if (keyword.length() != 0) {
1278:                    char ch = keyword.charAt(0);
1279:                    if ((ch >= '0') && (ch <= '9')) {
1280:                        number = true;
1281:                    }
1282:                }
1283:                if (number == false) {
1284:                    throw new IOException("Invalid keyword \"" + keyword + "\"");
1285:                }
1286:                return new ObjectIdentifier(keyword);
1287:            }
1288:
1289:            /**
1290:             * Get a keyword for the given ObjectIdentifier according to standard.
1291:             * If no keyword is available, the ObjectIdentifier is encoded as a
1292:             * String.
1293:             */
1294:            static String getKeyword(ObjectIdentifier oid, int standard) {
1295:                return getKeyword(oid, standard, Collections
1296:                        .<String, String> emptyMap());
1297:            }
1298:
1299:            /**
1300:             * Get a keyword for the given ObjectIdentifier according to standard.
1301:             * Checks the extraOidMap for a keyword first, then falls back to the
1302:             * builtin/default set. If no keyword is available, the ObjectIdentifier 
1303:             * is encoded as a String.
1304:             */
1305:            static String getKeyword(ObjectIdentifier oid, int standard,
1306:                    Map<String, String> extraOidMap) {
1307:
1308:                // check extraOidMap first, then fallback to built-in map
1309:                String oidString = oid.toString();
1310:                String keywordString = extraOidMap.get(oidString);
1311:                if (keywordString == null) {
1312:                    AVAKeyword ak = oidMap.get(oid);
1313:                    if ((ak != null) && ak.isCompliant(standard)) {
1314:                        return ak.keyword;
1315:                    }
1316:                } else {
1317:                    if (keywordString.length() == 0) {
1318:                        throw new IllegalArgumentException(
1319:                                "keyword cannot be empty");
1320:                    }
1321:                    keywordString = keywordString.trim();
1322:                    char c = keywordString.charAt(0);
1323:                    if (c < 65 || c > 122 || (c > 90 && c < 97)) {
1324:                        throw new IllegalArgumentException(
1325:                                "keyword does not start with letter");
1326:                    }
1327:                    for (int i = 1; i < keywordString.length(); i++) {
1328:                        c = keywordString.charAt(i);
1329:                        if ((c < 65 || c > 122 || (c > 90 && c < 97))
1330:                                && (c < 48 || c > 57) && c != '_') {
1331:                            throw new IllegalArgumentException(
1332:                                    "keyword character is not a letter, digit, or underscore");
1333:                        }
1334:                    }
1335:                    return keywordString;
1336:                }
1337:                // no compliant keyword, use OID
1338:                if (standard == AVA.RFC2253) {
1339:                    return oidString;
1340:                } else {
1341:                    return "OID." + oidString;
1342:                }
1343:            }
1344:
1345:            /**
1346:             * Test if oid has an associated keyword in standard.
1347:             */
1348:            static boolean hasKeyword(ObjectIdentifier oid, int standard) {
1349:                AVAKeyword ak = oidMap.get(oid);
1350:                if (ak == null) {
1351:                    return false;
1352:                }
1353:                return ak.isCompliant(standard);
1354:            }
1355:
1356:            static {
1357:                oidMap = new HashMap<ObjectIdentifier, AVAKeyword>();
1358:                keywordMap = new HashMap<String, AVAKeyword>();
1359:
1360:                // NOTE if multiple keywords are available for one OID, order
1361:                // is significant!! Preferred *LAST*.
1362:                new AVAKeyword("CN", X500Name.commonName_oid, true, true);
1363:                new AVAKeyword("C", X500Name.countryName_oid, true, true);
1364:                new AVAKeyword("L", X500Name.localityName_oid, true, true);
1365:                new AVAKeyword("S", X500Name.stateName_oid, false, false);
1366:                new AVAKeyword("ST", X500Name.stateName_oid, true, true);
1367:                new AVAKeyword("O", X500Name.orgName_oid, true, true);
1368:                new AVAKeyword("OU", X500Name.orgUnitName_oid, true, true);
1369:                new AVAKeyword("T", X500Name.title_oid, false, false);
1370:                new AVAKeyword("IP", X500Name.ipAddress_oid, false, false);
1371:                new AVAKeyword("STREET", X500Name.streetAddress_oid, true, true);
1372:                new AVAKeyword("DC", X500Name.DOMAIN_COMPONENT_OID, false, true);
1373:                new AVAKeyword("DNQUALIFIER", X500Name.DNQUALIFIER_OID, false,
1374:                        false);
1375:                new AVAKeyword("DNQ", X500Name.DNQUALIFIER_OID, false, false);
1376:                new AVAKeyword("SURNAME", X500Name.SURNAME_OID, false, false);
1377:                new AVAKeyword("GIVENNAME", X500Name.GIVENNAME_OID, false,
1378:                        false);
1379:                new AVAKeyword("INITIALS", X500Name.INITIALS_OID, false, false);
1380:                new AVAKeyword("GENERATION", X500Name.GENERATIONQUALIFIER_OID,
1381:                        false, false);
1382:                new AVAKeyword("EMAIL", PKCS9Attribute.EMAIL_ADDRESS_OID,
1383:                        false, false);
1384:                new AVAKeyword("EMAILADDRESS",
1385:                        PKCS9Attribute.EMAIL_ADDRESS_OID, false, false);
1386:                new AVAKeyword("UID", X500Name.userid_oid, false, true);
1387:                new AVAKeyword("SERIALNUMBER", X500Name.SERIALNUMBER_OID,
1388:                        false, false);
1389:            }
1390:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.