Path: blob/master/src/java.base/share/classes/sun/security/x509/AVA.java
41159 views
/*1* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.x509;2627import java.io.ByteArrayOutputStream;28import java.io.IOException;29import java.io.OutputStream;30import java.io.Reader;31import java.text.Normalizer;32import java.util.*;3334import static java.nio.charset.StandardCharsets.UTF_8;3536import sun.security.action.GetBooleanAction;37import sun.security.util.*;38import sun.security.pkcs.PKCS9Attribute;394041/**42* X.500 Attribute-Value-Assertion (AVA): an attribute, as identified by43* some attribute ID, has some particular value. Values are as a rule ASN.144* printable strings. A conventional set of type IDs is recognized when45* parsing (and generating) RFC 1779, 2253 or 4514 syntax strings.46*47* <P>AVAs are components of X.500 relative names. Think of them as being48* individual fields of a database record. The attribute ID is how you49* identify the field, and the value is part of a particular record.50* <p>51* Note that instances of this class are immutable.52*53* @see X500Name54* @see RDN55*56*57* @author David Brownell58* @author Amit Kapoor59* @author Hemma Prafullchandra60*/61public class AVA implements DerEncoder {6263private static final Debug debug = Debug.getInstance("x509", "\t[AVA]");64// See CR 6391482: if enabled this flag preserves the old but incorrect65// PrintableString encoding for DomainComponent. It may need to be set to66// avoid breaking preexisting certificates generated with sun.security APIs.67private static final boolean PRESERVE_OLD_DC_ENCODING = GetBooleanAction68.privilegedGetProperty("com.sun.security.preserveOldDCEncoding");6970/**71* DEFAULT format allows both RFC1779 and RFC2253 syntax and72* additional keywords.73*/74static final int DEFAULT = 1;75/**76* RFC1779 specifies format according to RFC1779.77*/78static final int RFC1779 = 2;79/**80* RFC2253 specifies format according to RFC2253.81*/82static final int RFC2253 = 3;8384// currently not private, accessed directly from RDN85final ObjectIdentifier oid;86final DerValue value;8788/*89* If the value has any of these characters in it, it must be quoted.90* Backslash and quote characters must also be individually escaped.91* Leading and trailing spaces, also multiple internal spaces, also92* call for quoting the whole string.93*/94private static final String specialChars1779 = ",=\n+<>#;\\\"";9596/*97* In RFC2253, if the value has any of these characters in it, it98* must be quoted by a preceding \.99*/100private static final String specialChars2253 = ",=+<>#;\\\"";101102/*103* includes special chars from RFC1779 and RFC2253, as well as ' ' from104* RFC 4514.105*/106private static final String specialCharsDefault = ",=\n+<>#;\\\" ";107private static final String escapedDefault = ",+<>;\"";108109public AVA(ObjectIdentifier type, DerValue val) {110if ((type == null) || (val == null)) {111throw new NullPointerException();112}113oid = type;114value = val;115}116117/**118* Parse an RFC 1779, 2253 or 4514 style AVA string: CN=fee fie foe fum119* or perhaps with quotes. Not all defined AVA tags are supported;120* of current note are X.400 related ones (PRMD, ADMD, etc).121*122* This terminates at unescaped AVA separators ("+") or RDN123* separators (",", ";"), and removes cosmetic whitespace at the end of124* values.125*/126AVA(Reader in) throws IOException {127this(in, DEFAULT);128}129130/**131* Parse an RFC 1779, 2253 or 4514 style AVA string: CN=fee fie foe fum132* or perhaps with quotes. Additional keywords can be specified in the133* keyword/OID map.134*135* This terminates at unescaped AVA separators ("+") or RDN136* separators (",", ";"), and removes cosmetic whitespace at the end of137* values.138*/139AVA(Reader in, Map<String, String> keywordMap) throws IOException {140this(in, DEFAULT, keywordMap);141}142143/**144* Parse an AVA string formatted according to format.145*/146AVA(Reader in, int format) throws IOException {147this(in, format, Collections.<String, String>emptyMap());148}149150/**151* Parse an AVA string formatted according to format.152*153* @param in Reader containing AVA String154* @param format parsing format155* @param keywordMap a Map where a keyword String maps to a corresponding156* OID String. Each AVA keyword will be mapped to the corresponding OID.157* If an entry does not exist, it will fallback to the builtin158* keyword/OID mapping.159* @throws IOException if the AVA String is not valid in the specified160* format or an OID String from the keywordMap is improperly formatted161*/162AVA(Reader in, int format, Map<String, String> keywordMap)163throws IOException {164// assume format is one of DEFAULT or RFC2253165166StringBuilder temp = new StringBuilder();167int c;168169/*170* First get the keyword indicating the attribute's type,171* and map it to the appropriate OID.172*/173while (true) {174c = readChar(in, "Incorrect AVA format");175if (c == '=') {176break;177}178temp.append((char)c);179}180181oid = AVAKeyword.getOID(temp.toString(), format, keywordMap);182183/*184* Now parse the value. "#hex", a quoted string, or a string185* terminated by "+", ",", ";". Whitespace before or after186* the value is stripped away unless format is RFC2253.187*/188temp.setLength(0);189if (format == RFC2253) {190// read next character191c = in.read();192if (c == ' ') {193throw new IOException("Incorrect AVA RFC2253 format - " +194"leading space must be escaped");195}196} else {197// read next character skipping whitespace198do {199c = in.read();200} while ((c == ' ') || (c == '\n'));201}202if (c == -1) {203// empty value204value = new DerValue("");205return;206}207208if (c == '#') {209value = parseHexString(in, format);210} else if ((c == '"') && (format != RFC2253)) {211value = parseQuotedString(in, temp);212} else {213value = parseString(in, c, format, temp);214}215}216217/**218* Get the ObjectIdentifier of this AVA.219*/220public ObjectIdentifier getObjectIdentifier() {221return oid;222}223224/**225* Get the value of this AVA as a DerValue.226*/227public DerValue getDerValue() {228return value;229}230231/**232* Get the value of this AVA as a String.233*234* @exception RuntimeException if we could not obtain the string form235* (should not occur)236*/237public String getValueString() {238try {239String s = value.getAsString();240if (s == null) {241throw new RuntimeException("AVA string is null");242}243return s;244} catch (IOException e) {245// should not occur246throw new RuntimeException("AVA error: " + e, e);247}248}249250private static DerValue parseHexString251(Reader in, int format) throws IOException {252int c;253ByteArrayOutputStream baos = new ByteArrayOutputStream();254byte b = 0;255int cNdx = 0;256while (true) {257c = in.read();258259if (isTerminator(c, format)) {260break;261}262try {263int cVal = HexFormat.fromHexDigit(c); // throws on invalid character264if ((cNdx % 2) == 1) {265b = (byte)((b * 16) + (byte)(cVal));266baos.write(b);267} else {268b = (byte)(cVal);269}270cNdx++;271} catch (NumberFormatException nfe) {272throw new IOException("AVA parse, invalid hex digit: "+ (char)c);273}274}275276// throw exception if no hex digits277if (cNdx == 0) {278throw new IOException("AVA parse, zero hex digits");279}280281// throw exception if odd number of hex digits282if (cNdx % 2 == 1) {283throw new IOException("AVA parse, odd number of hex digits");284}285286return new DerValue(baos.toByteArray());287}288289private DerValue parseQuotedString290(Reader in, StringBuilder temp) throws IOException {291292// RFC1779 specifies that an entire RDN may be enclosed in double293// quotes. In this case the syntax is any sequence of294// backslash-specialChar, backslash-backslash,295// backslash-doublequote, or character other than backslash or296// doublequote.297int c = readChar(in, "Quoted string did not end in quote");298299List<Byte> embeddedHex = new ArrayList<>();300boolean isPrintableString = true;301while (c != '"') {302if (c == '\\') {303c = readChar(in, "Quoted string did not end in quote");304305// check for embedded hex pairs306Byte hexByte = null;307if ((hexByte = getEmbeddedHexPair(c, in)) != null) {308309// always encode AVAs with embedded hex as UTF8310isPrintableString = false;311312// append consecutive embedded hex313// as single string later314embeddedHex.add(hexByte);315c = in.read();316continue;317}318319if (specialChars1779.indexOf((char)c) < 0) {320throw new IOException321("Invalid escaped character in AVA: " +322(char)c);323}324}325326// add embedded hex bytes before next char327if (embeddedHex.size() > 0) {328String hexString = getEmbeddedHexString(embeddedHex);329temp.append(hexString);330embeddedHex.clear();331}332333// check for non-PrintableString chars334isPrintableString &= DerValue.isPrintableStringChar((char)c);335temp.append((char)c);336c = readChar(in, "Quoted string did not end in quote");337}338339// add trailing embedded hex bytes340if (embeddedHex.size() > 0) {341String hexString = getEmbeddedHexString(embeddedHex);342temp.append(hexString);343embeddedHex.clear();344}345346do {347c = in.read();348} while ((c == '\n') || (c == ' '));349if (c != -1) {350throw new IOException("AVA had characters other than "351+ "whitespace after terminating quote");352}353354// encode as PrintableString unless value contains355// non-PrintableString chars356if (this.oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID) ||357(this.oid.equals(X500Name.DOMAIN_COMPONENT_OID) &&358PRESERVE_OLD_DC_ENCODING == false)) {359// EmailAddress and DomainComponent must be IA5String360return new DerValue(DerValue.tag_IA5String,361temp.toString().trim());362} else if (isPrintableString) {363return new DerValue(temp.toString().trim());364} else {365return new DerValue(DerValue.tag_UTF8String,366temp.toString().trim());367}368}369370private DerValue parseString371(Reader in, int c, int format, StringBuilder temp) throws IOException {372373List<Byte> embeddedHex = new ArrayList<>();374boolean isPrintableString = true;375boolean escape = false;376boolean leadingChar = true;377int spaceCount = 0;378do {379escape = false;380if (c == '\\') {381escape = true;382c = readChar(in, "Invalid trailing backslash");383384// check for embedded hex pairs385Byte hexByte = null;386if ((hexByte = getEmbeddedHexPair(c, in)) != null) {387388// always encode AVAs with embedded hex as UTF8389isPrintableString = false;390391// append consecutive embedded hex392// as single string later393embeddedHex.add(hexByte);394c = in.read();395leadingChar = false;396continue;397}398399// check if character was improperly escaped400if (format == DEFAULT &&401specialCharsDefault.indexOf((char)c) == -1) {402throw new IOException403("Invalid escaped character in AVA: '" +404(char)c + "'");405} else if (format == RFC2253) {406if (c == ' ') {407// only leading/trailing space can be escaped408if (!leadingChar && !trailingSpace(in)) {409throw new IOException410("Invalid escaped space character " +411"in AVA. Only a leading or trailing " +412"space character can be escaped.");413}414} else if (c == '#') {415// only leading '#' can be escaped416if (!leadingChar) {417throw new IOException418("Invalid escaped '#' character in AVA. " +419"Only a leading '#' can be escaped.");420}421} else if (specialChars2253.indexOf((char)c) == -1) {422throw new IOException423("Invalid escaped character in AVA: '" +424(char)c + "'");425}426}427} else {428// check if character should have been escaped429if (format == RFC2253) {430if (specialChars2253.indexOf((char)c) != -1) {431throw new IOException432("Character '" + (char)c +433"' in AVA appears without escape");434}435} else if (escapedDefault.indexOf((char)c) != -1) {436throw new IOException437("Character '" + (char)c +438"' in AVA appears without escape");439}440}441442// add embedded hex bytes before next char443if (embeddedHex.size() > 0) {444// add space(s) before embedded hex bytes445for (int i = 0; i < spaceCount; i++) {446temp.append(' ');447}448spaceCount = 0;449450String hexString = getEmbeddedHexString(embeddedHex);451temp.append(hexString);452embeddedHex.clear();453}454455// check for non-PrintableString chars456isPrintableString &= DerValue.isPrintableStringChar((char)c);457if (c == ' ' && escape == false) {458// do not add non-escaped spaces yet459// (non-escaped trailing spaces are ignored)460spaceCount++;461} else {462// add space(s)463for (int i = 0; i < spaceCount; i++) {464temp.append(' ');465}466spaceCount = 0;467temp.append((char)c);468}469c = in.read();470leadingChar = false;471} while (isTerminator(c, format) == false);472473if (format == RFC2253 && spaceCount > 0) {474throw new IOException("Incorrect AVA RFC2253 format - " +475"trailing space must be escaped");476}477478// add trailing embedded hex bytes479if (embeddedHex.size() > 0) {480String hexString = getEmbeddedHexString(embeddedHex);481temp.append(hexString);482embeddedHex.clear();483}484485// encode as PrintableString unless value contains486// non-PrintableString chars487if (this.oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID) ||488(this.oid.equals(X500Name.DOMAIN_COMPONENT_OID) &&489PRESERVE_OLD_DC_ENCODING == false)) {490// EmailAddress and DomainComponent must be IA5String491return new DerValue(DerValue.tag_IA5String, temp.toString());492} else if (isPrintableString) {493return new DerValue(temp.toString());494} else {495return new DerValue(DerValue.tag_UTF8String, temp.toString());496}497}498499private static Byte getEmbeddedHexPair(int c1, Reader in)500throws IOException {501502if (HexFormat.isHexDigit(c1)) {503int c2 = readChar(in, "unexpected EOF - " +504"escaped hex value must include two valid digits");505506if (HexFormat.isHexDigit(c2)) {507int hi = HexFormat.fromHexDigit(c1);508int lo = HexFormat.fromHexDigit(c2);509return (byte)((hi<<4) + lo);510} else {511throw new IOException512("escaped hex value must include two valid digits");513}514}515return null;516}517518private static String getEmbeddedHexString(List<Byte> hexList) {519int n = hexList.size();520byte[] hexBytes = new byte[n];521for (int i = 0; i < n; i++) {522hexBytes[i] = hexList.get(i).byteValue();523}524return new String(hexBytes, UTF_8);525}526527private static boolean isTerminator(int ch, int format) {528switch (ch) {529case -1:530case '+':531case ',':532return true;533case ';':534return format != RFC2253;535default:536return false;537}538}539540private static int readChar(Reader in, String errMsg) throws IOException {541int c = in.read();542if (c == -1) {543throw new IOException(errMsg);544}545return c;546}547548private static boolean trailingSpace(Reader in) throws IOException {549550boolean trailing = false;551552if (!in.markSupported()) {553// oh well554return true;555} else {556// make readAheadLimit huge -557// in practice, AVA was passed a StringReader from X500Name,558// and StringReader ignores readAheadLimit anyways559in.mark(9999);560while (true) {561int nextChar = in.read();562if (nextChar == -1) {563trailing = true;564break;565} else if (nextChar == ' ') {566continue;567} else if (nextChar == '\\') {568int followingChar = in.read();569if (followingChar != ' ') {570trailing = false;571break;572}573} else {574trailing = false;575break;576}577}578579in.reset();580return trailing;581}582}583584AVA(DerValue derval) throws IOException {585// Individual attribute value assertions are SEQUENCE of two values.586// That'd be a "struct" outside of ASN.1.587if (derval.tag != DerValue.tag_Sequence) {588throw new IOException("AVA not a sequence");589}590oid = derval.data.getOID();591value = derval.data.getDerValue();592593if (derval.data.available() != 0) {594throw new IOException("AVA, extra bytes = "595+ derval.data.available());596}597}598599AVA(DerInputStream in) throws IOException {600this(in.getDerValue());601}602603public boolean equals(Object obj) {604if (this == obj) {605return true;606}607if (obj instanceof AVA == false) {608return false;609}610AVA other = (AVA)obj;611return this.toRFC2253CanonicalString().equals612(other.toRFC2253CanonicalString());613}614615/**616* Returns a hashcode for this AVA.617*618* @return a hashcode for this AVA.619*/620public int hashCode() {621return toRFC2253CanonicalString().hashCode();622}623624/*625* AVAs are encoded as a SEQUENCE of two elements.626*/627public void encode(DerOutputStream out) throws IOException {628derEncode(out);629}630631/**632* DER encode this object onto an output stream.633* Implements the <code>DerEncoder</code> interface.634*635* @param out636* the output stream on which to write the DER encoding.637*638* @exception IOException on encoding error.639*/640public void derEncode(OutputStream out) throws IOException {641DerOutputStream tmp = new DerOutputStream();642DerOutputStream tmp2 = new DerOutputStream();643644tmp.putOID(oid);645value.encode(tmp);646tmp2.write(DerValue.tag_Sequence, tmp);647out.write(tmp2.toByteArray());648}649650private String toKeyword(int format, Map<String, String> oidMap) {651return AVAKeyword.getKeyword(oid, format, oidMap);652}653654/**655* Returns a printable form of this attribute, using RFC 1779656* syntax for individual attribute/value assertions.657*/658public String toString() {659return toKeywordValueString660(toKeyword(DEFAULT, Collections.<String, String>emptyMap()));661}662663/**664* Returns a printable form of this attribute, using RFC 1779665* syntax for individual attribute/value assertions. It only666* emits standardised keywords.667*/668public String toRFC1779String() {669return toRFC1779String(Collections.<String, String>emptyMap());670}671672/**673* Returns a printable form of this attribute, using RFC 1779674* syntax for individual attribute/value assertions. It675* emits standardised keywords, as well as keywords contained in the676* OID/keyword map.677*/678public String toRFC1779String(Map<String, String> oidMap) {679return toKeywordValueString(toKeyword(RFC1779, oidMap));680}681682/**683* Returns a printable form of this attribute, using RFC 2253684* syntax for individual attribute/value assertions. It only685* emits standardised keywords.686*/687public String toRFC2253String() {688return toRFC2253String(Collections.<String, String>emptyMap());689}690691/**692* Returns a printable form of this attribute, using RFC 2253693* syntax for individual attribute/value assertions. It694* emits standardised keywords, as well as keywords contained in the695* OID/keyword map.696*/697public String toRFC2253String(Map<String, String> oidMap) {698/*699* Section 2.3: The AttributeTypeAndValue is encoded as the string700* representation of the AttributeType, followed by an equals character701* ('=' ASCII 61), followed by the string representation of the702* AttributeValue. The encoding of the AttributeValue is given in703* section 2.4.704*/705StringBuilder typeAndValue = new StringBuilder(100);706typeAndValue.append(toKeyword(RFC2253, oidMap));707typeAndValue.append('=');708709/*710* Section 2.4: Converting an AttributeValue from ASN.1 to a String.711* If the AttributeValue is of a type which does not have a string712* representation defined for it, then it is simply encoded as an713* octothorpe character ('#' ASCII 35) followed by the hexadecimal714* representation of each of the bytes of the BER encoding of the X.500715* AttributeValue. This form SHOULD be used if the AttributeType is of716* the dotted-decimal form.717*/718if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9') ||719!isDerString(value, false))720{721byte[] data = null;722try {723data = value.toByteArray();724} catch (IOException ie) {725throw new IllegalArgumentException("DER Value conversion");726}727typeAndValue.append('#');728HexFormat.of().formatHex(typeAndValue, data);729} else {730/*731* 2.4 (cont): Otherwise, if the AttributeValue is of a type which732* has a string representation, the value is converted first to a733* UTF-8 string according to its syntax specification.734*735* NOTE: this implementation only emits DirectoryStrings of the736* types returned by isDerString().737*/738String valStr = null;739try {740valStr = new String(value.getDataBytes(), UTF_8);741} catch (IOException ie) {742throw new IllegalArgumentException("DER Value conversion");743}744745/*746* 2.4 (cont): If the UTF-8 string does not have any of the747* following characters which need escaping, then that string can be748* used as the string representation of the value.749*750* o a space or "#" character occurring at the beginning of the751* string752* o a space character occurring at the end of the string753* o one of the characters ",", "+", """, "\", "<", ">" or ";"754*755* Implementations MAY escape other characters.756*757* NOTE: this implementation also recognizes "=" and "#" as758* characters which need escaping, and null which is escaped as759* '\00' (see RFC 4514).760*761* If a character to be escaped is one of the list shown above, then762* it is prefixed by a backslash ('\' ASCII 92).763*764* Otherwise the character to be escaped is replaced by a backslash765* and two hex digits, which form a single byte in the code of the766* character.767*/768final String escapees = ",=+<>#;\"\\";769StringBuilder sbuffer = new StringBuilder();770771for (int i = 0; i < valStr.length(); i++) {772char c = valStr.charAt(i);773if (DerValue.isPrintableStringChar(c) ||774escapees.indexOf(c) >= 0) {775776// escape escapees777if (escapees.indexOf(c) >= 0) {778sbuffer.append('\\');779}780781// append printable/escaped char782sbuffer.append(c);783784} else if (c == '\u0000') {785// escape null character786sbuffer.append("\\00");787788} else if (debug != null && Debug.isOn("ava")) {789790// embed non-printable/non-escaped char791// as escaped hex pairs for debugging792byte[] valueBytes = Character.toString(c).getBytes(UTF_8);793HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);794} else {795796// append non-printable/non-escaped char797sbuffer.append(c);798}799}800801char[] chars = sbuffer.toString().toCharArray();802sbuffer = new StringBuilder();803804// Find leading and trailing whitespace.805int lead; // index of first char that is not leading whitespace806for (lead = 0; lead < chars.length; lead++) {807if (chars[lead] != ' ' && chars[lead] != '\r') {808break;809}810}811int trail; // index of last char that is not trailing whitespace812for (trail = chars.length - 1; trail >= 0; trail--) {813if (chars[trail] != ' ' && chars[trail] != '\r') {814break;815}816}817818// escape leading and trailing whitespace819for (int i = 0; i < chars.length; i++) {820char c = chars[i];821if (i < lead || i > trail) {822sbuffer.append('\\');823}824sbuffer.append(c);825}826typeAndValue.append(sbuffer);827}828return typeAndValue.toString();829}830831public String toRFC2253CanonicalString() {832/*833* Section 2.3: The AttributeTypeAndValue is encoded as the string834* representation of the AttributeType, followed by an equals character835* ('=' ASCII 61), followed by the string representation of the836* AttributeValue. The encoding of the AttributeValue is given in837* section 2.4.838*/839StringBuilder typeAndValue = new StringBuilder(40);840typeAndValue.append841(toKeyword(RFC2253, Collections.<String, String>emptyMap()));842typeAndValue.append('=');843844/*845* Section 2.4: Converting an AttributeValue from ASN.1 to a String.846* If the AttributeValue is of a type which does not have a string847* representation defined for it, then it is simply encoded as an848* octothorpe character ('#' ASCII 35) followed by the hexadecimal849* representation of each of the bytes of the BER encoding of the X.500850* AttributeValue. This form SHOULD be used if the AttributeType is of851* the dotted-decimal form.852*/853if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9') ||854!isDerString(value, true))855{856byte[] data = null;857try {858data = value.toByteArray();859} catch (IOException ie) {860throw new IllegalArgumentException("DER Value conversion");861}862typeAndValue.append('#');863HexFormat.of().formatHex(typeAndValue, data);864} else {865/*866* 2.4 (cont): Otherwise, if the AttributeValue is of a type which867* has a string representation, the value is converted first to a868* UTF-8 string according to its syntax specification.869*870* NOTE: this implementation only emits DirectoryStrings of the871* types returned by isDerString().872*/873String valStr = null;874try {875valStr = new String(value.getDataBytes(), UTF_8);876} catch (IOException ie) {877throw new IllegalArgumentException("DER Value conversion");878}879880/*881* 2.4 (cont): If the UTF-8 string does not have any of the882* following characters which need escaping, then that string can be883* used as the string representation of the value.884*885* o a space or "#" character occurring at the beginning of the886* string887* o a space character occurring at the end of the string888*889* o one of the characters ",", "+", """, "\", "<", ">" or ";"890*891* If a character to be escaped is one of the list shown above, then892* it is prefixed by a backslash ('\' ASCII 92).893*894* Otherwise the character to be escaped is replaced by a backslash895* and two hex digits, which form a single byte in the code of the896* character.897*/898final String escapees = ",+<>;\"\\";899StringBuilder sbuffer = new StringBuilder();900boolean previousWhite = false;901902for (int i = 0; i < valStr.length(); i++) {903char c = valStr.charAt(i);904905if (DerValue.isPrintableStringChar(c) ||906escapees.indexOf(c) >= 0 ||907(i == 0 && c == '#')) {908909// escape leading '#' and escapees910if ((i == 0 && c == '#') || escapees.indexOf(c) >= 0) {911sbuffer.append('\\');912}913914// convert multiple whitespace to single whitespace915if (!Character.isWhitespace(c)) {916previousWhite = false;917sbuffer.append(c);918} else {919if (previousWhite == false) {920// add single whitespace921previousWhite = true;922sbuffer.append(c);923} else {924// ignore subsequent consecutive whitespace925continue;926}927}928929} else if (debug != null && Debug.isOn("ava")) {930931// embed non-printable/non-escaped char932// as escaped hex pairs for debugging933934previousWhite = false;935byte[] valueBytes = Character.toString(c).getBytes(UTF_8);936HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);937} else {938939// append non-printable/non-escaped char940941previousWhite = false;942sbuffer.append(c);943}944}945946// remove leading and trailing whitespace from value947typeAndValue.append(sbuffer.toString().trim());948}949950String canon = typeAndValue.toString();951canon = canon.toUpperCase(Locale.US).toLowerCase(Locale.US);952return Normalizer.normalize(canon, Normalizer.Form.NFKD);953}954955/*956* Return true if DerValue can be represented as a String.957*/958private static boolean isDerString(DerValue value, boolean canonical) {959if (canonical) {960switch (value.tag) {961case DerValue.tag_PrintableString:962case DerValue.tag_UTF8String:963return true;964default:965return false;966}967} else {968switch (value.tag) {969case DerValue.tag_PrintableString:970case DerValue.tag_T61String:971case DerValue.tag_IA5String:972case DerValue.tag_GeneralString:973case DerValue.tag_BMPString:974case DerValue.tag_UTF8String:975return true;976default:977return false;978}979}980}981982boolean hasRFC2253Keyword() {983return AVAKeyword.hasKeyword(oid, RFC2253);984}985986private String toKeywordValueString(String keyword) {987/*988* Construct the value with as little copying and garbage989* production as practical. First the keyword (mandatory),990* then the equals sign, finally the value.991*/992StringBuilder retval = new StringBuilder(40);993994retval.append(keyword);995retval.append('=');996997try {998String valStr = value.getAsString();9991000if (valStr == null) {10011002// RFC 1779 specifies that attribute values associated1003// with non-standard keyword attributes may be represented1004// using the hex format below. This will be used only1005// when the value is not a string type10061007byte[] data = value.toByteArray();10081009retval.append('#');1010HexFormat.of().formatHex(retval, data);1011} else {10121013boolean quoteNeeded = false;1014StringBuilder sbuffer = new StringBuilder();1015boolean previousWhite = false;1016final String escapees = ",+=\n<>#;\\\"";10171018/*1019* Special characters (e.g. AVA list separators) cause strings1020* to need quoting, or at least escaping. So do leading or1021* trailing spaces, and multiple internal spaces.1022*/1023int length = valStr.length();1024boolean alreadyQuoted =1025(length > 1 && valStr.charAt(0) == '\"'1026&& valStr.charAt(length - 1) == '\"');10271028for (int i = 0; i < length; i++) {1029char c = valStr.charAt(i);1030if (alreadyQuoted && (i == 0 || i == length - 1)) {1031sbuffer.append(c);1032continue;1033}1034if (DerValue.isPrintableStringChar(c) ||1035escapees.indexOf(c) >= 0) {10361037// quote if leading whitespace or special chars1038if (!quoteNeeded &&1039((i == 0 && (c == ' ' || c == '\n')) ||1040escapees.indexOf(c) >= 0)) {1041quoteNeeded = true;1042}10431044// quote if multiple internal whitespace1045if (!(c == ' ' || c == '\n')) {1046// escape '"' and '\'1047if (c == '"' || c == '\\') {1048sbuffer.append('\\');1049}1050previousWhite = false;1051} else {1052if (!quoteNeeded && previousWhite) {1053quoteNeeded = true;1054}1055previousWhite = true;1056}10571058sbuffer.append(c);10591060} else if (debug != null && Debug.isOn("ava")) {10611062// embed non-printable/non-escaped char1063// as escaped hex pairs for debugging10641065previousWhite = false;10661067// embed escaped hex pairs1068byte[] valueBytes =1069Character.toString(c).getBytes(UTF_8);1070HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);1071} else {10721073// append non-printable/non-escaped char10741075previousWhite = false;1076sbuffer.append(c);1077}1078}10791080// quote if trailing whitespace1081if (sbuffer.length() > 0) {1082char trailChar = sbuffer.charAt(sbuffer.length() - 1);1083if (trailChar == ' ' || trailChar == '\n') {1084quoteNeeded = true;1085}1086}10871088// Emit the string ... quote it if needed1089// if string is already quoted, don't re-quote1090if (!alreadyQuoted && quoteNeeded) {1091retval.append('\"')1092.append(sbuffer)1093.append('\"');1094} else {1095retval.append(sbuffer);1096}1097}1098} catch (IOException e) {1099throw new IllegalArgumentException("DER Value conversion");1100}11011102return retval.toString();1103}11041105}11061107/**1108* Helper class that allows conversion from String to ObjectIdentifier and1109* vice versa according to RFC1779, RFC2253, and an augmented version of1110* those standards.1111*/1112class AVAKeyword {11131114private static final Map<ObjectIdentifier,AVAKeyword> oidMap;1115private static final Map<String,AVAKeyword> keywordMap;11161117private String keyword;1118private ObjectIdentifier oid;1119private boolean rfc1779Compliant, rfc2253Compliant;11201121private AVAKeyword(String keyword, ObjectIdentifier oid,1122boolean rfc1779Compliant, boolean rfc2253Compliant) {1123this.keyword = keyword;1124this.oid = oid;1125this.rfc1779Compliant = rfc1779Compliant;1126this.rfc2253Compliant = rfc2253Compliant;11271128// register it1129oidMap.put(oid, this);1130keywordMap.put(keyword, this);1131}11321133private boolean isCompliant(int standard) {1134switch (standard) {1135case AVA.RFC1779:1136return rfc1779Compliant;1137case AVA.RFC2253:1138return rfc2253Compliant;1139case AVA.DEFAULT:1140return true;1141default:1142// should not occur, internal error1143throw new IllegalArgumentException("Invalid standard " + standard);1144}1145}11461147/**1148* Get an object identifier representing the specified keyword (or1149* string encoded object identifier) in the given standard.1150*1151* @param keywordMap a Map where a keyword String maps to a corresponding1152* OID String. Each AVA keyword will be mapped to the corresponding OID.1153* If an entry does not exist, it will fallback to the builtin1154* keyword/OID mapping.1155* @throws IOException If the keyword is not valid in the specified standard1156* or the OID String to which a keyword maps to is improperly formatted.1157*/1158static ObjectIdentifier getOID1159(String keyword, int standard, Map<String, String> extraKeywordMap)1160throws IOException {11611162keyword = keyword.toUpperCase(Locale.ENGLISH);1163if (standard == AVA.RFC2253) {1164if (keyword.startsWith(" ") || keyword.endsWith(" ")) {1165throw new IOException("Invalid leading or trailing space " +1166"in keyword \"" + keyword + "\"");1167}1168} else {1169keyword = keyword.trim();1170}11711172// check user-specified keyword map first, then fallback to built-in1173// map1174String oidString = extraKeywordMap.get(keyword);1175if (oidString == null) {1176AVAKeyword ak = keywordMap.get(keyword);1177if ((ak != null) && ak.isCompliant(standard)) {1178return ak.oid;1179}1180} else {1181return ObjectIdentifier.of(oidString);1182}11831184// no keyword found, check if OID string1185if (standard == AVA.DEFAULT && keyword.startsWith("OID.")) {1186keyword = keyword.substring(4);1187}11881189boolean number = false;1190if (!keyword.isEmpty()) {1191char ch = keyword.charAt(0);1192if ((ch >= '0') && (ch <= '9')) {1193number = true;1194}1195}1196if (number == false) {1197throw new IOException("Invalid keyword \"" + keyword + "\"");1198}1199return ObjectIdentifier.of(keyword);1200}12011202/**1203* Get a keyword for the given ObjectIdentifier according to standard.1204* If no keyword is available, the ObjectIdentifier is encoded as a1205* String.1206*/1207static String getKeyword(ObjectIdentifier oid, int standard) {1208return getKeyword1209(oid, standard, Collections.<String, String>emptyMap());1210}12111212/**1213* Get a keyword for the given ObjectIdentifier according to standard.1214* Checks the extraOidMap for a keyword first, then falls back to the1215* builtin/default set. If no keyword is available, the ObjectIdentifier1216* is encoded as a String.1217*/1218static String getKeyword1219(ObjectIdentifier oid, int standard, Map<String, String> extraOidMap) {12201221// check extraOidMap first, then fallback to built-in map1222String oidString = oid.toString();1223String keywordString = extraOidMap.get(oidString);1224if (keywordString == null) {1225AVAKeyword ak = oidMap.get(oid);1226if ((ak != null) && ak.isCompliant(standard)) {1227return ak.keyword;1228}1229} else {1230if (keywordString.isEmpty()) {1231throw new IllegalArgumentException("keyword cannot be empty");1232}1233keywordString = keywordString.trim();1234char c = keywordString.charAt(0);1235if (c < 65 || c > 122 || (c > 90 && c < 97)) {1236throw new IllegalArgumentException1237("keyword does not start with letter");1238}1239for (int i=1; i<keywordString.length(); i++) {1240c = keywordString.charAt(i);1241if ((c < 65 || c > 122 || (c > 90 && c < 97)) &&1242(c < 48 || c > 57) && c != '_') {1243throw new IllegalArgumentException1244("keyword character is not a letter, digit, or underscore");1245}1246}1247return keywordString;1248}1249// no compliant keyword, use OID1250if (standard == AVA.RFC2253) {1251return oidString;1252} else {1253return "OID." + oidString;1254}1255}12561257/**1258* Test if oid has an associated keyword in standard.1259*/1260static boolean hasKeyword(ObjectIdentifier oid, int standard) {1261AVAKeyword ak = oidMap.get(oid);1262if (ak == null) {1263return false;1264}1265return ak.isCompliant(standard);1266}12671268static {1269oidMap = new HashMap<ObjectIdentifier,AVAKeyword>();1270keywordMap = new HashMap<String,AVAKeyword>();12711272// NOTE if multiple keywords are available for one OID, order1273// is significant!! Preferred *LAST*.1274new AVAKeyword("CN", X500Name.commonName_oid, true, true);1275new AVAKeyword("C", X500Name.countryName_oid, true, true);1276new AVAKeyword("L", X500Name.localityName_oid, true, true);1277new AVAKeyword("S", X500Name.stateName_oid, false, false);1278new AVAKeyword("ST", X500Name.stateName_oid, true, true);1279new AVAKeyword("O", X500Name.orgName_oid, true, true);1280new AVAKeyword("OU", X500Name.orgUnitName_oid, true, true);1281new AVAKeyword("T", X500Name.title_oid, false, false);1282new AVAKeyword("IP", X500Name.ipAddress_oid, false, false);1283new AVAKeyword("STREET", X500Name.streetAddress_oid,true, true);1284new AVAKeyword("DC", X500Name.DOMAIN_COMPONENT_OID,1285false, true);1286new AVAKeyword("DNQUALIFIER", X500Name.DNQUALIFIER_OID, false, false);1287new AVAKeyword("DNQ", X500Name.DNQUALIFIER_OID, false, false);1288new AVAKeyword("SURNAME", X500Name.SURNAME_OID, false, false);1289new AVAKeyword("GIVENNAME", X500Name.GIVENNAME_OID, false, false);1290new AVAKeyword("INITIALS", X500Name.INITIALS_OID, false, false);1291new AVAKeyword("GENERATION", X500Name.GENERATIONQUALIFIER_OID,1292false, false);1293new AVAKeyword("EMAIL", PKCS9Attribute.EMAIL_ADDRESS_OID, false, false);1294new AVAKeyword("EMAILADDRESS", PKCS9Attribute.EMAIL_ADDRESS_OID,1295false, false);1296new AVAKeyword("UID", X500Name.userid_oid, false, true);1297new AVAKeyword("SERIALNUMBER", X500Name.SERIALNUMBER_OID, false, false);1298}1299}130013011302