java.security.PKCS12Attribute: port class from jdk8u60

This class provides facilities to deal with attributes in entries for
PKCS12 keystores.

Test: check-ojluni-files, make droid docs, vogar PKCS12AttributeTest
Bug: 29631070
Change-Id: I8d40fe126f189d503d6df7bfa45c4763bb7cb0d1
diff --git a/luni/src/test/java/libcore/java/security/PKCS12AttributeTest.java b/luni/src/test/java/libcore/java/security/PKCS12AttributeTest.java
new file mode 100644
index 0000000..d77f0e2
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/PKCS12AttributeTest.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package java.security;
+
+import junit.framework.TestCase;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+
+public class PKCS12AttributeTest extends TestCase {
+    private static final String PKCS9_EMAIL_ADDRESS_OID = "1.2.840.113549.1.9.1";
+    private static final String PKCS9_CONTENT_TYPE_OID = "1.2.840.113549.1.9.3";
+    private static final String PKCS7_SIGNED_DATA_OID = "1.2.840.113549.1.7.2";
+    private static final String EXAMPLE_EMAIL_ADDRESS = "someemail@server.com";
+    private static final String EXAMPLE_EMAIL_ADDRESS_2 = "someotheremail@server.com";
+    private static final String EXAMPLE_SEQUENCE_OF_EMAILS =
+            "[" + EXAMPLE_EMAIL_ADDRESS + ", " + EXAMPLE_EMAIL_ADDRESS_2 + "]";
+
+    /*
+     * Encoded attribute obtained using BouncyCastle as an oracle for the known answer:
+     *
+            DERSequence s = new DERSequence(new ASN1Encodable[] {
+                new ASN1ObjectIdentifier("1.2.840.113549.1.9.1"),
+                new DERSet(new ASN1Encodable[] { new DERUTF8String("someemail@server.com") })
+            });
+            System.out.println(Arrays.toString(s.getEncoded()));
+     */
+    private static final byte[] ENCODED_ATTRIBUTE_UTF8_EMAIL_ADDRESS = new byte[] {
+            48, 35, 6, 9, 42, -122, 72, -122, -9, 13, 1, 9, 1, 49, 22, 12, 20, 115, 111, 109,
+            101, 101, 109, 97, 105, 108, 64, 115, 101, 114, 118, 101, 114, 46, 99, 111, 109
+    };
+
+    /*
+     * Encoded attribute obtained using BouncyCastle as an oracle for the known answer:
+     *
+            DERSequence s = new DERSequence(new ASN1Encodable[] {
+                new ASN1ObjectIdentifier("1.2.840.113549.1.9.1"),
+                    new DERSet(new ASN1Encodable[] {
+                        new DEROctetString("someemail@server.com".getBytes())
+                    })
+            });
+            System.out.println(Arrays.toString(s.getEncoded()));
+    */
+    private static final byte[] ENCODED_ATTRIBUTE_OCTET_EMAIL_ADDRESS = new byte[] {
+            48, 35, 6, 9, 42, -122, 72, -122, -9, 13, 1, 9, 1, 49, 22, 4, 20, 115, 111, 109,
+            101, 101, 109, 97, 105, 108, 64, 115, 101, 114, 118, 101, 114, 46, 99, 111, 109
+    };
+
+    /*
+     * Encoded attribute obtained using BouncyCastle as an oracle for the known answer:
+     *
+            DERSequence s = new DERSequence(new ASN1Encodable[] {
+                new ASN1ObjectIdentifier("1.2.840.113549.1.9.1"),
+                new DERSet(new ASN1Encodable[] {
+                    new DERUTF8String("someemail@server.com"),
+                    new DERUTF8String("someotheremail@server.com"),
+                })
+            });
+     */
+    private static final byte[] ENCODED_ATTRIBUTE_SEQUENCE_OF_EMAIL_ADDRESSES = new byte[] {
+            48, 62, 6, 9, 42, -122, 72, -122, -9, 13, 1, 9, 1, 49, 49, 12, 20, 115, 111, 109,
+            101, 101, 109, 97, 105, 108, 64, 115, 101, 114, 118, 101, 114, 46, 99, 111, 109, 12, 25,
+            115, 111, 109, 101, 111, 116, 104, 101, 114, 101, 109, 97, 105, 108, 64, 115, 101,
+            114, 118, 101, 114, 46, 99, 111, 109
+    };
+
+    /*
+     * Encoded attribute obtained using BouncyCastle as an oracle for the known answer:
+     *
+            DERSequence s = new DERSequence(new ASN1Encodable[] {
+                new ASN1ObjectIdentifier("1.2.840.113549.1.9.3"),
+                new DERSet(new ASN1Encodable[] {
+                    new ASN1ObjectIdentifier("1.2.840.113549.1.7.2")
+                })
+            });
+            System.out.println(Arrays.toString(s.getEncoded()));
+    */
+    private static final byte[] ENCODED_ATTRIBUTE_CONTENT_TYPE_SIGNED_DATA = new byte[] {
+            48, 24, 6, 9, 42, -122, 72, -122, -9, 13, 1, 9, 3, 49, 11, 6, 9, 42, -122, 72, -122, -9,
+            13, 1, 7, 2
+    };
+
+    /*
+      echo -n 'someemail@server.com' | recode ../x1 | tr $'\x0a' ' ' \
+          | sed 's/, /:/g' | sed 's/0x//g'
+     */
+    private static final String EXAMPLE_EMAIL_AS_HEX_BYTES =
+            "73:6F:6D:65:65:6D:61:69:6C:40:73:65:72:76:65:72:2E:63:6F:6D";
+
+    public void test_Constructor_String_String_success() {
+        PKCS12Attribute att = new PKCS12Attribute(PKCS9_EMAIL_ADDRESS_OID, EXAMPLE_EMAIL_ADDRESS);
+        assertEquals(PKCS9_EMAIL_ADDRESS_OID, att.getName());
+        assertEquals(EXAMPLE_EMAIL_ADDRESS, att.getValue());
+    }
+
+    public void test_Constructor_String_String_nullOID_throwsException() {
+        try {
+            new PKCS12Attribute(null, EXAMPLE_EMAIL_ADDRESS);
+            fail("Constructor allowed a null OID");
+        } catch(NullPointerException expected) {
+        }
+    }
+
+    public void test_Constructor_String_String_nullValue_throwsException() {
+        try {
+            new PKCS12Attribute(PKCS9_EMAIL_ADDRESS_OID, null);
+            fail("Constructor allowed a null value");
+        } catch(NullPointerException expected) {
+        }
+    }
+
+    public void test_Constructor_String_String_wrongOID_throwsException() {
+        try {
+            PKCS12Attribute att =
+                    new PKCS12Attribute("IDontThinkThisIsAnOID", EXAMPLE_EMAIL_ADDRESS);
+            fail("Constructor allowed an invalid OID");
+        } catch(IllegalArgumentException expected) {
+        }
+    }
+
+    public void test_Constructor_byteArray_success() {
+        PKCS12Attribute att = new PKCS12Attribute(ENCODED_ATTRIBUTE_UTF8_EMAIL_ADDRESS);
+        assertEquals(PKCS9_EMAIL_ADDRESS_OID, att.getName());
+        assertEquals(EXAMPLE_EMAIL_ADDRESS, att.getValue());
+    }
+
+    public void testConstructor_byteArray_nullEncoded_throwsException() {
+        try {
+            new PKCS12Attribute(null);
+            fail("Constructor accepted null encoded value");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void test_Constructor_byteArray_wrongEncoding_throwsException() {
+        try {
+            new PKCS12Attribute(new byte[]{3, 14, 16});
+            fail("Constructor accepted invalid encoding");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    public void test_Constructor_String_String_sequenceValue() {
+        PKCS12Attribute att = new PKCS12Attribute(
+                PKCS9_EMAIL_ADDRESS_OID, EXAMPLE_SEQUENCE_OF_EMAILS);
+        assertEquals(PKCS9_EMAIL_ADDRESS_OID, att.getName());
+        assertEquals(EXAMPLE_SEQUENCE_OF_EMAILS, att.getValue());
+        assertEquals(Arrays.toString(ENCODED_ATTRIBUTE_SEQUENCE_OF_EMAIL_ADDRESSES),
+                Arrays.toString(att.getEncoded()));
+    }
+
+    public void test_Constructor_String_String_hexValues() {
+        PKCS12Attribute att = new PKCS12Attribute(
+                PKCS9_EMAIL_ADDRESS_OID, EXAMPLE_EMAIL_AS_HEX_BYTES);
+        assertEquals(PKCS9_EMAIL_ADDRESS_OID, att.getName());
+        assertEquals(EXAMPLE_EMAIL_AS_HEX_BYTES, att.getValue());
+        // When specified as hex bytes, the underlying encoding is a DER octet string.
+        assertEquals(Arrays.toString(ENCODED_ATTRIBUTE_OCTET_EMAIL_ADDRESS),
+                Arrays.toString(att.getEncoded()));
+    }
+
+    public void test_Equals() {
+        PKCS12Attribute att = new PKCS12Attribute(
+                PKCS9_EMAIL_ADDRESS_OID, EXAMPLE_EMAIL_ADDRESS);
+        assertTrue(att.equals(att));
+        assertFalse(att.equals(new Object()));
+        assertFalse(att.equals(null));
+        assertTrue(att.equals(new PKCS12Attribute(ENCODED_ATTRIBUTE_UTF8_EMAIL_ADDRESS)));
+        assertFalse(att.equals(
+                new PKCS12Attribute(ENCODED_ATTRIBUTE_SEQUENCE_OF_EMAIL_ADDRESSES)));
+    }
+
+    /* Test the case in which the value encoded is an object id.*/
+    public void test_encoding_ObjectIdValue() {
+        PKCS12Attribute att = new PKCS12Attribute(ENCODED_ATTRIBUTE_CONTENT_TYPE_SIGNED_DATA);
+        assertEquals(PKCS9_CONTENT_TYPE_OID, att.getName());
+        /* Value is correctly decoded to a string. */
+        assertEquals(PKCS7_SIGNED_DATA_OID, att.getValue());
+    }
+}
diff --git a/ojluni/src/main/java/java/security/PKCS12Attribute.java b/ojluni/src/main/java/java/security/PKCS12Attribute.java
new file mode 100644
index 0000000..e389862
--- /dev/null
+++ b/ojluni/src/main/java/java/security/PKCS12Attribute.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.security;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.regex.Pattern;
+import sun.security.util.*;
+
+/**
+ * An attribute associated with a PKCS12 keystore entry.
+ * The attribute name is an ASN.1 Object Identifier and the attribute
+ * value is a set of ASN.1 types.
+ *
+ * @since 1.8
+ */
+public final class PKCS12Attribute implements KeyStore.Entry.Attribute {
+
+    private static final Pattern COLON_SEPARATED_HEX_PAIRS =
+        Pattern.compile("^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2})+$");
+    private String name;
+    private String value;
+    private byte[] encoded;
+    private int hashValue = -1;
+
+    /**
+     * Constructs a PKCS12 attribute from its name and value.
+     * The name is an ASN.1 Object Identifier represented as a list of
+     * dot-separated integers.
+     * A string value is represented as the string itself.
+     * A binary value is represented as a string of colon-separated
+     * pairs of hexadecimal digits.
+     * Multi-valued attributes are represented as a comma-separated
+     * list of values, enclosed in square brackets. See
+     * {@link Arrays#toString(java.lang.Object[])}.
+     * <p>
+     * A string value will be DER-encoded as an ASN.1 UTF8String and a
+     * binary value will be DER-encoded as an ASN.1 Octet String.
+     *
+     * @param name the attribute's identifier
+     * @param value the attribute's value
+     *
+     * @exception NullPointerException if {@code name} or {@code value}
+     *     is {@code null}
+     * @exception IllegalArgumentException if {@code name} or
+     *     {@code value} is incorrectly formatted
+     */
+    public PKCS12Attribute(String name, String value) {
+        if (name == null || value == null) {
+            throw new NullPointerException();
+        }
+        // Validate name
+        ObjectIdentifier type;
+        try {
+            type = new ObjectIdentifier(name);
+        } catch (IOException e) {
+            throw new IllegalArgumentException("Incorrect format: name", e);
+        }
+        this.name = name;
+
+        // Validate value
+        int length = value.length();
+        String[] values;
+        if (value.charAt(0) == '[' && value.charAt(length - 1) == ']') {
+            values = value.substring(1, length - 1).split(", ");
+        } else {
+            values = new String[]{ value };
+        }
+        this.value = value;
+
+        try {
+            this.encoded = encode(type, values);
+        } catch (IOException e) {
+            throw new IllegalArgumentException("Incorrect format: value", e);
+        }
+    }
+
+    /**
+     * Constructs a PKCS12 attribute from its ASN.1 DER encoding.
+     * The DER encoding is specified by the following ASN.1 definition:
+     * <pre>
+     *
+     * Attribute ::= SEQUENCE {
+     *     type   AttributeType,
+     *     values SET OF AttributeValue
+     * }
+     * AttributeType ::= OBJECT IDENTIFIER
+     * AttributeValue ::= ANY defined by type
+     *
+     * </pre>
+     *
+     * @param encoded the attribute's ASN.1 DER encoding. It is cloned
+     *     to prevent subsequent modificaion.
+     *
+     * @exception NullPointerException if {@code encoded} is
+     *     {@code null}
+     * @exception IllegalArgumentException if {@code encoded} is
+     *     incorrectly formatted
+     */
+    public PKCS12Attribute(byte[] encoded) {
+        if (encoded == null) {
+            throw new NullPointerException();
+        }
+        this.encoded = encoded.clone();
+
+        try {
+            parse(encoded);
+        } catch (IOException e) {
+            throw new IllegalArgumentException("Incorrect format: encoded", e);
+        }
+    }
+
+    /**
+     * Returns the attribute's ASN.1 Object Identifier represented as a
+     * list of dot-separated integers.
+     *
+     * @return the attribute's identifier
+     */
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Returns the attribute's ASN.1 DER-encoded value as a string.
+     * An ASN.1 DER-encoded value is returned in one of the following
+     * {@code String} formats:
+     * <ul>
+     * <li> the DER encoding of a basic ASN.1 type that has a natural
+     *      string representation is returned as the string itself.
+     *      Such types are currently limited to BOOLEAN, INTEGER,
+     *      OBJECT IDENTIFIER, UTCTime, GeneralizedTime and the
+     *      following six ASN.1 string types: UTF8String,
+     *      PrintableString, T61String, IA5String, BMPString and
+     *      GeneralString.
+     * <li> the DER encoding of any other ASN.1 type is not decoded but
+     *      returned as a binary string of colon-separated pairs of
+     *      hexadecimal digits.
+     * </ul>
+     * Multi-valued attributes are represented as a comma-separated
+     * list of values, enclosed in square brackets. See
+     * {@link Arrays#toString(java.lang.Object[])}.
+     *
+     * @return the attribute value's string encoding
+     */
+    @Override
+    public String getValue() {
+        return value;
+    }
+
+    /**
+     * Returns the attribute's ASN.1 DER encoding.
+     *
+     * @return a clone of the attribute's DER encoding
+     */
+    public byte[] getEncoded() {
+        return encoded.clone();
+    }
+
+    /**
+     * Compares this {@code PKCS12Attribute} and a specified object for
+     * equality.
+     *
+     * @param obj the comparison object
+     *
+     * @return true if {@code obj} is a {@code PKCS12Attribute} and
+     * their DER encodings are equal.
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof PKCS12Attribute)) {
+            return false;
+        }
+        return Arrays.equals(encoded, ((PKCS12Attribute) obj).getEncoded());
+    }
+
+    /**
+     * Returns the hashcode for this {@code PKCS12Attribute}.
+     * The hash code is computed from its DER encoding.
+     *
+     * @return the hash code
+     */
+    @Override
+    public int hashCode() {
+        if (hashValue == -1) {
+            Arrays.hashCode(encoded);
+        }
+        return hashValue;
+    }
+
+    /**
+     * Returns a string representation of this {@code PKCS12Attribute}.
+     *
+     * @return a name/value pair separated by an 'equals' symbol
+     */
+    @Override
+    public String toString() {
+        return (name + "=" + value);
+    }
+
+    private byte[] encode(ObjectIdentifier type, String[] values)
+            throws IOException {
+        DerOutputStream attribute = new DerOutputStream();
+        attribute.putOID(type);
+        DerOutputStream attrContent = new DerOutputStream();
+        for (String value : values) {
+            if (COLON_SEPARATED_HEX_PAIRS.matcher(value).matches()) {
+                byte[] bytes =
+                    new BigInteger(value.replace(":", ""), 16).toByteArray();
+                if (bytes[0] == 0) {
+                    bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
+                }
+                attrContent.putOctetString(bytes);
+            } else {
+                attrContent.putUTF8String(value);
+            }
+        }
+        attribute.write(DerValue.tag_Set, attrContent);
+        DerOutputStream attributeValue = new DerOutputStream();
+        attributeValue.write(DerValue.tag_Sequence, attribute);
+
+        return attributeValue.toByteArray();
+    }
+
+    private void parse(byte[] encoded) throws IOException {
+        DerInputStream attributeValue = new DerInputStream(encoded);
+        DerValue[] attrSeq = attributeValue.getSequence(2);
+        ObjectIdentifier type = attrSeq[0].getOID();
+        DerInputStream attrContent =
+            new DerInputStream(attrSeq[1].toByteArray());
+        DerValue[] attrValueSet = attrContent.getSet(1);
+        String[] values = new String[attrValueSet.length];
+        String printableString;
+        for (int i = 0; i < attrValueSet.length; i++) {
+            if (attrValueSet[i].tag == DerValue.tag_OctetString) {
+                values[i] = Debug.toString(attrValueSet[i].getOctetString());
+            } else if ((printableString = attrValueSet[i].getAsString())
+                != null) {
+                values[i] = printableString;
+            } else if (attrValueSet[i].tag == DerValue.tag_ObjectId) {
+                values[i] = attrValueSet[i].getOID().toString();
+            } else if (attrValueSet[i].tag == DerValue.tag_GeneralizedTime) {
+                values[i] = attrValueSet[i].getGeneralizedTime().toString();
+            } else if (attrValueSet[i].tag == DerValue.tag_UtcTime) {
+                values[i] = attrValueSet[i].getUTCTime().toString();
+            } else if (attrValueSet[i].tag == DerValue.tag_Integer) {
+                values[i] = attrValueSet[i].getBigInteger().toString();
+            } else if (attrValueSet[i].tag == DerValue.tag_Boolean) {
+                values[i] = String.valueOf(attrValueSet[i].getBoolean());
+            } else {
+                values[i] = Debug.toString(attrValueSet[i].getDataBytes());
+            }
+        }
+
+        this.name = type.toString();
+        this.value = values.length == 1 ? values[0] : Arrays.toString(values);
+    }
+}
diff --git a/openjdk_java_files.mk b/openjdk_java_files.mk
index 1238d5a..89ae10f 100644
--- a/openjdk_java_files.mk
+++ b/openjdk_java_files.mk
@@ -610,6 +610,7 @@
     ojluni/src/main/java/java/security/MessageDigestSpi.java \
     ojluni/src/main/java/java/security/NoSuchAlgorithmException.java \
     ojluni/src/main/java/java/security/NoSuchProviderException.java \
+    ojluni/src/main/java/java/security/PKCS12Attribute.java \
     ojluni/src/main/java/java/security/PermissionCollection.java \
     ojluni/src/main/java/java/security/Permission.java \
     ojluni/src/main/java/java/security/Permissions.java \