Merge "Delete test that depends on an external server."
diff --git a/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumMapTest.golden.ser b/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumMapTest.golden.ser
index 76f7668..8151214 100644
--- a/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumMapTest.golden.ser
+++ b/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumMapTest.golden.ser
Binary files differ
diff --git a/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumSetTest.golden.ser b/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumSetTest.golden.ser
index 66040e5..5271090 100644
--- a/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumSetTest.golden.ser
+++ b/harmony-tests/src/test/resources/serialization/org/apache/harmony/tests/java/util/EnumSetTest.golden.ser
Binary files differ
diff --git a/luni/src/main/java/java/io/File.java b/luni/src/main/java/java/io/File.java
index 123109b..9b98ecb 100644
--- a/luni/src/main/java/java/io/File.java
+++ b/luni/src/main/java/java/io/File.java
@@ -411,15 +411,10 @@
* if an I/O error occurs.
*/
public String getCanonicalPath() throws IOException {
- return realpath(getAbsolutePath());
+ return canonicalizePath(getAbsolutePath());
}
- /**
- * TODO: move this stuff to libcore.os.
- * @hide
- */
- private static native String realpath(String path);
- private static native String readlink(String path);
+ private static native String canonicalizePath(String path);
/**
* Returns a new file created using the canonical path of this file.
diff --git a/luni/src/main/java/java/nio/NIOAccess.java b/luni/src/main/java/java/nio/NIOAccess.java
index 12af44d..ddb102e 100644
--- a/luni/src/main/java/java/nio/NIOAccess.java
+++ b/luni/src/main/java/java/nio/NIOAccess.java
@@ -24,17 +24,11 @@
/**
* Returns the underlying native pointer to the data of the given
* Buffer starting at the Buffer's current position, or 0 if the
- * Buffer is not backed by native heap storage. Note that this is
- * different than what the Harmony implementation calls a "base
- * address."
- *
- * @param b the Buffer to be queried
- * @return the native pointer to the Buffer's data at its current
- * position, or 0 if there is none
+ * Buffer is not backed by native heap storage.
*/
static long getBasePointer(Buffer b) {
long address = b.effectiveDirectAddress;
- if (address == 0) {
+ if (address == 0L) {
return 0L;
}
return address + (b.position << b._elementSizeShift);
@@ -43,10 +37,6 @@
/**
* Returns the underlying Java array containing the data of the
* given Buffer, or null if the Buffer is not backed by a Java array.
- *
- * @param b the Buffer to be queried
- * @return the Java array containing the Buffer's data, or null if
- * there is none
*/
static Object getBaseArray(Buffer b) {
return b.hasArray() ? b.array() : null;
@@ -58,9 +48,6 @@
* the actual start of the data. The start of the data takes into
* account the Buffer's current position. This method is only
* meaningful if getBaseArray() returns non-null.
- *
- * @param b the Buffer to be queried
- * @return the data offset in bytes to the start of this Buffer's data
*/
static int getBaseArrayOffset(Buffer b) {
return b.hasArray() ? ((b.arrayOffset() + b.position) << b._elementSizeShift) : 0;
diff --git a/luni/src/main/java/java/security/Security.java b/luni/src/main/java/java/security/Security.java
index 1228b9e..81bafbd 100644
--- a/luni/src/main/java/java/security/Security.java
+++ b/luni/src/main/java/java/security/Security.java
@@ -73,10 +73,9 @@
// Register default providers
private static void registerDefaultProviders() {
secprops.put("security.provider.1", "com.android.org.conscrypt.OpenSSLProvider");
- secprops.put("security.provider.2", "org.apache.harmony.security.provider.cert.DRLCertFactory");
- secprops.put("security.provider.3", "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider");
- secprops.put("security.provider.4", "org.apache.harmony.security.provider.crypto.CryptoProvider");
- secprops.put("security.provider.5", "com.android.org.conscrypt.JSSEProvider");
+ secprops.put("security.provider.2", "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider");
+ secprops.put("security.provider.3", "org.apache.harmony.security.provider.crypto.CryptoProvider");
+ secprops.put("security.provider.4", "com.android.org.conscrypt.JSSEProvider");
}
/**
diff --git a/luni/src/main/java/java/security/security.properties b/luni/src/main/java/java/security/security.properties
index dd5830d..a06283b 100644
--- a/luni/src/main/java/java/security/security.properties
+++ b/luni/src/main/java/java/security/security.properties
@@ -20,13 +20,11 @@
#
# Android's provider of OpenSSL backed implementations
security.provider.1=com.android.org.conscrypt.OpenSSLProvider
-# Favor Harmony's CertificateFactory.X509 over BouncyCastle's
-security.provider.2=org.apache.harmony.security.provider.cert.DRLCertFactory
# Android's stripped down BouncyCastle provider
-security.provider.3=com.android.org.bouncycastle.jce.provider.BouncyCastleProvider
+security.provider.2=com.android.org.bouncycastle.jce.provider.BouncyCastleProvider
# Remaining Harmony providers
-security.provider.4=org.apache.harmony.security.provider.crypto.CryptoProvider
-security.provider.5=com.android.org.conscrypt.JSSEProvider
+security.provider.3=org.apache.harmony.security.provider.crypto.CryptoProvider
+security.provider.4=com.android.org.conscrypt.JSSEProvider
diff --git a/luni/src/main/java/libcore/icu/NativeCollation.java b/luni/src/main/java/libcore/icu/NativeCollation.java
index 0373fef..64e0278 100644
--- a/luni/src/main/java/libcore/icu/NativeCollation.java
+++ b/luni/src/main/java/libcore/icu/NativeCollation.java
@@ -23,7 +23,7 @@
public static native void closeCollator(long address);
public static native int compare(long address, String source, String target);
public static native int getAttribute(long address, int type);
- public static native int getCollationElementIterator(long address, String source);
+ public static native long getCollationElementIterator(long address, String source);
public static native String getRules(long address);
public static native byte[] getSortKey(long address, String source);
public static native long openCollator(String locale);
diff --git a/luni/src/main/java/libcore/io/BlockGuardOs.java b/luni/src/main/java/libcore/io/BlockGuardOs.java
index 411337a..05a756f 100644
--- a/luni/src/main/java/libcore/io/BlockGuardOs.java
+++ b/luni/src/main/java/libcore/io/BlockGuardOs.java
@@ -175,6 +175,11 @@
return os.poll(fds, timeoutMs);
}
+ @Override public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.posix_fallocate(fd, offset, length);
+ }
+
@Override public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.pread(fd, buffer, offset);
@@ -205,6 +210,11 @@
return os.read(fd, bytes, byteOffset, byteCount);
}
+ @Override public String readlink(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.readlink(path);
+ }
+
@Override public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.readv(fd, buffers, offsets, byteCounts);
diff --git a/luni/src/main/java/libcore/io/ForwardingOs.java b/luni/src/main/java/libcore/io/ForwardingOs.java
index 3800416..64734a0 100644
--- a/luni/src/main/java/libcore/io/ForwardingOs.java
+++ b/luni/src/main/java/libcore/io/ForwardingOs.java
@@ -98,12 +98,14 @@
public FileDescriptor open(String path, int flags, int mode) throws ErrnoException { return os.open(path, flags, mode); }
public FileDescriptor[] pipe() throws ErrnoException { return os.pipe(); }
public int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException { return os.poll(fds, timeoutMs); }
+ public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException { os.posix_fallocate(fd, offset, length); }
public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException { return os.pread(fd, buffer, offset); }
public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException { return os.pread(fd, bytes, byteOffset, byteCount, offset); }
public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException { return os.pwrite(fd, buffer, offset); }
public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException { return os.pwrite(fd, bytes, byteOffset, byteCount, offset); }
public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException { return os.read(fd, buffer); }
public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException { return os.read(fd, bytes, byteOffset, byteCount); }
+ public String readlink(String path) throws ErrnoException { return os.readlink(path); }
public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException { return os.readv(fd, buffers, offsets, byteCounts); }
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return os.recvfrom(fd, buffer, flags, srcAddress); }
public int recvfrom(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return os.recvfrom(fd, bytes, byteOffset, byteCount, flags, srcAddress); }
diff --git a/luni/src/main/java/libcore/io/Os.java b/luni/src/main/java/libcore/io/Os.java
index 2b68027..426f2c1 100644
--- a/luni/src/main/java/libcore/io/Os.java
+++ b/luni/src/main/java/libcore/io/Os.java
@@ -91,12 +91,14 @@
public FileDescriptor[] pipe() throws ErrnoException;
/* TODO: if we used the non-standard ppoll(2) behind the scenes, we could take a long timeout. */
public int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException;
+ public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException;
public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException;
public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException;
public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException;
public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException;
public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException;
public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException;
+ public String readlink(String path) throws ErrnoException;
public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException;
public int recvfrom(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException;
diff --git a/luni/src/main/java/libcore/io/Posix.java b/luni/src/main/java/libcore/io/Posix.java
index b99941c..35d3784 100644
--- a/luni/src/main/java/libcore/io/Posix.java
+++ b/luni/src/main/java/libcore/io/Posix.java
@@ -92,6 +92,7 @@
public native FileDescriptor open(String path, int flags, int mode) throws ErrnoException;
public native FileDescriptor[] pipe() throws ErrnoException;
public native int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException;
+ public native void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException;
public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
if (buffer.isDirect()) {
return preadBytes(fd, buffer, buffer.position(), buffer.remaining(), offset);
@@ -128,6 +129,7 @@
return readBytes(fd, bytes, byteOffset, byteCount);
}
private native int readBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException;
+ public native String readlink(String path) throws ErrnoException;
public native int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException {
if (buffer.isDirect()) {
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
deleted file mode 100644
index a2c5b4c..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.util.Arrays;
-
-/**
- * The caching mechanism designed to speed up the process
- * of Certificates/CRLs generation in the case of their repeated
- * generation.
- *
- * It keeps correspondences between Objects (Certificates or CLRs)
- * and arrays of bytes on the base of which the Objects have been generated,
- * and provides the means to determine whether it contains the object built on
- * the base of particular encoded form or not. If there are such
- * objects they are returned from the cache, if not - newly generated
- * objects can be saved in the cache.<br>
- *
- * The process of Certificate/CRL generation
- * (implemented in <code>X509CertFactoryImpl</code>) is accompanied with
- * prereading of the beginning of encoded form. This prefix is used to determine
- * whether provided form is PEM encoding or not.<br>
- *
- * So the use of the prefix is the first point to (approximately)
- * determine whether object to be generated is in the cache or not.
- *
- * The failure of the predetermination process tells us that there were not
- * object generated from the encoded form with such prefix and we should
- * generate (decode) the object. If predetermination is successful,
- * we conduct the accurate search on the base of whole encoded form. <br>
- *
- * So to speed up the object generation process this caching mechanism provides
- * the following functionality:<br>
- *
- * 1. With having of the beginning of the encoded form (prefix)
- * it is possible to predetermine whether object has already been
- * generated on the base of the encoding with the SIMILAR prefix or not.
- * This process is not computationally expensive and takes a little time.
- * But it prevents us from use of expensive full encoding
- * search in the case of its failure.<br>
- *
- * 2. If predetermination ends with success, the whole encoding
- * form should be provided to make the final answer: whether object has
- * already been generated on the base of this PARTICULAR encoded form or not.
- * If it is so - the cached object is returned from the cache,
- * if not - new object should be generated and saved in the cache.<br>
- *
- * Note: The length of the prefixes of the encoded forms should not be
- * less than correspondence (default value is 28).
- */
-public class Cache {
-
- // Hash code consist of 6 bytes: AABB00
- // where:
- // AA - 2 bytes for prefix hash
- // value generated on the base of the prefix of encoding
- // BB - 2 bytes for tail hash
- // value generated on the base of the tail of encoding
- // 00 - 2 reserved bytes equals to 0
- //
- // Note, that it is possible for 2 different arrays to have
- // the similar hash codes.
-
- // The masks to work with hash codes:
- // the hash code without the reserved bytes
- private static final long HASH_MASK = 0xFFFFFFFFFFFF0000L;
- // the hash code of the prefix
- private static final long PREFIX_HASH_MASK = 0xFFFFFFFF00000000L;
- // the index value contained in reserved bytes
- private static final int INDEX_MASK = 0x00FFFF;
-
- // size of the cache
- private final int cache_size;
- // the number of bytes which will be used for array hash generation.
- private final int prefix_size;
-
- // The following 3 arrays contain the information about cached objects.
- // This information includes: hash of the array, encoded form of the object,
- // and the object itself.
- // The hash-encoding-object correspondence is made by means of index
- // in the particular array. I.e. for index N hash contained in hashes[N]
- // corresponds to the encoding contained in encodings[N] which corresponds
- // to the object cached at cache[N]
-
- // array containing the hash codes of encodings
- private final long[] hashes;
- // array containing the encodings of the cached objects
- private final byte[][] encodings;
- // array containing the cached objects
- private final Object[] cache;
-
- // This array is used to speed up the process of the search in the cache.
- // This is an ordered array of the hash codes from 'hashes' array (described
- // above) with last 2 (reserved) bytes equals to the index of
- // the hash in the 'hashes' array. I.e. hash code ABCD00 with index 10 in
- // the hashes array will be represented in this array as ABCD0A (10==0x0A)
- // So this array contains ordered <hash to index> correspondences.
- // Note, that every item in this array is unique.
- private final long[] hashes_idx;
-
- // the index of the last cached object
- private int last_cached = 0;
- // cache population indicator
- private boolean cache_is_full = false;
-
- /**
- * Creates the Cache object.
- * @param pref_size specifies how many leading/trailing bytes of object's
- * encoded form will be used for hash computation
- * @param size capacity of the cache to be created.
- */
- public Cache(int pref_size, int size) {
- cache_size = size;
- prefix_size = pref_size;
- hashes = new long[cache_size];
- hashes_idx = new long[cache_size];
- encodings = new byte[cache_size][];
- cache = new Object[cache_size];
- }
-
- /**
- * Creates the Cache object of size of 9.
- * @param pref_size specifies how many leading/trailing bytes of object's
- * encoded form will be used for hash computation
- */
- public Cache(int pref_size) {
- this(pref_size, 9);
- }
-
- /**
- * Creates the Cache object of size of 9.
- */
- public Cache() {
- this(28, 9);
- }
-
- /**
- * Returns the hash code for the array. This code is used to
- * predetermine whether the object was built on the base of the
- * similar encoding or not (by means of <code>contains(long)</code> method),
- * to exactly determine whether object is contained in the cache or not,
- * and to put the object in the cache.
- * Note: parameter array should be of length not less than
- * specified by <code>prefix_size</code> (default 28)
- * @param arr the byte array containing at least prefix_size leading bytes
- * of the encoding.
- * @return hash code for specified encoding prefix
- */
- public long getHash(byte[] arr) {
- long hash = 0;
- for (int i=1; i<prefix_size; i++) {
- hash += (arr[i] & 0xFF);
- } // it takes about 2 bytes for prefix_size == 28
-
- // shift to the correct place
- hash = hash << 32;
- return hash;
- }
-
- /**
- * Checks if there are any object in the cache generated
- * on the base of encoding with prefix corresponding
- * to the specified hash code.
- * @param prefix_hash the hash code for the prefix
- * of the encoding (retrieved by method <code>getHash(byte[]))</code>
- * @return false if there were not any object generated
- * on the base of encoding with specified hash code, true
- * otherwise.
- */
- public boolean contains(long prefix_hash) {
- if (prefix_hash == 0) {
- return false;
- }
- int idx = -1*Arrays.binarySearch(hashes_idx, prefix_hash)-1;
- if (idx == cache_size) {
- return false;
- } else {
- return (hashes_idx[idx] & PREFIX_HASH_MASK) == prefix_hash;
- }
- }
-
- /**
- * Returns the object built on the base on the specified encoded
- * form if it is contained in the cache and null otherwise.
- * This method is computationally expensive and should be called only if
- * the method <code>contains(long)</code> for the hash code returned true.
- * @param hash the hash code for the prefix of the encoding
- * (retrieved by method <code>getHash(byte[])</code>)
- * @param encoding encoded form of the required object.
- * @return the object corresponding to specified encoding or null if
- * there is no such correspondence.
- */
- public Object get(long hash, byte[] encoding) {
- hash |= getSuffHash(encoding);
- if (hash == 0) {
- return null;
- }
- int idx = -1*Arrays.binarySearch(hashes_idx, hash)-1;
- if (idx == cache_size) {
- return null;
- }
- while ((hashes_idx[idx] & HASH_MASK) == hash) {
- int i = (int) (hashes_idx[idx] & INDEX_MASK) - 1;
- if (Arrays.equals(encoding, encodings[i])) {
- return cache[i];
- }
- idx++;
- if (idx == cache_size) {
- return null;
- }
- }
- return null;
- }
-
- /**
- * Puts the object into the cache.
- * @param hash hash code for the prefix of the encoding
- * @param encoding the encoded form of the object
- * @param object the object to be saved in the cache
- */
- public void put(long hash, byte[] encoding, Object object) {
- // check for empty space in the cache
- if (last_cached == cache_size) {
- // so cache is full, will erase the first entry in the
- // cache (oldest entry). it could be better to throw out
- // rarely used value instead of oldest one..
- last_cached = 0;
- cache_is_full = true;
- }
- // index pointing to the item of the table to be overwritten
- int index = last_cached++;
-
- // improve the hash value with info from the tail of encoding
- hash |= getSuffHash(encoding);
-
- if (cache_is_full) {
- // indexing hash value to be overwritten:
- long idx_hash = (hashes[index] | (index+1));
- int idx = Arrays.binarySearch(hashes_idx, idx_hash);
- if (idx < 0) {
- // it will never happen because we use saved hash value
- // (hashes[index])
- System.out.println("WARNING! "+idx);
- idx = -(idx + 1);
- }
- long new_hash_idx = (hash | (index + 1));
- int new_idx = Arrays.binarySearch(hashes_idx, new_hash_idx);
- if (new_idx >= 0) {
- // it's possible when we write the same hash in the same cell
- if (idx != new_idx) {
- // it will never happen because we use the same
- // hash and the same index in hash table
- System.out.println("WARNING: ");
- System.out.println(">> idx: "+idx+" new_idx: "+new_idx);
- }
- } else {
- new_idx = -(new_idx + 1);
- // replace in sorted array
- if (new_idx > idx) {
- System.arraycopy(hashes_idx, idx+1, hashes_idx, idx,
- new_idx - idx - 1);
- hashes_idx[new_idx-1] = new_hash_idx;
- } else if (idx > new_idx) {
- System.arraycopy(hashes_idx, new_idx, hashes_idx, new_idx+1,
- idx - new_idx);
- hashes_idx[new_idx] = new_hash_idx;
- } else { // idx == new_idx
- hashes_idx[new_idx] = new_hash_idx;
- }
- }
- } else {
- long idx_hash = (hash | (index + 1));
- int idx = Arrays.binarySearch(hashes_idx, idx_hash);
- if (idx < 0) {
- // it will always be true because idx_hash depends on index
- idx = -(idx + 1);
- }
- idx = idx - 1;
- if (idx != cache_size - index - 1) {
- // if not in the cell containing 0 (free cell), do copy:
- System.arraycopy(hashes_idx, cache_size - index,
- hashes_idx, cache_size - index - 1,
- idx - (cache_size - index) + 1);
- }
- hashes_idx[idx] = idx_hash;
- }
- // overwrite the values in the tables:
- hashes[index] = hash;
- encodings[index] = encoding;
- cache[index] = object;
- }
-
- // Returns the hash code built on the base of the tail of the encoded form
- // @param arr - the array containing at least prefix_size trailing bytes
- // of encoded form
- private long getSuffHash(byte[] arr) {
- long hash_addon = 0;
- for (int i=arr.length-1; i>arr.length - prefix_size; i--) {
- hash_addon += (arr[i] & 0xFF);
- }
- return hash_addon << 16;
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
deleted file mode 100644
index 790be67..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.security.Provider;
-
-public final class DRLCertFactory extends Provider {
- /**
- * @serial
- */
- private static final long serialVersionUID = -7269650779605195879L;
-
- /**
- * Constructs the instance of the certificate factory provider.
- */
- public DRLCertFactory() {
- // specification of the provider name, version, and description.
- super("DRLCertFactory", 1.0, "ASN.1, DER, PkiPath, PKCS7");
- // register the service
- put("CertificateFactory.X509", "org.apache.harmony.security.provider.cert.X509CertFactoryImpl");
- // mapping the alias
- put("Alg.Alias.CertificateFactory.X.509", "X509");
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java
deleted file mode 100644
index 38500e5..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.math.BigInteger;
-import java.security.cert.CRLException;
-import java.security.cert.X509CRLEntry;
-import java.util.Date;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertList;
-
-/**
- * Implementation of X509CRLEntry. It wraps the instance
- * of org.apache.harmony.security.x509.TBSCertList.RevokedCertificate
- * obtained during the decoding of TBSCertList substructure
- * of the CertificateList structure which is an X.509 form of CRL.
- * (see RFC 3280 at http://www.ietf.org/rfc/rfc3280.txt)
- * Normally the instances of this class are constructed by involving
- * X509CRLImpl object.
- * @see org.apache.harmony.security.x509.TBSCertList
- * @see org.apache.harmony.security.provider.cert.X509CRLImpl
- * @see java.security.cert.X509CRLEntry
- */
-public class X509CRLEntryImpl extends X509CRLEntry {
-
- // the crl entry object to be wrapped in X509CRLEntry
- private final TBSCertList.RevokedCertificate rcert;
- // the extensions of the entry
- private final Extensions extensions;
- // issuer of the revoked certificate described by this crl entry
- private final X500Principal issuer;
-
- // encoded form of this revoked certificate entry
- private byte[] encoding;
-
- /**
- * Creates an instance on the base of existing
- * <code>TBSCertList.RevokedCertificate</code> object and
- * information about the issuer of revoked certificate.
- * If specified issuer is null, it is supposed that issuer
- * of the revoked certificate is the same as for involving CRL.
- */
- public X509CRLEntryImpl(TBSCertList.RevokedCertificate rcert,
- X500Principal issuer) {
- this.rcert = rcert;
- this.extensions = rcert.getCrlEntryExtensions();
- this.issuer = issuer;
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509CRLEntry method implementations -------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509CRLEntry#getEncoded()
- * method documentation for more info
- */
- public byte[] getEncoded() throws CRLException {
- if (encoding == null) {
- encoding = rcert.getEncoded();
- }
- byte[] result = new byte[encoding.length];
- System.arraycopy(encoding, 0, result, 0, encoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getSerialNumber()
- * method documentation for more info
- */
- public BigInteger getSerialNumber() {
- return rcert.getUserCertificate();
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getCertificateIssuer()
- * method documentation for more info
- */
- public X500Principal getCertificateIssuer() {
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getRevocationDate()
- * method documentation for more info
- */
- public Date getRevocationDate() {
- return rcert.getRevocationDate();
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#hasExtensions()
- * method documentation for more info
- */
- public boolean hasExtensions() {
- return (extensions != null) && (extensions.size() != 0);
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#toString()
- * method documentation for more info
- */
- public String toString() {
- return "X509CRLEntryImpl: "+rcert.toString();
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509Extension method implementations ------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509Extension#getNonCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getNonCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getExtensionValue(String)
- * method documentation for more info
- */
- public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- /**
- * @see java.security.cert.X509Extension#hasUnsupportedCriticalExtension()
- * method documentation for more info
- */
- public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- return extensions.hasUnsupportedCritical();
- }
-}
-
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java
deleted file mode 100644
index 68ec38a..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java
+++ /dev/null
@@ -1,504 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Principal;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.CRLException;
-import java.security.cert.Certificate;
-import java.security.cert.X509CRL;
-import java.security.cert.X509CRLEntry;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.CertificateList;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertList;
-
-/**
- * This class is an implementation of X509CRL. It wraps
- * the instance of org.apache.harmony.security.x509.CertificateList
- * built on the base of provided ASN.1 DER encoded form of
- * CertificateList structure (as specified in RFC 3280
- * http://www.ietf.org/rfc/rfc3280.txt).
- * Implementation supports work with indirect CRLs.
- * @see org.apache.harmony.security.x509.CertificateList
- * @see java.security.cert.X509CRL
- */
-public class X509CRLImpl extends X509CRL {
-
- // the core object to be wrapped in X509CRL
- private final CertificateList crl;
-
- // To speed up access to the info, the following fields
- // cache values retrieved from the CertificateList object
- private final TBSCertList tbsCertList;
- private byte[] tbsCertListEncoding;
- private final Extensions extensions;
- private X500Principal issuer;
- private ArrayList entries;
- private int entriesSize;
- private byte[] signature;
- private String sigAlgOID;
- private String sigAlgName;
- private byte[] sigAlgParams;
-
- // encoded form of crl
- private byte[] encoding;
-
- // indicates whether the signature algorithm parameters are null
- private boolean nullSigAlgParams;
- // indicates whether the crl entries have already been retrieved
- // from CertificateList object (crl)
- private boolean entriesRetrieved;
-
- // indicates whether this X.509 CRL is direct or indirect
- // (see rfc 3280 http://www.ietf.org/rfc/rfc3280.txt, p 5.)
- private boolean isIndirectCRL;
- // if crl is indirect, this field holds an info about how
- // many of the leading certificates in the list are issued
- // by the same issuer as CRL.
- private int nonIndirectEntriesSize;
-
- /**
- * Creates X.509 CRL by wrapping of the specified CertificateList object.
- */
- public X509CRLImpl(CertificateList crl) {
- this.crl = crl;
- this.tbsCertList = crl.getTbsCertList();
- this.extensions = tbsCertList.getCrlExtensions();
- }
-
- /**
- * Creates X.509 CRL on the base of ASN.1 DER encoded form of
- * the CRL (CertificateList structure described in RFC 3280)
- * provided via input stream.
- * @throws CRLException if decoding errors occur.
- */
- public X509CRLImpl(InputStream in) throws CRLException {
- try {
- // decode CertificateList structure
- this.crl = (CertificateList) CertificateList.ASN1.decode(in);
- this.tbsCertList = crl.getTbsCertList();
- this.extensions = tbsCertList.getCrlExtensions();
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * Creates X.509 CRL on the base of ASN.1 DER encoded form of
- * the CRL (CertificateList structure described in RFC 3280)
- * provided via array of bytes.
- * @throws IOException if decoding errors occur.
- */
- public X509CRLImpl(byte[] encoding) throws IOException {
- this((CertificateList) CertificateList.ASN1.decode(encoding));
- }
-
- // ---------------------------------------------------------------------
- // ----- java.security.cert.X509CRL abstract method implementations ----
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509CRL#getEncoded()
- * method documentation for more info
- */
- public byte[] getEncoded() throws CRLException {
- if (encoding == null) {
- encoding = crl.getEncoded();
- }
- byte[] result = new byte[encoding.length];
- System.arraycopy(encoding, 0, result, 0, encoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getVersion()
- * method documentation for more info
- */
- public int getVersion() {
- return tbsCertList.getVersion();
- }
-
- /**
- * @see java.security.cert.X509CRL#getIssuerDN()
- * method documentation for more info
- */
- public Principal getIssuerDN() {
- if (issuer == null) {
- issuer = tbsCertList.getIssuer().getX500Principal();
- }
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRL#getIssuerX500Principal()
- * method documentation for more info
- */
- public X500Principal getIssuerX500Principal() {
- if (issuer == null) {
- issuer = tbsCertList.getIssuer().getX500Principal();
- }
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRL#getThisUpdate()
- * method documentation for more info
- */
- public Date getThisUpdate() {
- return tbsCertList.getThisUpdate();
- }
-
- /**
- * @see java.security.cert.X509CRL#getNextUpdate()
- * method documentation for more info
- */
- public Date getNextUpdate() {
- return tbsCertList.getNextUpdate();
- }
-
- /*
- * Retrieves the crl entries (TBSCertList.RevokedCertificate objects)
- * from the TBSCertList structure and converts them to the
- * X509CRLEntryImpl objects
- */
- private void retrieveEntries() {
- entriesRetrieved = true;
- List rcerts = tbsCertList.getRevokedCertificates();
- if (rcerts == null) {
- return;
- }
- entriesSize = rcerts.size();
- entries = new ArrayList(entriesSize);
- // null means that revoked certificate issuer is the same as CRL issuer
- X500Principal rcertIssuer = null;
- for (int i=0; i<entriesSize; i++) {
- TBSCertList.RevokedCertificate rcert =
- (TBSCertList.RevokedCertificate) rcerts.get(i);
- X500Principal iss = rcert.getIssuer();
- if (iss != null) {
- // certificate issuer differs from CRL issuer
- // and CRL is indirect.
- rcertIssuer = iss;
- isIndirectCRL = true;
- // remember how many leading revoked certificates in the
- // list are issued by the same issuer as issuer of CRL
- // (these certificates are first in the list)
- nonIndirectEntriesSize = i;
- }
- entries.add(new X509CRLEntryImpl(rcert, rcertIssuer));
- }
- }
-
- /**
- * Searches for certificate in CRL.
- * This method supports indirect CRLs: if CRL is indirect method takes
- * into account serial number and issuer of the certificate,
- * if CRL issued by CA (i.e. it is not indirect) search is done only
- * by serial number of the specified certificate.
- * @see java.security.cert.X509CRL#getRevokedCertificate(X509Certificate)
- * method documentation for more info
- */
- public X509CRLEntry getRevokedCertificate(X509Certificate certificate) {
- if (certificate == null) {
- throw new NullPointerException("certificate == null");
- }
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- BigInteger serialN = certificate.getSerialNumber();
- if (isIndirectCRL) {
- // search in indirect crl
- X500Principal certIssuer = certificate.getIssuerX500Principal();
- if (certIssuer.equals(getIssuerX500Principal())) {
- // certificate issuer is CRL issuer
- certIssuer = null;
- }
- for (int i=0; i<entriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- // check the serial number of revoked certificate
- if (serialN.equals(entry.getSerialNumber())) {
- // revoked certificate issuer
- X500Principal iss = entry.getCertificateIssuer();
- // check the issuer of revoked certificate
- if (certIssuer != null) {
- // certificate issuer is not a CRL issuer, so
- // check issuers for equality
- if (certIssuer.equals(iss)) {
- return entry;
- }
- } else if (iss == null) {
- // both certificates was issued by CRL issuer
- return entry;
- }
- }
- }
- } else {
- // search in CA's (non indirect) crl: just look up the serial number
- for (int i=0; i<entriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- if (serialN.equals(entry.getSerialNumber())) {
- return entry;
- }
- }
- }
- return null;
- }
-
- /**
- * Method searches for CRL entry with specified serial number.
- * The method will search only certificate issued by CRL's issuer.
- * @see java.security.cert.X509CRL#getRevokedCertificate(BigInteger)
- * method documentation for more info
- */
- public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) {
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- for (int i=0; i<nonIndirectEntriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- if (serialNumber.equals(entry.getSerialNumber())) {
- return entry;
- }
- }
- return null;
- }
-
- /**
- * @see java.security.cert.X509CRL#getRevokedCertificates()
- * method documentation for more info
- */
- public Set<? extends X509CRLEntry> getRevokedCertificates() {
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- return new HashSet(entries);
- }
-
- /**
- * @see java.security.cert.X509CRL#getTBSCertList()
- * method documentation for more info
- */
- public byte[] getTBSCertList() throws CRLException {
- if (tbsCertListEncoding == null) {
- tbsCertListEncoding = tbsCertList.getEncoded();
- }
- byte[] result = new byte[tbsCertListEncoding.length];
- System.arraycopy(tbsCertListEncoding, 0,
- result, 0, tbsCertListEncoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSignature()
- * method documentation for more info
- */
- public byte[] getSignature() {
- if (signature == null) {
- signature = crl.getSignatureValue();
- }
- byte[] result = new byte[signature.length];
- System.arraycopy(signature, 0, result, 0, signature.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgName()
- * method documentation for more info
- */
- public String getSigAlgName() {
- if (sigAlgOID == null) {
- sigAlgOID = tbsCertList.getSignature().getAlgorithm();
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
- sigAlgName = sigAlgOID;
- }
- }
- return sigAlgName;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgOID()
- * method documentation for more info
- */
- public String getSigAlgOID() {
- if (sigAlgOID == null) {
- sigAlgOID = tbsCertList.getSignature().getAlgorithm();
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
- sigAlgName = sigAlgOID;
- }
- }
- return sigAlgOID;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgParams()
- * method documentation for more info
- */
- public byte[] getSigAlgParams() {
- if (nullSigAlgParams) {
- return null;
- }
- if (sigAlgParams == null) {
- sigAlgParams = tbsCertList.getSignature().getParameters();
- if (sigAlgParams == null) {
- nullSigAlgParams = true;
- return null;
- }
- }
- return sigAlgParams;
- }
-
- /**
- * @see java.security.cert.X509CRL#verify(PublicKey key)
- * method documentation for more info
- */
- public void verify(PublicKey key)
- throws CRLException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- Signature signature = Signature.getInstance(getSigAlgName());
- signature.initVerify(key);
- byte[] tbsEncoding = tbsCertList.getEncoded();
- signature.update(tbsEncoding, 0, tbsEncoding.length);
- if (!signature.verify(crl.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- /**
- * @see java.security.cert.X509CRL#verify(PublicKey key, String sigProvider)
- * method documentation for more info
- */
- public void verify(PublicKey key, String sigProvider)
- throws CRLException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- Signature signature = Signature.getInstance(
- getSigAlgName(), sigProvider);
- signature.initVerify(key);
- byte[] tbsEncoding = tbsCertList.getEncoded();
- signature.update(tbsEncoding, 0, tbsEncoding.length);
- if (!signature.verify(crl.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.CRL abstract method implementations -------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.CRL#isRevoked(Certificate)
- * method documentation for more info
- */
- public boolean isRevoked(Certificate cert) {
- if (!(cert instanceof X509Certificate)) {
- return false;
- }
- return getRevokedCertificate((X509Certificate) cert) != null;
- }
-
- /**
- * @see java.security.cert.CRL#toString()
- * method documentation for more info
- */
- public String toString() {
- return crl.toString();
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509Extension method implementations ------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509Extension#getNonCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getNonCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getExtensionValue(String)
- * method documentation for more info
- */
- public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- /**
- * @see java.security.cert.X509Extension#hasUnsupportedCriticalExtension()
- * method documentation for more info
- */
- public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- return extensions.hasUnsupportedCritical();
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
deleted file mode 100644
index 9129ec2..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
+++ /dev/null
@@ -1,858 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.security.cert.CRL;
-import java.security.cert.CRLException;
-import java.security.cert.CertPath;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactorySpi;
-import java.security.cert.X509CRL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import libcore.io.Base64;
-import libcore.io.Streams;
-import org.apache.harmony.security.asn1.ASN1Constants;
-import org.apache.harmony.security.asn1.BerInputStream;
-import org.apache.harmony.security.pkcs7.ContentInfo;
-import org.apache.harmony.security.pkcs7.SignedData;
-import org.apache.harmony.security.x509.CertificateList;
-
-/**
- * X509 Certificate Factory Service Provider Interface Implementation.
- * It supports CRLs and Certificates in (PEM) ASN.1 DER encoded form,
- * and Certification Paths in PkiPath and PKCS7 formats.
- * For Certificates and CRLs factory maintains the caching
- * mechanisms allowing to speed up repeated Certificate/CRL
- * generation.
- * @see Cache
- */
-public class X509CertFactoryImpl extends CertificateFactorySpi {
-
- // number of leading/trailing bytes used for cert hash computation
- private static final int CERT_CACHE_SEED_LENGTH = 28;
- // certificate cache
- private static final Cache CERT_CACHE = new Cache(CERT_CACHE_SEED_LENGTH);
- // number of leading/trailing bytes used for crl hash computation
- private static final int CRL_CACHE_SEED_LENGTH = 24;
- // crl cache
- private static final Cache CRL_CACHE = new Cache(CRL_CACHE_SEED_LENGTH);
-
- /**
- * Default constructor.
- * Creates the instance of Certificate Factory SPI ready for use.
- */
- public X509CertFactoryImpl() { }
-
- /**
- * Generates the X.509 certificate from the data in the stream.
- * The data in the stream can be either in ASN.1 DER encoded X.509
- * certificate, or PEM (Base64 encoding bounded by
- * <code>"-----BEGIN CERTIFICATE-----"</code> at the beginning and
- * <code>"-----END CERTIFICATE-----"</code> at the end) representation
- * of the former encoded form.
- *
- * Before the generation the encoded form is looked up in
- * the cache. If the cache contains the certificate with requested encoded
- * form it is returned from it, otherwise it is generated by ASN.1
- * decoder.
- *
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertificate(InputStream)
- * method documentation for more info
- */
- public Certificate engineGenerateCertificate(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- try {
- if (!inStream.markSupported()) {
- // create the mark supporting wrapper
- inStream = new RestoringInputStream(inStream);
- }
- // mark is needed to recognize the format of the provided encoding
- // (ASN.1 or PEM)
- inStream.mark(1);
- // check whether the provided certificate is in PEM encoded form
- if (inStream.read() == '-') {
- // decode PEM, retrieve CRL
- return getCertificate(decodePEM(inStream, CERT_BOUND_SUFFIX));
- } else {
- inStream.reset();
- // retrieve CRL
- return getCertificate(inStream);
- }
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * Generates the collection of the certificates on the base of provided
- * via input stream encodings.
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertificates(InputStream)
- * method documentation for more info
- */
- public Collection<? extends Certificate>
- engineGenerateCertificates(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- ArrayList<Certificate> result = new ArrayList<Certificate>();
- try {
- if (!inStream.markSupported()) {
- // create the mark supporting wrapper
- inStream = new RestoringInputStream(inStream);
- }
- // if it is PEM encoded form this array will contain the encoding
- // so ((it is PEM) <-> (encoding != null))
- byte[] encoding = null;
- // The following by SEQUENCE ASN.1 tag, used for
- // recognizing the data format
- // (is it PKCS7 ContentInfo structure, X.509 Certificate, or
- // unsupported encoding)
- int second_asn1_tag = -1;
- inStream.mark(1);
- int ch;
- while ((ch = inStream.read()) != -1) {
- // check if it is PEM encoded form
- if (ch == '-') { // beginning of PEM encoding ('-' char)
- // decode PEM chunk and store its content (ASN.1 encoding)
- encoding = decodePEM(inStream, FREE_BOUND_SUFFIX);
- } else if (ch == 0x30) { // beginning of ASN.1 sequence (0x30)
- encoding = null;
- inStream.reset();
- // prepare for data format determination
- inStream.mark(CERT_CACHE_SEED_LENGTH);
- } else { // unsupported data
- if (result.size() == 0) {
- throw new CertificateException("Unsupported encoding");
- } else {
- // it can be trailing user data,
- // so keep it in the stream
- inStream.reset();
- return result;
- }
- }
- // Check the data format
- BerInputStream in = (encoding == null)
- ? new BerInputStream(inStream)
- : new BerInputStream(encoding);
- // read the next ASN.1 tag
- second_asn1_tag = in.next(); // inStream position changed
- if (encoding == null) {
- // keep whole structure in the stream
- inStream.reset();
- }
- // check if it is a TBSCertificate structure
- if (second_asn1_tag != ASN1Constants.TAG_C_SEQUENCE) {
- if (result.size() == 0) {
- // there were not read X.509 Certificates, so
- // break the cycle and check
- // whether it is PKCS7 structure
- break;
- } else {
- // it can be trailing user data,
- // so return what we already read
- return result;
- }
- } else {
- if (encoding == null) {
- result.add(getCertificate(inStream));
- } else {
- result.add(getCertificate(encoding));
- }
- }
- // mark for the next iteration
- inStream.mark(1);
- }
- if (result.size() != 0) {
- // some Certificates have been read
- return result;
- } else if (ch == -1) {
- /* No data in the stream, so return the empty collection. */
- return result;
- }
- // else: check if it is PKCS7
- if (second_asn1_tag == ASN1Constants.TAG_OID) {
- // it is PKCS7 ContentInfo structure, so decode it
- ContentInfo info = (ContentInfo)
- ((encoding != null)
- ? ContentInfo.ASN1.decode(encoding)
- : ContentInfo.ASN1.decode(inStream));
- // retrieve SignedData
- SignedData data = info.getSignedData();
- if (data == null) {
- throw new CertificateException("Invalid PKCS7 data provided");
- }
- List<org.apache.harmony.security.x509.Certificate> certs = data.getCertificates();
- if (certs != null) {
- for (org.apache.harmony.security.x509.Certificate cert : certs) {
- result.add(new X509CertImpl(cert));
- }
- }
- return result;
- }
- // else: Unknown data format
- throw new CertificateException("Unsupported encoding");
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCRL(InputStream)
- * method documentation for more info
- */
- public CRL engineGenerateCRL(InputStream inStream)
- throws CRLException {
- if (inStream == null) {
- throw new CRLException("inStream == null");
- }
- try {
- if (!inStream.markSupported()) {
- // Create the mark supporting wrapper
- // Mark is needed to recognize the format
- // of provided encoding form (ASN.1 or PEM)
- inStream = new RestoringInputStream(inStream);
- }
- inStream.mark(1);
- // check whether the provided crl is in PEM encoded form
- if (inStream.read() == '-') {
- // decode PEM, retrieve CRL
- return getCRL(decodePEM(inStream, FREE_BOUND_SUFFIX));
- } else {
- inStream.reset();
- // retrieve CRL
- return getCRL(inStream);
- }
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCRLs(InputStream)
- * method documentation for more info
- */
- public Collection<? extends CRL> engineGenerateCRLs(InputStream inStream)
- throws CRLException {
- if (inStream == null) {
- throw new CRLException("inStream == null");
- }
- ArrayList<CRL> result = new ArrayList<CRL>();
- try {
- if (!inStream.markSupported()) {
- inStream = new RestoringInputStream(inStream);
- }
- // if it is PEM encoded form this array will contain the encoding
- // so ((it is PEM) <-> (encoding != null))
- byte[] encoding = null;
- // The following by SEQUENCE ASN.1 tag, used for
- // recognizing the data format
- // (is it PKCS7 ContentInfo structure, X.509 CRL, or
- // unsupported encoding)
- int second_asn1_tag = -1;
- inStream.mark(1);
- int ch;
- while ((ch = inStream.read()) != -1) {
- // check if it is PEM encoded form
- if (ch == '-') { // beginning of PEM encoding ('-' char)
- // decode PEM chunk and store its content (ASN.1 encoding)
- encoding = decodePEM(inStream, FREE_BOUND_SUFFIX);
- } else if (ch == 0x30) { // beginning of ASN.1 sequence (0x30)
- encoding = null;
- inStream.reset();
- // prepare for data format determination
- inStream.mark(CRL_CACHE_SEED_LENGTH);
- } else { // unsupported data
- if (result.size() == 0) {
- throw new CRLException("Unsupported encoding");
- } else {
- // it can be trailing user data,
- // so keep it in the stream
- inStream.reset();
- return result;
- }
- }
- // Check the data format
- BerInputStream in = (encoding == null)
- ? new BerInputStream(inStream)
- : new BerInputStream(encoding);
- // read the next ASN.1 tag
- second_asn1_tag = in.next();
- if (encoding == null) {
- // keep whole structure in the stream
- inStream.reset();
- }
- // check if it is a TBSCertList structure
- if (second_asn1_tag != ASN1Constants.TAG_C_SEQUENCE) {
- if (result.size() == 0) {
- // there were not read X.509 CRLs, so
- // break the cycle and check
- // whether it is PKCS7 structure
- break;
- } else {
- // it can be trailing user data,
- // so return what we already read
- return result;
- }
- } else {
- if (encoding == null) {
- result.add(getCRL(inStream));
- } else {
- result.add(getCRL(encoding));
- }
- }
- inStream.mark(1);
- }
- if (result.size() != 0) {
- // the stream was read out
- return result;
- } else if (ch == -1) {
- throw new CRLException("There is no data in the stream");
- }
- // else: check if it is PKCS7
- if (second_asn1_tag == ASN1Constants.TAG_OID) {
- // it is PKCS7 ContentInfo structure, so decode it
- ContentInfo info = (ContentInfo)
- ((encoding != null)
- ? ContentInfo.ASN1.decode(encoding)
- : ContentInfo.ASN1.decode(inStream));
- // retrieve SignedData
- SignedData data = info.getSignedData();
- if (data == null) {
- throw new CRLException("Invalid PKCS7 data provided");
- }
- List<CertificateList> crls = data.getCRLs();
- if (crls != null) {
- for (CertificateList crl : crls) {
- result.add(new X509CRLImpl(crl));
- }
- }
- return result;
- }
- // else: Unknown data format
- throw new CRLException("Unsupported encoding");
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(InputStream)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- return engineGenerateCertPath(inStream, "PkiPath");
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(InputStream,String)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(
- InputStream inStream, String encoding) throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- if (!inStream.markSupported()) {
- inStream = new RestoringInputStream(inStream);
- }
- try {
- inStream.mark(1);
- int ch;
-
- // check if it is PEM encoded form
- if ((ch = inStream.read()) == '-') {
- // decode PEM chunk into ASN.1 form and decode CertPath object
- return X509CertPathImpl.getInstance(
- decodePEM(inStream, FREE_BOUND_SUFFIX), encoding);
- } else if (ch == 0x30) { // ASN.1 Sequence
- inStream.reset();
- // decode ASN.1 form
- return X509CertPathImpl.getInstance(inStream, encoding);
- } else {
- throw new CertificateException("Unsupported encoding");
- }
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(List)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(List<? extends Certificate> certificates)
- throws CertificateException {
- return new X509CertPathImpl(certificates);
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGetCertPathEncodings()
- * method documentation for more info
- */
- public Iterator<String> engineGetCertPathEncodings() {
- return X509CertPathImpl.encodings.iterator();
- }
-
- // ---------------------------------------------------------------------
- // ------------------------ Staff methods ------------------------------
- // ---------------------------------------------------------------------
-
- private static final byte[] PEM_BEGIN = "-----BEGIN".getBytes(StandardCharsets.UTF_8);
- private static final byte[] PEM_END = "-----END".getBytes(StandardCharsets.UTF_8);
- /**
- * Code describing free format for PEM boundary suffix:
- * "^-----BEGIN.*\n" at the beginning, and<br>
- * "\n-----END.*(EOF|\n)$" at the end.
- */
- private static final byte[] FREE_BOUND_SUFFIX = null;
- /**
- * Code describing PEM boundary suffix for X.509 certificate:
- * "^-----BEGIN CERTIFICATE-----\n" at the beginning, and<br>
- * "\n-----END CERTIFICATE-----" at the end.
- */
- private static final byte[] CERT_BOUND_SUFFIX = " CERTIFICATE-----".getBytes(StandardCharsets.UTF_8);
-
- /**
- * Method retrieves the PEM encoded data from the stream
- * and returns its decoded representation.
- * Method checks correctness of PEM boundaries. It supposes that
- * the first '-' of the opening boundary has already been read from
- * the stream. So first of all it checks that the leading bytes
- * are equal to "-----BEGIN" boundary prefix. Than if boundary_suffix
- * is not null, it checks that next bytes equal to boundary_suffix
- * + new line char[s] ([CR]LF).
- * If boundary_suffix parameter is null, method supposes free suffix
- * format and skips any bytes until the new line.<br>
- * After the opening boundary has been read and checked, the method
- * read Base64 encoded data until closing PEM boundary is not reached.<br>
- * Than it checks closing boundary - it should start with new line +
- * "-----END" + boundary_suffix. If boundary_suffix is null,
- * any characters are skipped until the new line.<br>
- * After this any trailing new line characters are skipped from the stream,
- * Base64 encoding is decoded and returned.
- * @param inStream the stream containing the PEM encoding.
- * @param boundary_suffix the suffix of expected PEM multipart
- * boundary delimiter.<br>
- * If it is null, that any character sequences are accepted.
- * @throws IOException If PEM boundary delimiter does not comply
- * with expected or some I/O or decoding problems occur.
- */
- private byte[] decodePEM(InputStream inStream, byte[] boundary_suffix)
- throws IOException {
- int ch; // the char to be read
- // check and skip opening boundary delimiter
- // (first '-' is supposed as already read)
- for (int i = 1; i < PEM_BEGIN.length; ++i) {
- if (PEM_BEGIN[i] != (ch = inStream.read())) {
- throw new IOException(
- "Incorrect PEM encoding: '-----BEGIN"
- + ((boundary_suffix == null)
- ? "" : new String(boundary_suffix))
- + "' is expected as opening delimiter boundary.");
- }
- }
- if (boundary_suffix == null) {
- // read (skip) the trailing characters of
- // the beginning PEM boundary delimiter
- while ((ch = inStream.read()) != '\n') {
- if (ch == -1) {
- throw new IOException("Incorrect PEM encoding: EOF before content");
- }
- }
- } else {
- for (int i=0; i<boundary_suffix.length; i++) {
- if (boundary_suffix[i] != inStream.read()) {
- throw new IOException("Incorrect PEM encoding: '-----BEGIN" +
- new String(boundary_suffix) + "' is expected as opening delimiter boundary.");
- }
- }
- // read new line characters
- if ((ch = inStream.read()) == '\r') {
- // CR has been read, now read LF character
- ch = inStream.read();
- }
- if (ch != '\n') {
- throw new IOException("Incorrect PEM encoding: newline expected after " +
- "opening delimiter boundary");
- }
- }
- int size = 1024; // the size of the buffer containing Base64 data
- byte[] buff = new byte[size];
- int index = 0;
- // read bytes while ending boundary delimiter is not reached
- while ((ch = inStream.read()) != '-') {
- if (ch == -1) {
- throw new IOException("Incorrect Base64 encoding: EOF without closing delimiter");
- }
- buff[index++] = (byte) ch;
- if (index == size) {
- // enlarge the buffer
- byte[] newbuff = new byte[size+1024];
- System.arraycopy(buff, 0, newbuff, 0, size);
- buff = newbuff;
- size += 1024;
- }
- }
- if (buff[index-1] != '\n') {
- throw new IOException("Incorrect Base64 encoding: newline expected before " +
- "closing boundary delimiter");
- }
- // check and skip closing boundary delimiter prefix
- // (first '-' was read)
- for (int i = 1; i < PEM_END.length; ++i) {
- if (PEM_END[i] != inStream.read()) {
- throw badEnd(boundary_suffix);
- }
- }
- if (boundary_suffix == null) {
- // read (skip) the trailing characters of
- // the closing PEM boundary delimiter
- while (((ch = inStream.read()) != -1) && (ch != '\n') && (ch != '\r')) {
- }
- } else {
- for (int i=0; i<boundary_suffix.length; i++) {
- if (boundary_suffix[i] != inStream.read()) {
- throw badEnd(boundary_suffix);
- }
- }
- }
- // skip trailing line breaks
- inStream.mark(1);
- while (((ch = inStream.read()) != -1) && (ch == '\n' || ch == '\r')) {
- inStream.mark(1);
- }
- inStream.reset();
- buff = Base64.decode(buff, index);
- if (buff == null) {
- throw new IOException("Incorrect Base64 encoding");
- }
- return buff;
- }
-
- private IOException badEnd(byte[] boundary_suffix) throws IOException {
- String s = (boundary_suffix == null) ? "" : new String(boundary_suffix);
- throw new IOException("Incorrect PEM encoding: '-----END" + s + "' is expected as closing delimiter boundary.");
- }
-
- /**
- * Reads the data of specified length from source
- * and returns it as an array.
- * @return the byte array contained read data or
- * null if the stream contains not enough data
- * @throws IOException if some I/O error has been occurred.
- */
- private static byte[] readBytes(InputStream source, int length)
- throws IOException {
- byte[] result = new byte[length];
- for (int i=0; i<length; i++) {
- int bytik = source.read();
- if (bytik == -1) {
- return null;
- }
- result[i] = (byte) bytik;
- }
- return result;
- }
-
- /**
- * Returns the Certificate object corresponding to the provided encoding.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static Certificate getCertificate(byte[] encoding)
- throws CertificateException, IOException {
- if (encoding.length < CERT_CACHE_SEED_LENGTH) {
- throw new CertificateException("encoding.length < CERT_CACHE_SEED_LENGTH");
- }
- synchronized (CERT_CACHE) {
- long hash = CERT_CACHE.getHash(encoding);
- if (CERT_CACHE.contains(hash)) {
- Certificate res =
- (Certificate) CERT_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- }
- Certificate res = new X509CertImpl(encoding);
- CERT_CACHE.put(hash, encoding, res);
- return res;
- }
- }
-
- /**
- * Returns the Certificate object corresponding to the encoding provided
- * by the stream.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static Certificate getCertificate(InputStream inStream)
- throws CertificateException, IOException {
- synchronized (CERT_CACHE) {
- inStream.mark(CERT_CACHE_SEED_LENGTH);
- // read the prefix of the encoding
- byte[] buff = readBytes(inStream, CERT_CACHE_SEED_LENGTH);
- inStream.reset();
- if (buff == null) {
- throw new CertificateException("InputStream doesn't contain enough data");
- }
- long hash = CERT_CACHE.getHash(buff);
- if (CERT_CACHE.contains(hash)) {
- byte[] encoding = new byte[BerInputStream.getLength(buff)];
- if (encoding.length < CERT_CACHE_SEED_LENGTH) {
- throw new CertificateException("Bad Certificate encoding");
- }
- Streams.readFully(inStream, encoding);
- Certificate res = (Certificate) CERT_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- res = new X509CertImpl(encoding);
- CERT_CACHE.put(hash, encoding, res);
- return res;
- } else {
- inStream.reset();
- Certificate res = new X509CertImpl(inStream);
- CERT_CACHE.put(hash, res.getEncoded(), res);
- return res;
- }
- }
- }
-
- /**
- * Returns the CRL object corresponding to the provided encoding.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static CRL getCRL(byte[] encoding)
- throws CRLException, IOException {
- if (encoding.length < CRL_CACHE_SEED_LENGTH) {
- throw new CRLException("encoding.length < CRL_CACHE_SEED_LENGTH");
- }
- synchronized (CRL_CACHE) {
- long hash = CRL_CACHE.getHash(encoding);
- if (CRL_CACHE.contains(hash)) {
- X509CRL res = (X509CRL) CRL_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- }
- X509CRL res = new X509CRLImpl(encoding);
- CRL_CACHE.put(hash, encoding, res);
- return res;
- }
- }
-
- /**
- * Returns the CRL object corresponding to the encoding provided
- * by the stream.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static CRL getCRL(InputStream inStream)
- throws CRLException, IOException {
- synchronized (CRL_CACHE) {
- inStream.mark(CRL_CACHE_SEED_LENGTH);
- byte[] buff = readBytes(inStream, CRL_CACHE_SEED_LENGTH);
- // read the prefix of the encoding
- inStream.reset();
- if (buff == null) {
- throw new CRLException("InputStream doesn't contain enough data");
- }
- long hash = CRL_CACHE.getHash(buff);
- if (CRL_CACHE.contains(hash)) {
- byte[] encoding = new byte[BerInputStream.getLength(buff)];
- if (encoding.length < CRL_CACHE_SEED_LENGTH) {
- throw new CRLException("Bad CRL encoding");
- }
- Streams.readFully(inStream, encoding);
- CRL res = (CRL) CRL_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- res = new X509CRLImpl(encoding);
- CRL_CACHE.put(hash, encoding, res);
- return res;
- } else {
- X509CRL res = new X509CRLImpl(inStream);
- CRL_CACHE.put(hash, res.getEncoded(), res);
- return res;
- }
- }
- }
-
- /*
- * This class extends any existing input stream with
- * mark functionality. It acts as a wrapper over the
- * stream and supports reset to the
- * marked state with readlimit no more than BUFF_SIZE.
- */
- private static class RestoringInputStream extends InputStream {
-
- // wrapped input stream
- private final InputStream inStream;
- // specifies how much of the read data is buffered
- // after the mark has been set up
- private static final int BUFF_SIZE = 32;
- // buffer to keep the bytes read after the mark has been set up
- private final int[] buff = new int[BUFF_SIZE*2];
- // position of the next byte to read,
- // the value of -1 indicates that the buffer is not used
- // (mark was not set up or was invalidated, or reset to the marked
- // position has been done and all the buffered data was read out)
- private int pos = -1;
- // position of the last buffered byte
- private int bar = 0;
- // position in the buffer where the mark becomes invalidated
- private int end = 0;
-
- /**
- * Creates the mark supporting wrapper over the stream.
- */
- public RestoringInputStream(InputStream inStream) {
- this.inStream = inStream;
- }
-
- @Override
- public int available() throws IOException {
- return (bar - pos) + inStream.available();
- }
-
- @Override
- public void close() throws IOException {
- inStream.close();
- }
-
- @Override
- public void mark(int readlimit) {
- if (pos < 0) {
- pos = 0;
- bar = 0;
- end = BUFF_SIZE - 1;
- } else {
- end = (pos + BUFF_SIZE - 1) % BUFF_SIZE;
- }
- }
-
- @Override
- public boolean markSupported() {
- return true;
- }
-
- /**
- * Reads the byte from the stream. If mark has been set up
- * and was not invalidated byte is read from the underlying
- * stream and saved into the buffer. If the current read position
- * has been reset to the marked position and there are remaining
- * bytes in the buffer, the byte is taken from it. In the other cases
- * (if mark has been invalidated, or there are no buffered bytes)
- * the byte is taken directly from the underlying stream and it is
- * returned without saving to the buffer.
- *
- * @see java.io.InputStream#read()
- * method documentation for more info
- */
- public int read() throws IOException {
- // if buffer is currently used
- if (pos >= 0) {
- // current position in the buffer
- int cur = pos % BUFF_SIZE;
- // check whether the buffer contains the data to be read
- if (cur < bar) {
- // return the data from the buffer
- pos++;
- return buff[cur];
- }
- // check whether buffer has free space
- if (cur != end) {
- // it has, so read the data from the wrapped stream
- // and place it in the buffer
- buff[cur] = inStream.read();
- bar = cur+1;
- pos++;
- return buff[cur];
- } else {
- // buffer if full and can not operate
- // any more, so invalidate the mark position
- // and turn off the using of buffer
- pos = -1;
- }
- }
- // buffer is not used, so return the data from the wrapped stream
- return inStream.read();
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int read_b;
- int i;
- for (i=0; i<len; i++) {
- if ((read_b = read()) == -1) {
- return (i == 0) ? -1 : i;
- }
- b[off+i] = (byte) read_b;
- }
- return i;
- }
-
- @Override
- public void reset() throws IOException {
- if (pos >= 0) {
- pos = (end + 1) % BUFF_SIZE;
- } else {
- throw new IOException("Could not reset the stream: " +
- "position became invalid or stream has not been marked");
- }
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
deleted file mode 100644
index 4600bdc..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
+++ /dev/null
@@ -1,430 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Principal;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.Certificate;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertificate;
-
-/**
- * This class is an implementation of X509Certificate. It wraps
- * the instance of org.apache.harmony.security.x509.Certificate
- * built on the base of provided ASN.1 DER encoded form of
- * Certificate structure (as specified in RFC 3280
- * http://www.ietf.org/rfc/rfc3280.txt).
- * @see org.apache.harmony.security.x509.Certificate
- * @see java.security.cert.X509Certificate
- */
-public final class X509CertImpl extends X509Certificate {
-
- /** @serial */
- private static final long serialVersionUID = 2972248729446736154L;
-
- /** the core object to be wrapped in X509Certificate */
- private final Certificate certificate;
-
- private final TBSCertificate tbsCert;
- private final Extensions extensions;
- // to speed up access to the info, the following fields
- // cache values retrieved from the certificate object,
- // initialized using the "single-check idiom".
- private volatile long notBefore = -1;
- private volatile long notAfter = -1;
- private volatile BigInteger serialNumber;
- private volatile X500Principal issuer;
- private volatile X500Principal subject;
- private volatile byte[] tbsCertificate;
- private volatile byte[] signature;
- private volatile String sigAlgName;
- private volatile String sigAlgOID;
- private volatile byte[] sigAlgParams;
- // indicates whether the signature algorithm parameters are null
- private volatile boolean nullSigAlgParams;
- private volatile PublicKey publicKey;
-
- // encoding of the certificate
- private volatile byte[] encoding;
-
- /**
- * Constructs the instance on the base of ASN.1 encoded
- * form of X.509 certificate provided via stream parameter.
- * @param in input stream containing ASN.1 encoded form of certificate.
- * @throws CertificateException if some decoding problems occur.
- */
- public X509CertImpl(InputStream in) throws CertificateException {
- try {
- // decode the Certificate object
- this.certificate = (Certificate) Certificate.ASN1.decode(in);
- // cache the values of TBSCertificate and Extensions
- this.tbsCert = certificate.getTbsCertificate();
- this.extensions = tbsCert.getExtensions();
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * Constructs the instance on the base of existing Certificate object to
- * be wrapped.
- */
- public X509CertImpl(Certificate certificate) {
- this.certificate = certificate;
- // cache the values of TBSCertificate and Extensions
- this.tbsCert = certificate.getTbsCertificate();
- this.extensions = tbsCert.getExtensions();
- }
-
- /**
- * Constructs the instance on the base of ASN.1 encoded
- * form of X.509 certificate provided via array of bytes.
- * @param encoding byte array containing ASN.1 encoded form of certificate.
- * @throws IOException if some decoding problems occur.
- */
- public X509CertImpl(byte[] encoding) throws IOException {
- this((Certificate) Certificate.ASN1.decode(encoding));
- }
-
- public void checkValidity()
- throws CertificateExpiredException, CertificateNotYetValidException {
- checkValidity(System.currentTimeMillis());
- }
-
- public void checkValidity(Date date)
- throws CertificateExpiredException, CertificateNotYetValidException {
- checkValidity(date.getTime());
- }
-
- private void checkValidity(long time)
- throws CertificateExpiredException, CertificateNotYetValidException {
- if (time < getNotBeforeInternal()) {
- throw new CertificateNotYetValidException("current time: " + new Date(time)
- + ", validation time: " + new Date(getNotBeforeInternal()));
- }
- if (time > getNotAfterInternal()) {
- throw new CertificateExpiredException("current time: " + new Date(time)
- + ", expiration time: " + new Date(getNotAfterInternal()));
- }
- }
-
- public int getVersion() {
- return tbsCert.getVersion() + 1;
- }
-
- public BigInteger getSerialNumber() {
- BigInteger result = serialNumber;
- if (result == null) {
- serialNumber = result = tbsCert.getSerialNumber();
- }
- return result;
- }
-
- public Principal getIssuerDN() {
- return getIssuerX500Principal();
- }
-
- public X500Principal getIssuerX500Principal() {
- X500Principal result = issuer;
- if (result == null) {
- // retrieve the issuer's principal
- issuer = result = tbsCert.getIssuer().getX500Principal();
- }
- return result;
- }
-
- public Principal getSubjectDN() {
- return getSubjectX500Principal();
- }
-
- public X500Principal getSubjectX500Principal() {
- X500Principal result = subject;
- if (result == null) {
- // retrieve the subject's principal
- subject = result = tbsCert.getSubject().getX500Principal();
- }
- return result;
- }
-
- public Date getNotBefore() {
- return new Date(getNotBeforeInternal());
- }
-
- private long getNotBeforeInternal() {
- long result = notBefore;
- if (result == -1) {
- notBefore = result = tbsCert.getValidity().getNotBefore().getTime();
- }
- return result;
- }
-
- public Date getNotAfter() {
- return new Date(getNotAfterInternal());
- }
-
- private long getNotAfterInternal() {
- long result = notAfter;
- if (result == -1) {
- notAfter = result = tbsCert.getValidity().getNotAfter().getTime();
- }
- return result;
- }
-
- public byte[] getTBSCertificate() throws CertificateEncodingException {
- return getTbsCertificateInternal().clone();
- }
-
- private byte[] getTbsCertificateInternal() {
- byte[] result = tbsCertificate;
- if (result == null) {
- tbsCertificate = result = tbsCert.getEncoded();
- }
- return result;
- }
-
- public byte[] getSignature() {
- return getSignatureInternal().clone();
- }
-
- private byte[] getSignatureInternal() {
- byte[] result = signature;
- if (result == null) {
- signature = result = certificate.getSignatureValue();
- }
- return result;
- }
-
- public String getSigAlgName() {
- String result = sigAlgName;
- if (result == null) {
- String sigAlgOIDLocal = getSigAlgOID();
- // retrieve the name of the signing algorithm
- result = AlgNameMapper.map2AlgName(sigAlgOIDLocal);
- if (result == null) {
- // if could not be found, use OID as a name
- result = sigAlgOIDLocal;
- }
- sigAlgName = result;
- }
- return result;
- }
-
- public String getSigAlgOID() {
- String result = sigAlgOID;
- if (result == null) {
- // if info was not retrieved (and cached), do it:
- sigAlgOID = result = tbsCert.getSignature().getAlgorithm();
- }
- return result;
- }
-
- public byte[] getSigAlgParams() {
- if (nullSigAlgParams) {
- return null;
- }
- byte[] result = sigAlgParams;
- if (result == null) {
- result = tbsCert.getSignature().getParameters();
- if (result == null) {
- nullSigAlgParams = true;
- return null;
- }
- sigAlgParams = result;
- }
- return result;
- }
-
- public boolean[] getIssuerUniqueID() {
- return tbsCert.getIssuerUniqueID();
- }
-
- public boolean[] getSubjectUniqueID() {
- return tbsCert.getSubjectUniqueID();
- }
-
- public boolean[] getKeyUsage() {
- if (extensions == null) {
- return null;
- }
- return extensions.valueOfKeyUsage();
- }
-
- public List<String> getExtendedKeyUsage()
- throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- return extensions.valueOfExtendedKeyUsage();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- public int getBasicConstraints() {
- if (extensions == null) {
- return -1;
- }
- return extensions.valueOfBasicConstraints();
- }
-
- public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- // Retrieve the extension value from the cached extensions object
- // This extension is not checked for correctness during
- // certificate generation, so now it can throw exception
- return extensions.valueOfSubjectAlternativeName();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- /**
- * @see java.security.cert.X509Certificate#getIssuerAlternativeNames()
- * method documentation for more information.
- */
- public Collection<List<?>> getIssuerAlternativeNames() throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- // Retrieve the extension value from the cached extensions object
- // This extension is not checked for correctness during
- // certificate generation, so now it can throw exception
- return extensions.valueOfIssuerAlternativeName();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- @Override public byte[] getEncoded() throws CertificateEncodingException {
- return getEncodedInternal().clone();
- }
- private byte[] getEncodedInternal() throws CertificateEncodingException {
- byte[] result = encoding;
- if (encoding == null) {
- encoding = result = certificate.getEncoded();
- }
- return result;
- }
-
- @Override public PublicKey getPublicKey() {
- PublicKey result = publicKey;
- if (result == null) {
- publicKey = result = tbsCert.getSubjectPublicKeyInfo().getPublicKey();
- }
- return result;
- }
-
- @Override public String toString() {
- return certificate.toString();
- }
-
- @Override public void verify(PublicKey key)
- throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
-
- Signature signature = Signature.getInstance(getSigAlgName());
- signature.initVerify(key);
- // retrieve the encoding of the TBSCertificate structure
- byte[] tbsCertificateLocal = getTbsCertificateInternal();
- // compute and verify the signature
- signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
- if (!signature.verify(certificate.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- @Override public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
-
- Signature signature = Signature.getInstance(getSigAlgName(), sigProvider);
- signature.initVerify(key);
- // retrieve the encoding of the TBSCertificate structure
- byte[] tbsCertificateLocal = getTbsCertificateInternal();
- // compute and verify the signature
- signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
- if (!signature.verify(certificate.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- @Override public Set<String> getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- return extensions.getNonCriticalExtensions();
- }
-
- @Override public Set<String> getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- return extensions.getCriticalExtensions();
- }
-
- @Override public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- @Override public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- // retrieve the info from the cached extensions object
- return extensions.hasUnsupportedCritical();
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
deleted file mode 100644
index 3699700..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
+++ /dev/null
@@ -1,451 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.cert.CertPath;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.harmony.security.asn1.ASN1Any;
-import org.apache.harmony.security.asn1.ASN1Explicit;
-import org.apache.harmony.security.asn1.ASN1Implicit;
-import org.apache.harmony.security.asn1.ASN1Oid;
-import org.apache.harmony.security.asn1.ASN1Sequence;
-import org.apache.harmony.security.asn1.ASN1SequenceOf;
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.BerInputStream;
-import org.apache.harmony.security.pkcs7.ContentInfo;
-import org.apache.harmony.security.pkcs7.SignedData;
-import org.apache.harmony.security.x509.Certificate;
-
-/**
- * This class is an implementation of X.509 CertPath. This implementation
- * provides ability to create the instance of X.509 Certification Path
- * by several means:<br>
- *
- * 1. It can be created over the list of X.509 certificates
- * (implementations of X509Certificate class) provided in constructor.<br>
- *
- * 2. It can be created by means of <code>getInstance</code> methods
- * on the base of the following ASN.1 DER encoded forms:<br>
- *
- * - PkiPath as defined in
- * ITU-T Recommendation X.509(2000) Corrigendum 1(2001)
- * (can be seen at
- * ftp://ftp.bull.com/pub/OSIdirectory/DefectResolution/TechnicalCorrigenda/ApprovedTechnicalCorrigendaToX.509/8%7CX.509-TC1(4th).pdf)
- * <br>
- * - PKCS #7 SignedData object provided in the form of
- * ContentInfo structure. CertPath object is generated on the base of
- * certificates presented in <code>certificates</code> field of the SignedData
- * object which in its turn is retrieved from ContentInfo structure.
- * (see http://www.ietf.org/rfc/rfc2315.txt
- * for more info on PKCS #7)
- * <br>
- *
- */
-public class X509CertPathImpl extends CertPath {
- /**
- * @serial
- */
- private static final long serialVersionUID = 7989755106209515436L;
-
- /**
- * Supported encoding types for CerthPath. Used by the various APIs that
- * encode this into bytes such as {@link #getEncoded()}.
- */
- private enum Encoding {
- PKI_PATH("PkiPath"),
- PKCS7("PKCS7");
-
- private final String apiName;
-
- Encoding(String apiName) {
- this.apiName = apiName;
- }
-
- static Encoding findByApiName(String apiName) throws CertificateEncodingException {
- for (Encoding element : values()) {
- if (element.apiName.equals(apiName)) {
- return element;
- }
- }
-
- return null;
- }
- }
-
- /** Unmodifiable list of encodings for the API. */
- static final List<String> encodings = Collections.unmodifiableList(Arrays.asList(new String[] {
- Encoding.PKI_PATH.apiName,
- Encoding.PKCS7.apiName,
- }));
-
- /** The list of certificates in the order of target toward trust anchor. */
- private final List<X509Certificate> certificates;
-
- /** PkiPath encoding of the certification path. */
- private byte[] pkiPathEncoding;
-
- /** PKCS7 encoding of the certification path. */
- private byte[] pkcs7Encoding;
-
- /**
- * Creates an instance of X.509 CertPath over the specified list of
- * certificates.
- *
- * @throws CertificateException if some of the object in the list is not an
- * instance of subclass of X509Certificate.
- */
- public X509CertPathImpl(List<? extends java.security.cert.Certificate> certs)
- throws CertificateException {
- super("X.509");
-
- final int size = certs.size();
- certificates = new ArrayList<X509Certificate>(size);
-
- for (int i = 0; i < size; i++) {
- final java.security.cert.Certificate cert = certs.get(i);
- if (!(cert instanceof X509Certificate)) {
- throw new CertificateException("Certificate " + i + " is not an X.509 certificate");
- }
-
- certificates.add((X509Certificate) cert);
- }
- }
-
- /**
- * Creates an X.509 CertPath over the specified {@code certs}. The
- * {@code certs} should be sorted correctly when calling into the
- * constructor. Additionally, the {@code encodedPath} should match the
- * expected output for the {@code type} of encoding.
- */
- private X509CertPathImpl(List<X509Certificate> certs, Encoding type) {
- super("X.509");
-
- certificates = certs;
- }
-
- /**
- * Extract a CertPath from a PKCS#7 {@code contentInfo} object.
- */
- private static X509CertPathImpl getCertPathFromContentInfo(ContentInfo contentInfo)
- throws CertificateException {
- final SignedData sd = contentInfo.getSignedData();
- if (sd == null) {
- throw new CertificateException("Incorrect PKCS7 encoded form: missing signed data");
- }
-
- List<Certificate> certs = sd.getCertificates();
- if (certs == null) {
- certs = Collections.emptyList();
- }
-
- final List<X509Certificate> result = new ArrayList<X509Certificate>(certs.size());
- for (Certificate cert : certs) {
- result.add(new X509CertImpl(cert));
- }
-
- return new X509CertPathImpl(result, Encoding.PKCS7);
- }
-
- /**
- * Generates certification path object on the base of PkiPath encoded form
- * provided via input stream.
- *
- * @throws CertificateException if some problems occurred during the
- * decoding.
- */
- public static X509CertPathImpl getInstance(InputStream in) throws CertificateException {
- try {
- return (X509CertPathImpl) ASN1.decode(in);
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the basis of encoding provided via
- * input stream. The format of provided encoded form is specified by
- * parameter <code>encoding</code>.
- *
- * @throws CertificateException if specified encoding form is not supported,
- * or some problems occurred during the decoding.
- */
- public static X509CertPathImpl getInstance(InputStream in, String encoding)
- throws CertificateException {
- try {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
-
- switch (encType) {
- case PKI_PATH:
- return (X509CertPathImpl) ASN1.decode(in);
- case PKCS7:
- return getCertPathFromContentInfo((ContentInfo) ContentInfo.ASN1.decode(in));
- default:
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the base of PkiPath
- * encoded form provided via array of bytes.
- * @throws CertificateException if some problems occurred during
- * the decoding.
- */
- public static X509CertPathImpl getInstance(byte[] in) throws CertificateException {
- try {
- return (X509CertPathImpl) ASN1.decode(in);
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the base of encoding provided via
- * array of bytes. The format of provided encoded form is specified by
- * parameter {@code encoding}.
- *
- * @throws CertificateException if specified encoding form is not supported,
- * or some problems occurred during the decoding.
- */
- public static X509CertPathImpl getInstance(byte[] in, String encoding)
- throws CertificateException {
- try {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
-
- switch (encType) {
- case PKI_PATH:
- return (X509CertPathImpl) ASN1.decode(in);
- case PKCS7:
- return getCertPathFromContentInfo((ContentInfo) ContentInfo.ASN1.decode(in));
- default:
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- // ---------------------------------------------------------------------
- // ---- java.security.cert.CertPath abstract method implementations ----
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.CertPath#getCertificates()
- * method documentation for more info
- */
- @Override
- public List<X509Certificate> getCertificates() {
- return Collections.unmodifiableList(certificates);
- }
-
- /**
- * Returns in PkiPath format which is our default encoding.
- *
- * @see java.security.cert.CertPath#getEncoded()
- */
- @Override
- public byte[] getEncoded() throws CertificateEncodingException {
- return getEncoded(Encoding.PKI_PATH);
- }
-
- /**
- * @see #getEncoded(String)
- */
- private byte[] getEncoded(Encoding encoding) throws CertificateEncodingException {
- switch (encoding) {
- case PKI_PATH:
- if (pkiPathEncoding == null) {
- pkiPathEncoding = ASN1.encode(this);
- }
-
- return pkiPathEncoding.clone();
- case PKCS7:
- if (pkcs7Encoding == null) {
- pkcs7Encoding = PKCS7_SIGNED_DATA_OBJECT.encode(this);
- }
-
- return pkcs7Encoding.clone();
- default:
- throw new CertificateEncodingException("Unsupported encoding: " + encoding);
- }
- }
-
- /**
- * @see java.security.cert.CertPath#getEncoded(String)
- */
- @Override
- public byte[] getEncoded(String encoding) throws CertificateEncodingException {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateEncodingException("Unsupported encoding: " + encoding);
- }
-
- return getEncoded(encType);
- }
-
- /**
- * @see java.security.cert.CertPath#getEncodings()
- * method documentation for more info
- */
- @Override
- public Iterator<String> getEncodings() {
- return encodings.iterator();
- }
-
- /**
- * ASN.1 DER Encoder/Decoder for PkiPath structure.
- */
- public static final ASN1SequenceOf ASN1 = new ASN1SequenceOf(ASN1Any.getInstance()) {
- /**
- * Builds the instance of X509CertPathImpl on the base of the list of
- * ASN.1 encodings of X.509 certificates provided via PkiPath structure.
- * This method participates in decoding process.
- */
- public Object getDecodedObject(BerInputStream in) throws IOException {
- // retrieve the decoded content
- final List<byte[]> encodedCerts = (List<byte[]>) in.content;
-
- final int size = encodedCerts.size();
- final List<X509Certificate> certificates = new ArrayList<X509Certificate>(size);
-
- for (int i = size - 1; i >= 0; i--) {
- // create the X.509 certificate on the base of its encoded form
- // and add it to the list.
- certificates.add(new X509CertImpl((Certificate) Certificate.ASN1
- .decode(encodedCerts.get(i))));
- }
-
- // create and return the resulting object
- return new X509CertPathImpl(certificates, Encoding.PKI_PATH);
- }
-
- /**
- * Returns the Collection of the encoded form of certificates contained
- * in the X509CertPathImpl object to be encoded.
- * This method participates in encoding process.
- */
- public Collection<byte[]> getValues(Object object) {
- // object to be encoded
- final X509CertPathImpl cp = (X509CertPathImpl) object;
-
- // if it has no certificates in it - create the sequence of size 0
- if (cp.certificates == null) {
- return Collections.emptyList();
- }
-
- final int size = cp.certificates.size();
- final List<byte[]> encodings = new ArrayList<byte[]>(size);
-
- try {
- for (int i = size - 1; i >= 0; i--) {
- // get the encoded form of certificate and place it into the
- // list to be encoded in PkiPath format
- encodings.add(cp.certificates.get(i).getEncoded());
- }
- } catch (CertificateEncodingException e) {
- throw new IllegalArgumentException("Encoding error occurred", e);
- }
-
- return encodings;
- }
- };
-
-
- /**
- * Encoder for PKCS#7 SignedData. It is assumed that only certificate field
- * is important all other fields contain pre-calculated encodings.
- */
- private static final ASN1Sequence ASN1_SIGNED_DATA = new ASN1Sequence(
- new ASN1Type[] {
- // version ,digestAlgorithms, content info
- ASN1Any.getInstance(),
- // certificates
- new ASN1Implicit(0, ASN1),
- // set of crls is optional and is missed here
- ASN1Any.getInstance(),// signers info
- }) {
-
- // precalculated ASN.1 encodings for
- // version ,digestAlgorithms, content info field of SignedData
- private final byte[] PRECALCULATED_HEAD = new byte[] { 0x02, 0x01,
- 0x01,// version (v1)
- 0x31, 0x00,// empty set of DigestAlgorithms
- 0x30, 0x03, 0x06, 0x01, 0x00 // empty ContentInfo with oid=0
- };
-
- // precalculated empty set of SignerInfos
- private final byte[] SIGNERS_INFO = new byte[] { 0x31, 0x00 };
-
- protected void getValues(Object object, Object[] values) {
- values[0] = PRECALCULATED_HEAD;
- values[1] = object; // pass X509CertPathImpl object
- values[2] = SIGNERS_INFO;
- }
-
- // stub to prevent using the instance as decoder
- public Object decode(BerInputStream in) throws IOException {
- throw new RuntimeException(
- "Invalid use of encoder for PKCS#7 SignedData object");
- }
- };
-
- private static final ASN1Sequence PKCS7_SIGNED_DATA_OBJECT = new ASN1Sequence(
- new ASN1Type[] { ASN1Any.getInstance(), // contentType
- new ASN1Explicit(0, ASN1_SIGNED_DATA) // SignedData
- }) {
-
- // precalculated ASN.1 encoding for SignedData object oid
- private final byte[] SIGNED_DATA_OID = ASN1Oid.getInstance().encode(
- ContentInfo.SIGNED_DATA);
-
- protected void getValues(Object object, Object[] values) {
- values[0] = SIGNED_DATA_OID;
- values[1] = object; // pass X509CertPathImpl object
- }
-
- // stub to prevent using the instance as decoder
- public Object decode(BerInputStream in) throws IOException {
- throw new RuntimeException(
- "Invalid use of encoder for PKCS#7 SignedData object");
- }
- };
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
index 7c2785a..ad5ac7d 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
@@ -20,12 +20,9 @@
import java.security.Provider;
/**
- * Implementation of Provider for SecureRandom, MessageDigest and Signature
- * using a Secure Hash Algorithm, SHA-1;
- * see SECURE HASH STANDARD, FIPS PUB 180-1 (http://www.itl.nist.gov/fipspubs/fip180-1.htm) <BR>
- * <BR>
- * The implementation supports "SHA1PRNG", "SHA-1" and "SHA1withDSA" algorithms described in
- * JavaTM Cryptography Architecture, API Specification & Reference
+ * Implementation of Provider for SecureRandom. The implementation supports the
+ * "SHA1PRNG" algorithm described in JavaTM Cryptography Architecture, API
+ * Specification & Reference
*/
public final class CryptoProvider extends Provider {
@@ -36,46 +33,10 @@
* Creates a Provider and puts parameters
*/
public CryptoProvider() {
-
super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
- // names of classes implementing services
- final String MD_NAME = "org.apache.harmony.security.provider.crypto.SHA1_MessageDigestImpl";
- final String SR_NAME = "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl";
-
- final String SIGN_NAME = "org.apache.harmony.security.provider.crypto.SHA1withDSA_SignatureImpl";
-
- final String SIGN_ALIAS = "SHA1withDSA";
-
-
- final String KEYF_NAME = "org.apache.harmony.security.provider.crypto.DSAKeyFactoryImpl";
-
- put("MessageDigest.SHA-1", MD_NAME);
- put("MessageDigest.SHA-1 ImplementedIn", "Software");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
-
- put("SecureRandom.SHA1PRNG", SR_NAME);
+ put("SecureRandom.SHA1PRNG",
+ "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
-
- put("Signature.SHA1withDSA", SIGN_NAME);
- put("Signature.SHA1withDSA ImplementedIn", "Software");
- put("Alg.Alias.Signature.SHAwithDSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSAwithSHA1", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA-1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSS", SIGN_ALIAS);
-
- put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.13", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.27", SIGN_ALIAS);
-
- put("KeyFactory.DSA", KEYF_NAME);
- put("KeyFactory.DSA ImplementedIn", "Software");
- put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
- put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
deleted file mode 100644
index 690d16e..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.security.provider.crypto;
-
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.Key;
-import java.security.KeyFactorySpi;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.interfaces.DSAPublicKey;
-import java.security.spec.DSAPrivateKeySpec;
-import java.security.spec.DSAPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.KeySpec;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-
-public class DSAKeyFactoryImpl extends KeyFactorySpi {
-
- /**
- * This method generates a DSAPrivateKey object from the provided key specification.
- *
- * @param
- * keySpec - the specification (key material) for the DSAPrivateKey.
- *
- * @return
- * a DSAPrivateKey object
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec
- */
- protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
- throws InvalidKeySpecException {
-
- if (keySpec != null) {
- if (keySpec instanceof DSAPrivateKeySpec) {
-
- return new DSAPrivateKeyImpl((DSAPrivateKeySpec) keySpec);
- }
- if (keySpec instanceof PKCS8EncodedKeySpec) {
-
- return new DSAPrivateKeyImpl((PKCS8EncodedKeySpec) keySpec);
- }
- }
- throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
- }
-
- /**
- * This method generates a DSAPublicKey object from the provided key specification.
- *
- * @param
- * keySpec - the specification (key material) for the DSAPublicKey.
- *
- * @return
- * a DSAPublicKey object
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is neither DSAPublicKeySpec nor X509EncodedKeySpec
- */
- protected PublicKey engineGeneratePublic(KeySpec keySpec)
- throws InvalidKeySpecException {
-
- if (keySpec != null) {
- if (keySpec instanceof DSAPublicKeySpec) {
-
- return new DSAPublicKeyImpl((DSAPublicKeySpec) keySpec);
- }
- if (keySpec instanceof X509EncodedKeySpec) {
-
- return new DSAPublicKeyImpl((X509EncodedKeySpec) keySpec);
- }
- }
- throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
- }
-
- /**
- * This method returns a specification for the supplied key.
- *
- * The specification will be returned in the form of an object of the type
- * specified by keySpec.
- *
- * @param key -
- * either DSAPrivateKey or DSAPublicKey
- * @param keySpec -
- * either DSAPrivateKeySpec.class or DSAPublicKeySpec.class
- *
- * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is not a specification for DSAPublicKey or
- * DSAPrivateKey
- */
- protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
- throws InvalidKeySpecException {
-
- BigInteger p, q, g, x, y;
-
- if (key != null) {
- if (keySpec == null) {
- throw new NullPointerException("keySpec == null");
- }
- if (key instanceof DSAPrivateKey) {
- DSAPrivateKey privateKey = (DSAPrivateKey) key;
-
- if (keySpec.equals(DSAPrivateKeySpec.class)) {
-
- x = privateKey.getX();
-
- DSAParams params = privateKey.getParams();
-
- p = params.getP();
- q = params.getQ();
- g = params.getG();
-
- return (T) (new DSAPrivateKeySpec(x, p, q, g));
- }
-
- if (keySpec.equals(PKCS8EncodedKeySpec.class)) {
- return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
- }
-
- throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
- }
-
- if (key instanceof DSAPublicKey) {
- DSAPublicKey publicKey = (DSAPublicKey) key;
-
- if (keySpec.equals(DSAPublicKeySpec.class)) {
-
- y = publicKey.getY();
-
- DSAParams params = publicKey.getParams();
-
- p = params.getP();
- q = params.getQ();
- g = params.getG();
-
- return (T) (new DSAPublicKeySpec(y, p, q, g));
- }
-
- if (keySpec.equals(X509EncodedKeySpec.class)) {
- return (T) (new X509EncodedKeySpec(key.getEncoded()));
- }
-
- throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
- }
- }
- throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey");
- }
-
- /**
- * The method generates a DSAPublicKey object from the provided key.
- *
- * @param
- * key - a DSAPublicKey object or DSAPrivateKey object.
- *
- * @return
- * object of the same type as the "key" argument
- *
- * @throws InvalidKeyException
- * if "key" is neither DSAPublicKey nor DSAPrivateKey
- */
- protected Key engineTranslateKey(Key key) throws InvalidKeyException {
-
- if (key != null) {
- if (key instanceof DSAPrivateKey) {
-
- DSAPrivateKey privateKey = (DSAPrivateKey) key;
- DSAParams params = privateKey.getParams();
-
- try {
- return engineGeneratePrivate(new DSAPrivateKeySpec(
- privateKey.getX(), params.getP(), params.getQ(),
- params.getG()));
- } catch (InvalidKeySpecException e) {
- // Actually this exception shouldn't be thrown
- throw new InvalidKeyException("ATTENTION: InvalidKeySpecException: " + e);
- }
- }
-
- if (key instanceof DSAPublicKey) {
-
- DSAPublicKey publicKey = (DSAPublicKey) key;
- DSAParams params = publicKey.getParams();
-
- try {
- return engineGeneratePublic(new DSAPublicKeySpec(publicKey
- .getY(), params.getP(), params.getQ(), params
- .getG()));
- } catch (InvalidKeySpecException e) {
- // Actually this exception shouldn't be thrown
- throw new InvalidKeyException("ATTENTION: InvalidKeySpecException: " + e);
- }
- }
- }
- throw new InvalidKeyException("'key' is neither DSAPublicKey nor DSAPrivateKey");
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
deleted file mode 100644
index c0fc766..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
- /*
- * TODO
- * 1. The class extends the PrivateKeyImpl class in "org.apache.harmony.security" package.
- *
- * 2. See a compatibility with RI comments
- * in the below "DSAPrivateKeyImpl(PKCS8EncodedKeySpec keySpec)" constructor.
- */
-
-
-package org.apache.harmony.security.provider.crypto;
-
-import java.io.IOException;
-import java.io.NotActiveException;
-import java.math.BigInteger;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.spec.DSAParameterSpec;
-import java.security.spec.DSAPrivateKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import org.apache.harmony.security.PrivateKeyImpl;
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.pkcs8.PrivateKeyInfo;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.AlgorithmIdentifier;
-
-/**
- * The class provides DSAPrivateKey functionality by extending a class implementing PrivateKey
- * and implementing methods defined in both interfaces, DSAKey and DSAPrivateKey
- */
-public class DSAPrivateKeyImpl extends PrivateKeyImpl implements DSAPrivateKey {
-
- /**
- * @serial
- */
- private static final long serialVersionUID = -4716227614104950081L;
-
- private BigInteger x, g, p, q;
-
- private transient DSAParams params;
-
- /**
- * Creates object from DSAPrivateKeySpec.
- *
- * @param keySpec - a DSAPrivateKeySpec object
- */
- public DSAPrivateKeyImpl(DSAPrivateKeySpec keySpec) {
-
- super("DSA");
-
- PrivateKeyInfo pki;
-
- g = keySpec.getG();
- p = keySpec.getP();
- q = keySpec.getQ();
-
- ThreeIntegerSequence threeInts = new ThreeIntegerSequence(p
- .toByteArray(), q.toByteArray(), g.toByteArray());
-
- AlgorithmIdentifier ai = new AlgorithmIdentifier(AlgNameMapper
- .map2OID("DSA"),
- threeInts.getEncoded());
- x = keySpec.getX();
-
- pki = new PrivateKeyInfo(0, ai, ASN1Integer.getInstance().encode(
- x.toByteArray()), null);
-
- setEncoding(pki.getEncoded());
-
- params = new DSAParameterSpec(p, q, g);
- }
-
- /**
- * Creates object from PKCS8EncodedKeySpec.
- *
- * @param keySpec - a XPKCS8EncodedKeySpec object
- *
- * @throws InvalidKeySpecException - if key data cannot be obtain from encoded format
- */
- public DSAPrivateKeyImpl(PKCS8EncodedKeySpec keySpec)
- throws InvalidKeySpecException {
-
- super("DSA");
-
- AlgorithmIdentifier ai;
- ThreeIntegerSequence threeInts = null;
-
- String alg, algName;
-
- byte[] encoding = keySpec.getEncoded();
-
- PrivateKeyInfo privateKeyInfo = null;
-
- try {
- privateKeyInfo = (PrivateKeyInfo) PrivateKeyInfo.ASN1
- .decode(encoding);
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode keySpec encoding: " + e);
- }
-
- try {
- x = new BigInteger((byte[]) ASN1Integer.getInstance().decode(
- privateKeyInfo.getPrivateKey()));
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
-
- ai = privateKeyInfo.getAlgorithmIdentifier();
- try {
- threeInts = (ThreeIntegerSequence) ThreeIntegerSequence.ASN1
- .decode(ai.getParameters());
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
- p = new BigInteger(threeInts.p);
- q = new BigInteger(threeInts.q);
- g = new BigInteger(threeInts.g);
- params = new DSAParameterSpec(p, q, g);
- setEncoding(encoding);
-
- /*
- * the following code implements RI behavior
- */
- alg = ai.getAlgorithm();
- algName = AlgNameMapper.map2AlgName(alg);
- setAlgorithm(algName == null ? alg : algName);
- }
-
- public BigInteger getX() {
- return x;
- }
-
- public DSAParams getParams() {
- return params;
- }
-
- private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
- in.defaultReadObject();
- params = new DSAParameterSpec(p, q, g);
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
deleted file mode 100644
index 6b35970..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
- /*
- * TODO
- * 1. The class extends the PublicKeyImpl class in "org.apache.harmony.security" package.
- *
- * 2. The class uses methods in the auxiliary non-public "ThreeIntegerSequence" class
- * defined along with the "DSAPrivateKeyImpl" class.
- *
- * 3. See a compatibility with RI comments
- * in the below "DSAPublicKeyImpl(X509EncodedKeySpec keySpec)" constructor.
- */
-
-package org.apache.harmony.security.provider.crypto;
-
-import java.io.IOException;
-import java.io.NotActiveException;
-import java.math.BigInteger;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPublicKey;
-import java.security.spec.DSAParameterSpec;
-import java.security.spec.DSAPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.X509EncodedKeySpec;
-import org.apache.harmony.security.PublicKeyImpl;
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.AlgorithmIdentifier;
-import org.apache.harmony.security.x509.SubjectPublicKeyInfo;
-
-/**
- * The class provides DSAPublicKey functionality by extending a class implementing PublicKey
- * and implementing methods defined in both interfaces, DSAKey and DSAPublicKey
- */
-public class DSAPublicKeyImpl extends PublicKeyImpl implements DSAPublicKey {
-
- /**
- * @serial
- */
- private static final long serialVersionUID = -2279672131310978336L;
-
- private BigInteger y, g, p, q;
-
- private transient DSAParams params;
-
- /**
- * Creates object from DSAPublicKeySpec.
- *
- * @param keySpec - a DSAPublicKeySpec object
- */
- public DSAPublicKeyImpl(DSAPublicKeySpec keySpec) {
-
- super("DSA");
-
- SubjectPublicKeyInfo spki;
-
- p = keySpec.getP();
- q = keySpec.getQ();
- g = keySpec.getG();
-
- ThreeIntegerSequence threeInts = new ThreeIntegerSequence(p
- .toByteArray(), q.toByteArray(), g.toByteArray());
-
- AlgorithmIdentifier ai = new AlgorithmIdentifier(AlgNameMapper
- .map2OID("DSA"),
- threeInts.getEncoded());
-
- y = keySpec.getY();
-
- spki = new SubjectPublicKeyInfo(ai, ASN1Integer.getInstance().encode(
- y.toByteArray()));
- setEncoding(spki.getEncoded());
-
- params = (DSAParams) (new DSAParameterSpec(p, q, g));
- }
-
- /**
- * Creates object from X509EncodedKeySpec.
- *
- * @param keySpec - a X509EncodedKeySpec object
- *
- * @throws InvalidKeySpecException - if key data cannot be obtain from encoded format
- */
- public DSAPublicKeyImpl(X509EncodedKeySpec keySpec)
- throws InvalidKeySpecException {
-
- super("DSA");
-
- AlgorithmIdentifier ai;
- ThreeIntegerSequence threeInts = null;
-
- SubjectPublicKeyInfo subjectPublicKeyInfo = null;
-
- byte[] encoding = keySpec.getEncoded();
-
- String alg, algName;
-
- try {
- subjectPublicKeyInfo = (SubjectPublicKeyInfo) SubjectPublicKeyInfo.ASN1
- .decode(encoding);
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode keySpec encoding: " + e);
- }
-
- try {
- y = new BigInteger((byte[]) ASN1Integer.getInstance().decode(
- subjectPublicKeyInfo.getSubjectPublicKey()));
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
-
- ai = subjectPublicKeyInfo.getAlgorithmIdentifier();
-
- try {
- threeInts = (ThreeIntegerSequence) ThreeIntegerSequence.ASN1
- .decode(ai.getParameters());
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
- p = new BigInteger(threeInts.p);
- q = new BigInteger(threeInts.q);
- g = new BigInteger(threeInts.g);
- params = (DSAParams) (new DSAParameterSpec(p, q, g));
-
- setEncoding(encoding);
-
- /*
- * the following code implements RI behavior
- */
- alg = ai.getAlgorithm();
- algName = AlgNameMapper.map2AlgName(alg);
- setAlgorithm(algName == null ? alg : algName);
- }
-
- /**
- * @return
- * a value of a public key (y).
- */
- public BigInteger getY() {
- return y;
- }
-
- /**
- * @return
- * DSA key parameters (p, q, g).
- */
- public DSAParams getParams() {
- return params;
- }
-
- private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
- in.defaultReadObject();
- params = new DSAParameterSpec(p, q, g);
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
deleted file mode 100644
index 3f41f18..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.security.provider.crypto;
-
-import java.security.DigestException;
-import java.security.MessageDigestSpi;
-import java.util.Arrays;
-
-import static org.apache.harmony.security.provider.crypto.SHA1Constants.*;
-
-/**
- * This class extends the MessageDigestSpi class implementing all its abstract methods;
- * it overrides the "Object clone()" and "int engineGetDigestLength()" methods. <BR>
- * The class implements the Cloneable interface.
- */
-public class SHA1_MessageDigestImpl extends MessageDigestSpi implements Cloneable {
- private int[] buffer; // buffer has the following structure:
- // - 0-16 - frame for accumulating a message
- // - 17-79 - for SHA1Impl methods
- // - 80 - unused
- // - 81 - to store length of the message
- // - 82-86 - frame for current message digest
-
- private byte[] oneByte; // one byte buffer needed to use in engineUpdate(byte)
- // having buffer as private field is just optimization
-
- private long messageLength; // total length of bytes supplied by user
-
-
- /**
- * The constructor creates needed buffers and sets the engine at initial state
- */
- public SHA1_MessageDigestImpl() {
-
- // BYTES_OFFSET +6 is minimal length required by methods in SHA1Impl
- buffer = new int[BYTES_OFFSET +6];
-
- oneByte = new byte[1];
-
- engineReset();
- }
-
-
- /**
- * The method performs final actions and invokes the "computeHash(int[])" method.
- * In case if there is no enough words in current frame
- * after processing its data, extra frame is prepared and
- * the "computeHash(int[])" method is invoked second time. <BR>
- *
- * After processing, the method resets engine's state
- *
- * @param
- * digest - byte array
- * @param
- * offset - offset in digest
- */
- private void processDigest(byte[] digest, int offset) {
-
- int i, j; // implementation variables
- int lastWord; //
-
- long nBits = messageLength <<3 ; // length has to be calculated before padding
-
- engineUpdate( (byte) 0x80 ); // beginning byte in padding
-
- i = 0; // i contains number of beginning word for following loop
-
- lastWord = (buffer[BYTES_OFFSET] + 3)>>2 ; // computing of # of full words by shifting
- // # of bytes
-
- // possible cases:
- //
- // - buffer[BYTES_OFFSET] == 0 - buffer frame is empty,
- // padding byte was 64th in previous frame
- // current frame should contain only message's length
- //
- // - lastWord < 14 - two last, these are 14 & 15, words in 16 word frame are free;
- // no extra frame needed
- // - lastWord = 14 - only one last, namely 15-th, word in frame doesn't contain bytes;
- // extra frame is needed
- // - lastWord > 14 - last word in frame is not full;
- // extra frame is needed
-
- if ( buffer[BYTES_OFFSET] != 0 ) {
-
- if ( lastWord < 15 ) {
- i = lastWord;
- } else {
- if ( lastWord == 15 ) {
- buffer[15] = 0; // last word in frame is set to "0"
- }
- SHA1Impl.computeHash(buffer);
- i = 0;
- }
- }
- Arrays.fill(buffer, i, 14, 0);
-
- buffer[14] = (int)( nBits >>>32 );
- buffer[15] = (int)( nBits & 0xFFFFFFFF );
- SHA1Impl.computeHash(buffer);
-
- // converting 5-word frame into 20 bytes
- j = offset;
- for ( i = HASH_OFFSET; i < HASH_OFFSET +5; i++ ) {
- int k = buffer[i];
- digest[j ] = (byte) ( k >>>24 ); // getting first byte from left
- digest[j+1] = (byte) ( k >>>16 ); // getting second byte from left
- digest[j+2] = (byte) ( k >>> 8 ); // getting third byte from left
- digest[j+3] = (byte) ( k ); // getting fourth byte from left
- j += 4;
- }
-
- engineReset();
- }
-
- // methods specified in java.security.MessageDigestSpi
-
- /**
- * Returns a "deep" copy of this SHA1MDImpl object. <BR>
- *
- * The method overrides "clone()" in class Object. <BR>
- *
- * @return
- * a clone of this object
- */
- public Object clone() throws CloneNotSupportedException {
- SHA1_MessageDigestImpl cloneObj = (SHA1_MessageDigestImpl) super.clone();
- cloneObj.buffer = buffer.clone();
- cloneObj.oneByte = oneByte.clone();
- return cloneObj;
- }
-
-
- /**
- * Computes a message digest value. <BR>
- *
- * The method resets the engine. <BR>
- *
- * The method overrides "engineDigest()" in class MessageDigestSpi. <BR>
- *
- * @return
- * byte array containing message digest value
- */
- protected byte[] engineDigest() {
- byte[] hash = new byte[DIGEST_LENGTH];
- processDigest(hash, 0);
- return hash;
- }
-
-
- /**
- * Computes message digest value.
- * Upon return, the value is stored in "buf" buffer beginning "offset" byte. <BR>
- *
- * The method resets the engine. <BR>
- *
- * The method overrides "engineDigest(byte[],int,int) in class MessageDigestSpi.
- *
- * @param
- * buf byte array to store a message digest returned
- * @param
- * offset a position in the array for first byte of the message digest
- * @param
- * len number of bytes within buffer allotted for the message digest;
- * as this implementation doesn't provide partial digests,
- * len should be >= 20, DigestException is thrown otherwise
- * @return
- * the length of the message digest stored in the "buf" buffer;
- * in this implementation the length=20
- *
- * @throws IllegalArgumentException
- * if null is passed to the "buf" argument <BR>
- * if offset + len > buf.length <BR>
- * if offset > buf.length or len > buf.length
- *
- * @throws DigestException
- * if len < 20
- *
- * @throws ArrayIndexOutOfBoundsException
- * if offset < 0
- */
- protected int engineDigest(byte[] buf, int offset, int len) throws DigestException {
- if (buf == null) {
- throw new IllegalArgumentException("buf == null");
- }
- if (offset > buf.length || len > buf.length || (len + offset) > buf.length) {
- throw new IllegalArgumentException();
- }
- if (len < DIGEST_LENGTH) {
- throw new DigestException("len < DIGEST_LENGTH");
- }
- if (offset < 0) {
- throw new ArrayIndexOutOfBoundsException(offset);
- }
-
- processDigest(buf, offset);
-
- return DIGEST_LENGTH;
- }
-
-
- /**
- * Returns a message digest length. <BR>
- *
- * The method overrides "engineGetDigestLength()" in class MessageDigestSpi. <BR>
- *
- * @return
- * total length of current message digest as an int value
- */
- protected int engineGetDigestLength() {
- return DIGEST_LENGTH;
- }
-
-
- /**
- * Resets the engine. <BR>
- *
- * The method overrides "engineReset()" in class MessageDigestSpi. <BR>
- */
- protected void engineReset() {
-
- messageLength = 0;
-
- buffer[BYTES_OFFSET] = 0;
- buffer[HASH_OFFSET ] = H0;
- buffer[HASH_OFFSET +1] = H1;
- buffer[HASH_OFFSET +2] = H2;
- buffer[HASH_OFFSET +3] = H3;
- buffer[HASH_OFFSET +4] = H4;
- }
-
-
- /**
- * Supplements a byte to current message. <BR>
- *
- * The method overrides "engineUpdate(byte)" in class MessageDigestSpi. <BR>
- *
- * @param
- * input byte to add to current message
- */
- protected void engineUpdate(byte input) {
-
- oneByte[0] = input;
- SHA1Impl.updateHash( buffer, oneByte, 0, 0 );
- messageLength++;
- }
-
-
- /**
- * Updates current message. <BR>
- *
- * The method overrides "engineUpdate(byte[],int,int)" in class MessageDigestSpi. <BR>
- *
- * The method silently returns if "len" <= 0.
- *
- * @param
- * input a byte array
- * @param
- * offset a number of first byte in the "input" array to use for updating
- * @param
- * len a number of bytes to use
- *
- * @throws NullPointerException
- * if null is passed to the "buf" argument
- *
- * @throws IllegalArgumentException
- * if offset > buf.length or len > buf.length or
- * (len + offset) > buf.length
- * @throws ArrayIndexOutOfBoundsException
- * offset < 0
- */
- protected void engineUpdate(byte[] input, int offset, int len) {
- if (input == null) {
- throw new IllegalArgumentException("input == null");
- }
- if (len <= 0) {
- return;
- }
- if (offset < 0) {
- throw new ArrayIndexOutOfBoundsException(offset);
- }
- if (offset > input.length || len > input.length || (len + offset) > input.length) {
- throw new IllegalArgumentException();
- }
-
- SHA1Impl.updateHash(buffer, input, offset, offset + len -1 );
- messageLength += len;
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java
deleted file mode 100644
index 2958e00..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java
+++ /dev/null
@@ -1,423 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.security.provider.crypto;
-
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.InvalidParameterException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.interfaces.DSAKey;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.interfaces.DSAPublicKey;
-
-public class SHA1withDSA_SignatureImpl extends Signature {
-
- private MessageDigest msgDigest;
-
- private DSAKey dsaKey;
-
- /**
- * The solo constructor.
- */
- public SHA1withDSA_SignatureImpl() throws NoSuchAlgorithmException {
-
- super("SHA1withDSA");
-
- msgDigest = MessageDigest.getInstance("SHA1");
- }
-
- /**
- * Deprecated method.
- *
- * @return
- * null
- */
- protected Object engineGetParameter(String param)
- throws InvalidParameterException {
- if (param == null) {
- throw new NullPointerException("param == null");
- }
- return null;
- }
-
- /**
- * Initializes this signature object with PrivateKey object
- * passed as argument to the method.
- *
- * @params
- * privateKey DSAPrivateKey object
- * @throws
- * InvalidKeyException if privateKey is not DSAPrivateKey object
- */
- protected void engineInitSign(PrivateKey privateKey)
- throws InvalidKeyException {
-
- DSAParams params;
-
- // parameters and private key
- BigInteger p, q, x;
-
- int n;
-
- if (privateKey == null || !(privateKey instanceof DSAPrivateKey)) {
- throw new InvalidKeyException();
- }
-
- params = ((DSAPrivateKey) privateKey).getParams();
- p = params.getP();
- q = params.getQ();
- x = ((DSAPrivateKey) privateKey).getX();
-
- // checks described in DSA standard
- n = p.bitLength();
- if (p.compareTo(BigInteger.valueOf(1)) != 1 || n < 512 || n > 1024 || (n & 077) != 0) {
- throw new InvalidKeyException("bad p");
- }
- if (q.signum() != 1 && q.bitLength() != 160) {
- throw new InvalidKeyException("bad q");
- }
- if (x.signum() != 1 || x.compareTo(q) != -1) {
- throw new InvalidKeyException("x <= 0 || x >= q");
- }
-
- dsaKey = (DSAKey) privateKey;
-
- msgDigest.reset();
- }
-
- /**
- * Initializes this signature object with PublicKey object
- * passed as argument to the method.
- *
- * @params
- * publicKey DSAPublicKey object
- * @throws
- * InvalidKeyException if publicKey is not DSAPublicKey object
- */
- protected void engineInitVerify(PublicKey publicKey)
- throws InvalidKeyException {
-
- // parameters and public key
- BigInteger p, q, y;
-
- int n1;
-
- if (publicKey == null || !(publicKey instanceof DSAPublicKey)) {
- throw new InvalidKeyException("publicKey is not an instance of DSAPublicKey");
- }
-
- DSAParams params = ((DSAPublicKey) publicKey).getParams();
- p = params.getP();
- q = params.getQ();
- y = ((DSAPublicKey) publicKey).getY();
-
- // checks described in DSA standard
- n1 = p.bitLength();
- if (p.compareTo(BigInteger.valueOf(1)) != 1 || n1 < 512 || n1 > 1024 || (n1 & 077) != 0) {
- throw new InvalidKeyException("bad p");
- }
- if (q.signum() != 1 || q.bitLength() != 160) {
- throw new InvalidKeyException("bad q");
- }
- if (y.signum() != 1) {
- throw new InvalidKeyException("y <= 0");
- }
-
- dsaKey = (DSAKey) publicKey;
-
- msgDigest.reset();
- }
-
- /*
- * Deprecated method.
- *
- * @throws
- * InvalidParameterException
- */
- protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
- if (param == null) {
- throw new NullPointerException("param == null");
- }
- throw new InvalidParameterException("invalid parameter for this engine");
- }
-
- /**
- * Returns signature bytes as byte array containing
- * ASN1 representation for two BigInteger objects
- * which is SEQUENCE of two INTEGERS.
- * Length of sequence varies from less than 46 to 48.
- *
- * Resets object to the state it was in
- * when previous call to either "initSign" method was called.
- *
- * @return
- * byte array containing signature in ASN1 representation
- * @throws
- * SignatureException if object's state is not SIGN or
- * signature algorithm cannot process data
- */
-
- protected byte[] engineSign() throws SignatureException {
-
- // names of below BigIntegers are the same as they are defined in DSA standard
- BigInteger r = null;
- BigInteger s = null;
- BigInteger k = null;
-
- // parameters and private key
- BigInteger p, q, g, x;
-
- // BigInteger for message digest
- BigInteger digestBI;
-
- // various byte array being used in computing signature
- byte[] randomBytes;
- byte[] rBytes;
- byte[] sBytes;
- byte[] signature;
-
- int n, n1, n2;
-
- DSAParams params;
-
- if (appRandom == null) {
- appRandom = new SecureRandom();
- }
-
- params = dsaKey.getParams();
- p = params.getP();
- q = params.getQ();
- g = params.getG();
- x = ((DSAPrivateKey) dsaKey).getX();
-
- // forming signature according algorithm described in chapter 5 of DSA standard
-
- digestBI = new BigInteger(1, msgDigest.digest());
-
- randomBytes = new byte[20];
-
- for (;;) {
-
- appRandom.nextBytes(randomBytes);
-
- k = new BigInteger(1, randomBytes);
- if (k.compareTo(q) != -1) {
- continue;
- }
- r = g.modPow(k, p).mod(q);
- if (r.signum() == 0) {
- continue;
- }
-
- s = k.modInverse(q).multiply(digestBI.add(x.multiply(r)).mod(q))
- .mod(q);
-
- if (s.signum() != 0) {
- break;
- }
- }
-
- // forming signature's ASN1 representation which is SEQUENCE of two INTEGERs
- //
- rBytes = r.toByteArray();
- n1 = rBytes.length;
- if ((rBytes[0] & 0x80) != 0) {
- n1++;
- }
- sBytes = s.toByteArray();
- n2 = sBytes.length;
- if ((sBytes[0] & 0x80) != 0) {
- n2++;
- }
-
- signature = new byte[6 + n1 + n2]; // 48 is max. possible length of signature
- signature[0] = (byte) 0x30; // ASN1 SEQUENCE tag
- signature[1] = (byte) (4 + n1 + n2); // total length of two INTEGERs
- signature[2] = (byte) 0x02; // ASN1 INTEGER tag
- signature[3] = (byte) n1; // length of r
- signature[4 + n1] = (byte) 0x02; // ASN1 INTEGER tag
- signature[5 + n1] = (byte) n2; // length of s
-
- if (n1 == rBytes.length) {
- n = 4;
- } else {
- n = 5;
- }
- System.arraycopy(rBytes, 0, signature, n, rBytes.length);
-
- if (n2 == sBytes.length) {
- n = 6 + n1;
- } else {
- n = 7 + n1;
- }
- System.arraycopy(sBytes, 0, signature, n, sBytes.length);
-
- return signature;
- }
-
- /**
- * Updates data to sign or to verify.
- *
- * @params
- * b byte to update
- * @throws
- * SignatureException if object was not initialized for signing or verifying
- */
- protected void engineUpdate(byte b) throws SignatureException {
-
- msgDigest.update(b);
- }
-
- /**
- * Updates data to sign or to verify.
- *
- * @params
- * b byte array containing bytes to update
- * @params
- * off offset in byte array to start from
- * @params
- * len number of bytes to use for updating
- * @throws
- * SignatureException if object was not initialized for signing or verifying
- */
- protected void engineUpdate(byte[] b, int off, int len)
- throws SignatureException {
-
- msgDigest.update(b, off, len);
- }
-
- private boolean checkSignature(byte[] sigBytes, int offset, int length)
- throws SignatureException {
-
- // names of below BigIntegers are the same as they are defined in DSA standard
- BigInteger r, s, w;
- BigInteger u1, u2, v;
-
- // parameters and public key
- BigInteger p, q, g, y;
-
- DSAParams params;
-
- int n1, n2;
-
- byte[] bytes;
- byte[] digest;
-
- // checking up on signature's ASN1
- try {
- byte dummy;
- n1 = sigBytes[offset + 3];
- n2 = sigBytes[offset + n1 + 5];
-
- if (sigBytes[offset + 0] != 0x30 || sigBytes[offset + 2] != 2
- || sigBytes[offset + n1 + 4] != 2
- || sigBytes[offset + 1] != (n1 + n2 + 4) || n1 > 21
- || n2 > 21
- || (length != 0 && (sigBytes[offset + 1] + 2) > length)) {
- throw new SignatureException("signature bytes have invalid encoding");
- }
-
- dummy = sigBytes[5 + n1 + n2]; // to check length of sigBytes
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new SignatureException("bad argument: byte[] is too small");
- }
-
- digest = msgDigest.digest();
-
- bytes = new byte[n1];
- System.arraycopy(sigBytes, offset + 4, bytes, 0, n1);
- r = new BigInteger(bytes);
-
- bytes = new byte[n2];
- System.arraycopy(sigBytes, offset + 6 + n1, bytes, 0, n2);
- s = new BigInteger(bytes);
-
- params = dsaKey.getParams();
- p = params.getP();
- q = params.getQ();
- g = params.getG();
- y = ((DSAPublicKey) dsaKey).getY();
-
- // forming signature according algorithm described in chapter 6 of DSA standard
-
- if (r.signum() != 1 || r.compareTo(q) != -1 || s.signum() != 1
- || s.compareTo(q) != -1) {
- return false;
- }
-
- w = s.modInverse(q);
-
- u1 = (new BigInteger(1, digest)).multiply(w).mod(q);
- u2 = r.multiply(w).mod(q);
-
- v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
-
- if (v.compareTo(r) != 0) {
- return false;
- }
- return true;
- }
-
- /**
- * Verifies the signature bytes.
- *
- * @params
- * sigBytes byte array with signature bytes to verify.
- * @return
- * true if signature bytes were verified, false otherwise
- * @throws
- * SignatureException if object's state is not VERIFY or
- * signature format is not ASN1 representation or
- * signature algorithm cannot process data
- */
- protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
- if (sigBytes == null) {
- throw new NullPointerException("sigBytes == null");
- }
-
- return checkSignature(sigBytes, 0, 0);
- }
-
- /**
- * Verifies the signature bytes.
- *
- * @params
- * sigBytes byte array with signature bytes to verify.
- * @params
- * offset index in sigBytes to start from
- * @params
- * length number of bytes allotted for signature
- * @return
- * true if signature bytes were verified, false otherwise
- * @throws
- * SignatureException if object's state is not VERIFY or
- * signature format is not ASN1 representation or
- * signature algorithm cannot process data
- */
- protected boolean engineVerify(byte[] sigBytes, int offset, int length)
- throws SignatureException {
- return checkSignature(sigBytes, offset, length);
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java
deleted file mode 100644
index 4f4232a..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.security.provider.crypto;
-
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.asn1.ASN1Sequence;
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.BerInputStream;
-
-
-/**
- * The auxiliary class providing means to process ASN1Sequence of three Integers.
- * Such sequences are parts of ASN1 encoded formats for DSA private and public keys.
- */
-class ThreeIntegerSequence {
-
- byte[] p, q, g;
-
- private byte[] encoding;
-
- ThreeIntegerSequence(byte[] p, byte[] q, byte[] g) {
-
- this.p = p;
- this.q = q;
- this.g = g;
- encoding = null;
- }
-
- public byte[] getEncoded() {
- if (encoding == null) {
- encoding = ASN1.encode(this);
- }
- return encoding;
- }
-
- public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
- ASN1Integer.getInstance(), ASN1Integer.getInstance(),
- ASN1Integer.getInstance() }) {
-
- protected Object getDecodedObject(BerInputStream in) {
-
- Object[] values = (Object[]) in.content;
-
- return new ThreeIntegerSequence((byte[]) values[0],
- (byte[]) values[1], (byte[]) values[2]);
- }
-
- protected void getValues(Object object, Object[] values) {
-
- ThreeIntegerSequence mySeq = (ThreeIntegerSequence) object;
-
- values[0] = mySeq.p;
- values[1] = mySeq.q;
- values[2] = mySeq.g;
- }
- };
-}
diff --git a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
index db6f4ef..fa6308e 100644
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
+++ b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
@@ -48,7 +48,7 @@
private boolean inStartElement = false;
private int attributeCount = -1;
- private int attributePointer = 0;
+ private long attributePointer = 0;
private final Locator locator = new ExpatLocator();
@@ -129,7 +129,7 @@
* @param attributeCount number of attributes
*/
/*package*/ void startElement(String uri, String localName, String qName,
- int attributePointer, int attributeCount) throws SAXException {
+ long attributePointer, int attributeCount) throws SAXException {
ContentHandler contentHandler = xmlReader.contentHandler;
if (contentHandler == null) {
return;
@@ -772,7 +772,7 @@
@Override
void startElement(String uri, String localName, String qName,
- int attributePointer, int attributeCount) throws SAXException {
+ long attributePointer, int attributeCount) throws SAXException {
/*
* Skip topmost element generated by our workaround in
* {@link #handleExternalEntity}.
diff --git a/luni/src/main/native/realpath.cpp b/luni/src/main/native/canonicalize_path.cpp
similarity index 98%
rename from luni/src/main/native/realpath.cpp
rename to luni/src/main/native/canonicalize_path.cpp
index d1960a4..b2a2a01 100644
--- a/luni/src/main/native/realpath.cpp
+++ b/luni/src/main/native/canonicalize_path.cpp
@@ -45,7 +45,7 @@
*
* This implementation also removes all the fixed-length buffers of the C original.
*/
-bool realpath(const char* path, std::string& resolved) {
+bool canonicalize_path(const char* path, std::string& resolved) {
// 'path' must be an absolute path.
if (path[0] != '/') {
errno = EINVAL;
diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp
index c217ea2..046fc4f 100644
--- a/luni/src/main/native/java_io_File.cpp
+++ b/luni/src/main/native/java_io_File.cpp
@@ -22,7 +22,6 @@
#include "JniException.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
-#include "readlink.h"
#include "toStringArray.h"
#include <string>
@@ -39,96 +38,82 @@
#include <unistd.h>
#include <utime.h>
-static jstring File_readlink(JNIEnv* env, jclass, jstring javaPath) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return NULL;
- }
+static jstring File_canonicalizePath(JNIEnv* env, jclass, jstring javaPath) {
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return NULL;
+ }
- std::string result;
- if (!readlink(path.c_str(), result)) {
- jniThrowIOException(env, errno);
- return NULL;
- }
- return env->NewStringUTF(result.c_str());
-}
-
-static jstring File_realpath(JNIEnv* env, jclass, jstring javaPath) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return NULL;
- }
-
- extern bool realpath(const char* path, std::string& resolved);
- std::string result;
- if (!realpath(path.c_str(), result)) {
- jniThrowIOException(env, errno);
- return NULL;
- }
- return env->NewStringUTF(result.c_str());
+ extern bool canonicalize_path(const char* path, std::string& resolved);
+ std::string result;
+ if (!canonicalize_path(path.c_str(), result)) {
+ jniThrowIOException(env, errno);
+ return NULL;
+ }
+ return env->NewStringUTF(result.c_str());
}
static jboolean File_setLastModifiedImpl(JNIEnv* env, jclass, jstring javaPath, jlong ms) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return JNI_FALSE;
- }
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return JNI_FALSE;
+ }
- // We want to preserve the access time.
- struct stat sb;
- if (stat(path.c_str(), &sb) == -1) {
- return JNI_FALSE;
- }
+ // We want to preserve the access time.
+ struct stat sb;
+ if (stat(path.c_str(), &sb) == -1) {
+ return JNI_FALSE;
+ }
- // TODO: we could get microsecond resolution with utimes(3), "legacy" though it is.
- utimbuf times;
- times.actime = sb.st_atime;
- times.modtime = static_cast<time_t>(ms / 1000);
- return (utime(path.c_str(), ×) == 0);
+ // TODO: we could get microsecond resolution with utimes(3), "legacy" though it is.
+ utimbuf times;
+ times.actime = sb.st_atime;
+ times.modtime = static_cast<time_t>(ms / 1000);
+ return (utime(path.c_str(), ×) == 0);
}
// Iterates over the filenames in the given directory.
class ScopedReaddir {
-public:
- ScopedReaddir(const char* path) {
- mDirStream = opendir(path);
- mIsBad = (mDirStream == NULL);
+ public:
+ ScopedReaddir(const char* path) {
+ mDirStream = opendir(path);
+ mIsBad = (mDirStream == NULL);
+ }
+
+ ~ScopedReaddir() {
+ if (mDirStream != NULL) {
+ closedir(mDirStream);
}
+ }
- ~ScopedReaddir() {
- if (mDirStream != NULL) {
- closedir(mDirStream);
- }
+ // Returns the next filename, or NULL.
+ const char* next() {
+ if (mIsBad) {
+ return NULL;
}
-
- // Returns the next filename, or NULL.
- const char* next() {
- if (mIsBad) {
- return NULL;
- }
- errno = 0;
- dirent* result = readdir(mDirStream);
- if (result != NULL) {
- return result->d_name;
- }
- if (errno != 0) {
- mIsBad = true;
- }
- return NULL;
+ errno = 0;
+ dirent* result = readdir(mDirStream);
+ if (result != NULL) {
+ return result->d_name;
}
-
- // Has an error occurred on this stream?
- bool isBad() const {
- return mIsBad;
+ if (errno != 0) {
+ mIsBad = true;
}
+ return NULL;
+ }
-private:
- DIR* mDirStream;
- bool mIsBad;
+ // Has an error occurred on this stream?
+ bool isBad() const {
+ return mIsBad;
+ }
- // Disallow copy and assignment.
- ScopedReaddir(const ScopedReaddir&);
- void operator=(const ScopedReaddir&);
+ private:
+ DIR* mDirStream;
+ bool mIsBad;
+
+ // Disallow copy and assignment.
+ ScopedReaddir(const ScopedReaddir&);
+ void operator=(const ScopedReaddir&);
};
typedef std::vector<std::string> DirEntries;
@@ -136,38 +121,37 @@
// Reads the directory referred to by 'pathBytes', adding each directory entry
// to 'entries'.
static bool readDirectory(JNIEnv* env, jstring javaPath, DirEntries& entries) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return false;
- }
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return false;
+ }
- ScopedReaddir dir(path.c_str());
- const char* filename;
- while ((filename = dir.next()) != NULL) {
- if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) {
- // TODO: this hides allocation failures from us. Push directory iteration up into Java?
- entries.push_back(filename);
- }
+ ScopedReaddir dir(path.c_str());
+ const char* filename;
+ while ((filename = dir.next()) != NULL) {
+ if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) {
+ // TODO: this hides allocation failures from us. Push directory iteration up into Java?
+ entries.push_back(filename);
}
- return !dir.isBad();
+ }
+ return !dir.isBad();
}
static jobjectArray File_listImpl(JNIEnv* env, jclass, jstring javaPath) {
- // Read the directory entries into an intermediate form.
- DirEntries entries;
- if (!readDirectory(env, javaPath, entries)) {
- return NULL;
- }
- // Translate the intermediate form into a Java String[].
- return toStringArray(env, entries);
+ // Read the directory entries into an intermediate form.
+ DirEntries entries;
+ if (!readDirectory(env, javaPath, entries)) {
+ return NULL;
+ }
+ // Translate the intermediate form into a Java String[].
+ return toStringArray(env, entries);
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(File, listImpl, "(Ljava/lang/String;)[Ljava/lang/String;"),
- NATIVE_METHOD(File, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(File, realpath, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(File, setLastModifiedImpl, "(Ljava/lang/String;J)Z"),
+ NATIVE_METHOD(File, canonicalizePath, "(Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(File, listImpl, "(Ljava/lang/String;)[Ljava/lang/String;"),
+ NATIVE_METHOD(File, setLastModifiedImpl, "(Ljava/lang/String;J)Z"),
};
void register_java_io_File(JNIEnv* env) {
- jniRegisterNativeMethods(env, "java/io/File", gMethods, NELEM(gMethods));
+ jniRegisterNativeMethods(env, "java/io/File", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp b/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
index 5d715c9..ce8a72c 100644
--- a/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
+++ b/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
@@ -143,19 +143,19 @@
return it->following(offset);
}
-static jint NativeBreakIterator_getCharacterInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getCharacterInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createCharacterInstance);
}
-static jint NativeBreakIterator_getLineInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getLineInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createLineInstance);
}
-static jint NativeBreakIterator_getSentenceInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getSentenceInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createSentenceInstance);
}
-static jint NativeBreakIterator_getWordInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getWordInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createWordInstance);
}
diff --git a/luni/src/main/native/libcore_icu_NativeCollation.cpp b/luni/src/main/native/libcore_icu_NativeCollation.cpp
index f265bb5..b8603bd 100644
--- a/luni/src/main/native/libcore_icu_NativeCollation.cpp
+++ b/luni/src/main/native/libcore_icu_NativeCollation.cpp
@@ -179,7 +179,7 @@
NATIVE_METHOD(NativeCollation, closeElements, "(J)V"),
NATIVE_METHOD(NativeCollation, compare, "(JLjava/lang/String;Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCollation, getAttribute, "(JI)I"),
- NATIVE_METHOD(NativeCollation, getCollationElementIterator, "(JLjava/lang/String;)I"),
+ NATIVE_METHOD(NativeCollation, getCollationElementIterator, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCollation, getMaxExpansion, "(JI)I"),
NATIVE_METHOD(NativeCollation, getOffset, "(J)I"),
NATIVE_METHOD(NativeCollation, getRules, "(J)Ljava/lang/String;"),
diff --git a/luni/src/main/native/libcore_io_Memory.cpp b/luni/src/main/native/libcore_io_Memory.cpp
index 2cef410..9edbfb8 100644
--- a/luni/src/main/native/libcore_io_Memory.cpp
+++ b/luni/src/main/native/libcore_io_Memory.cpp
@@ -38,8 +38,8 @@
#define LONG_ALIGNMENT_MASK 0x7
#define INT_ALIGNMENT_MASK 0x3
#define SHORT_ALIGNMENT_MASK 0x1
-#elif defined(__i386__) || defined(__x86_64__)
-// x86 can load anything at any alignment.
+#elif defined(__aarch64__) || defined(__i386__) || defined(__x86_64__)
+// These architectures can load anything at any alignment.
#define LONG_ALIGNMENT_MASK 0x0
#define INT_ALIGNMENT_MASK 0x0
#define SHORT_ALIGNMENT_MASK 0x0
diff --git a/luni/src/main/native/libcore_io_Posix.cpp b/luni/src/main/native/libcore_io_Posix.cpp
index 67c871a..1f38a57 100644
--- a/luni/src/main/native/libcore_io_Posix.cpp
+++ b/luni/src/main/native/libcore_io_Posix.cpp
@@ -24,12 +24,13 @@
#include "JniException.h"
#include "NetworkUtilities.h"
#include "Portability.h"
+#include "readlink.h"
#include "ScopedBytes.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
-#include "UniquePtr.h"
#include "toStringArray.h"
+#include "UniquePtr.h"
#include <arpa/inet.h>
#include <errno.h>
@@ -1015,6 +1016,14 @@
return rc;
}
+static void Posix_posix_fallocate(JNIEnv* env, jobject, jobject javaFd, jlong offset, jlong length) {
+ int fd = jniGetFDFromFileDescriptor(env, javaFd);
+ errno = TEMP_FAILURE_RETRY(posix_fallocate64(fd, offset, length));
+ if (errno != 0) {
+ throwErrnoException(env, "posix_fallocate");
+ }
+}
+
static jint Posix_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) {
ScopedBytesRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
@@ -1042,6 +1051,20 @@
return throwIfMinusOne(env, "read", TEMP_FAILURE_RETRY(read(fd, bytes.get() + byteOffset, byteCount)));
}
+static jstring Posix_readlink(JNIEnv* env, jobject, jstring javaPath) {
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return NULL;
+ }
+
+ std::string result;
+ if (!readlink(path.c_str(), result)) {
+ throwErrnoException(env, "readlink");
+ return NULL;
+ }
+ return env->NewStringUTF(result.c_str());
+}
+
static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
IoVec<ScopedBytesRW> ioVec(env, env->GetArrayLength(buffers));
if (!ioVec.init(buffers, offsets, byteCounts)) {
@@ -1427,9 +1450,11 @@
NATIVE_METHOD(Posix, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, pipe, "()[Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, poll, "([Llibcore/io/StructPollfd;I)I"),
+ NATIVE_METHOD(Posix, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"),
NATIVE_METHOD(Posix, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
+ NATIVE_METHOD(Posix, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(Posix, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
NATIVE_METHOD(Posix, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"),
NATIVE_METHOD(Posix, remove, "(Ljava/lang/String;)V"),
diff --git a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
index 6ba055a..af34fb8 100644
--- a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
+++ b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
@@ -1291,7 +1291,7 @@
static void ExpatParser_staticInitialize(JNIEnv* env, jobject classObject, jstring empty) {
jclass clazz = reinterpret_cast<jclass>(classObject);
startElementMethod = env->GetMethodID(clazz, "startElement",
- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V");
+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JI)V");
if (startElementMethod == NULL) return;
endElementMethod = env->GetMethodID(clazz, "endElement",
diff --git a/luni/src/main/native/sub.mk b/luni/src/main/native/sub.mk
index 4e10cc7..e8b6e4a 100644
--- a/luni/src/main/native/sub.mk
+++ b/luni/src/main/native/sub.mk
@@ -4,69 +4,69 @@
# or BUILD_*_LIBRARY.
LOCAL_SRC_FILES := \
- AsynchronousSocketCloseMonitor.cpp \
- ExecStrings.cpp \
- IcuUtilities.cpp \
- JniException.cpp \
- NetworkUtilities.cpp \
- Register.cpp \
- ZipUtilities.cpp \
- cbigint.cpp \
- java_io_Console.cpp \
- java_io_File.cpp \
- java_io_ObjectStreamClass.cpp \
- java_lang_Character.cpp \
- java_lang_Double.cpp \
- java_lang_Float.cpp \
- java_lang_Math.cpp \
- java_lang_ProcessManager.cpp \
- java_lang_RealToString.cpp \
- java_lang_StrictMath.cpp \
- java_lang_StringToReal.cpp \
- java_lang_System.cpp \
- java_math_NativeBN.cpp \
- java_nio_ByteOrder.cpp \
- java_nio_charset_Charsets.cpp \
- java_text_Bidi.cpp \
- java_util_jar_StrictJarFile.cpp \
- java_util_regex_Matcher.cpp \
- java_util_regex_Pattern.cpp \
- java_util_zip_Adler32.cpp \
- java_util_zip_CRC32.cpp \
- java_util_zip_Deflater.cpp \
- java_util_zip_Inflater.cpp \
- libcore_icu_AlphabeticIndex.cpp \
- libcore_icu_DateIntervalFormat.cpp \
- libcore_icu_ICU.cpp \
- libcore_icu_NativeBreakIterator.cpp \
- libcore_icu_NativeCollation.cpp \
- libcore_icu_NativeConverter.cpp \
- libcore_icu_NativeDecimalFormat.cpp \
- libcore_icu_NativeIDN.cpp \
- libcore_icu_NativeNormalizer.cpp \
- libcore_icu_NativePluralRules.cpp \
- libcore_icu_TimeZoneNames.cpp \
- libcore_icu_Transliterator.cpp \
- libcore_io_AsynchronousCloseMonitor.cpp \
- libcore_io_Memory.cpp \
- libcore_io_OsConstants.cpp \
- libcore_io_Posix.cpp \
- org_apache_harmony_xml_ExpatParser.cpp \
- readlink.cpp \
- realpath.cpp \
- sun_misc_Unsafe.cpp \
- valueOf.cpp
+ AsynchronousSocketCloseMonitor.cpp \
+ ExecStrings.cpp \
+ IcuUtilities.cpp \
+ JniException.cpp \
+ NetworkUtilities.cpp \
+ Register.cpp \
+ ZipUtilities.cpp \
+ canonicalize_path.cpp \
+ cbigint.cpp \
+ java_io_Console.cpp \
+ java_io_File.cpp \
+ java_io_ObjectStreamClass.cpp \
+ java_lang_Character.cpp \
+ java_lang_Double.cpp \
+ java_lang_Float.cpp \
+ java_lang_Math.cpp \
+ java_lang_ProcessManager.cpp \
+ java_lang_RealToString.cpp \
+ java_lang_StrictMath.cpp \
+ java_lang_StringToReal.cpp \
+ java_lang_System.cpp \
+ java_math_NativeBN.cpp \
+ java_nio_ByteOrder.cpp \
+ java_nio_charset_Charsets.cpp \
+ java_text_Bidi.cpp \
+ java_util_jar_StrictJarFile.cpp \
+ java_util_regex_Matcher.cpp \
+ java_util_regex_Pattern.cpp \
+ java_util_zip_Adler32.cpp \
+ java_util_zip_CRC32.cpp \
+ java_util_zip_Deflater.cpp \
+ java_util_zip_Inflater.cpp \
+ libcore_icu_AlphabeticIndex.cpp \
+ libcore_icu_DateIntervalFormat.cpp \
+ libcore_icu_ICU.cpp \
+ libcore_icu_NativeBreakIterator.cpp \
+ libcore_icu_NativeCollation.cpp \
+ libcore_icu_NativeConverter.cpp \
+ libcore_icu_NativeDecimalFormat.cpp \
+ libcore_icu_NativeIDN.cpp \
+ libcore_icu_NativeNormalizer.cpp \
+ libcore_icu_NativePluralRules.cpp \
+ libcore_icu_TimeZoneNames.cpp \
+ libcore_icu_Transliterator.cpp \
+ libcore_io_AsynchronousCloseMonitor.cpp \
+ libcore_io_Memory.cpp \
+ libcore_io_OsConstants.cpp \
+ libcore_io_Posix.cpp \
+ org_apache_harmony_xml_ExpatParser.cpp \
+ readlink.cpp \
+ sun_misc_Unsafe.cpp \
+ valueOf.cpp \
LOCAL_C_INCLUDES += \
- external/icu4c/common \
- external/icu4c/i18n \
- external/openssl/include \
- external/zlib \
- system/core/include
+ external/icu4c/common \
+ external/icu4c/i18n \
+ external/openssl/include \
+ external/zlib \
+ system/core/include \
LOCAL_STATIC_LIBRARIES += \
- libfdlibm
+ libfdlibm \
LOCAL_SHARED_LIBRARIES += \
- liblog \
- libnativehelper
+ liblog \
+ libnativehelper \
diff --git a/luni/src/test/java/libcore/io/MemoryTest.java b/luni/src/test/java/libcore/io/MemoryTest.java
index 9a596fb..c817b20 100644
--- a/luni/src/test/java/libcore/io/MemoryTest.java
+++ b/luni/src/test/java/libcore/io/MemoryTest.java
@@ -32,10 +32,10 @@
int scale = SizeOf.INT;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -57,7 +57,7 @@
}
}
- private void assertIntsEqual(int[] expectedValues, int ptr, boolean swap) {
+ private void assertIntsEqual(int[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekInt(ptr + SizeOf.INT * i, swap));
}
@@ -73,10 +73,10 @@
int scale = SizeOf.LONG;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -98,7 +98,7 @@
}
}
- private void assertLongsEqual(long[] expectedValues, int ptr, boolean swap) {
+ private void assertLongsEqual(long[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekLong(ptr + SizeOf.LONG * i, swap));
}
@@ -111,10 +111,10 @@
int scale = SizeOf.SHORT;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -136,7 +136,7 @@
}
}
- private void assertShortsEqual(short[] expectedValues, int ptr, boolean swap) {
+ private void assertShortsEqual(short[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekShort(ptr + SizeOf.SHORT * i, swap));
}
diff --git a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
index fbd4aef4..dfd050d 100644
--- a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
+++ b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
@@ -36,6 +36,7 @@
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Arrays;
+import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
@@ -316,6 +317,22 @@
assertEquals(result1, result2);
}
+ /*
+ * This is needed because the certificate revocation in our CRL can be a
+ * couple seconds ahead of the lastUpdate time in the CRL.
+ */
+ private static void assertDateSlightlyBefore(Date expected, Date actual) throws Exception {
+ Calendar c = Calendar.getInstance();
+
+ // Make sure it's within 2 seconds of expected.
+ c.setTime(expected);
+ c.add(Calendar.SECOND, -2);
+ assertTrue(actual.after(c.getTime()));
+
+ // Before or equal...
+ assertTrue(actual.before(expected) || actual.equals(expected));
+ }
+
private void assertRsaCrlEntry(CertificateFactory f, X509CRLEntry rsaEntry) throws Exception {
assertNotNull(rsaEntry);
@@ -324,7 +341,7 @@
Date expectedDate = dates.get("lastUpdate");
assertEquals(rsaCert.getSerialNumber(), rsaEntry.getSerialNumber());
- assertDateEquals(expectedDate, rsaEntry.getRevocationDate());
+ assertDateSlightlyBefore(expectedDate, rsaEntry.getRevocationDate());
assertNull(rsaEntry.getCertificateIssuer());
assertFalse(rsaEntry.hasExtensions());
assertNull(rsaEntry.getCriticalExtensionOIDs());
@@ -334,12 +351,14 @@
}
private void assertDsaCrlEntry(CertificateFactory f, X509CRLEntry dsaEntry) throws Exception {
+ assertNotNull(dsaEntry);
+
X509Certificate dsaCert = getCertificate(f, CERT_DSA);
Map<String, Date> dates = getCrlDates(CRL_RSA_DSA_DATES);
Date expectedDate = dates.get("lastUpdate");
assertEquals(dsaCert.getSerialNumber(), dsaEntry.getSerialNumber());
- assertDateEquals(expectedDate, dsaEntry.getRevocationDate());
+ assertDateSlightlyBefore(expectedDate, dsaEntry.getRevocationDate());
assertNull(dsaEntry.getCertificateIssuer());
assertTrue(dsaEntry.hasExtensions());
/* TODO: get the OID */
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherTest.java b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
index d32a838..b9241c0 100644
--- a/luni/src/test/java/libcore/javax/crypto/CipherTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
@@ -97,12 +97,16 @@
return false;
}
}
- // stream modes CFB, CTR, CTS, OFB with PKCS5Padding don't really make sense
+ // stream modes CFB, CTR, CTS, OFB with PKCS5Padding or PKCS7Padding don't really make sense
if (!provider.equals("AndroidOpenSSL") &&
(algorithm.equals("AES/CFB/PKCS5PADDING")
+ || algorithm.equals("AES/CFB/PKCS7PADDING")
|| algorithm.equals("AES/CTR/PKCS5PADDING")
+ || algorithm.equals("AES/CTR/PKCS7PADDING")
|| algorithm.equals("AES/CTS/PKCS5PADDING")
- || algorithm.equals("AES/OFB/PKCS5PADDING"))) {
+ || algorithm.equals("AES/CTS/PKCS7PADDING")
+ || algorithm.equals("AES/OFB/PKCS5PADDING")
+ || algorithm.equals("AES/OFB/PKCS7PADDING"))) {
return false;
}
return true;
@@ -276,16 +280,22 @@
static {
setExpectedBlockSize("AES", 16);
setExpectedBlockSize("AES/CBC/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CBC/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CBC/NOPADDING", 16);
setExpectedBlockSize("AES/CFB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CFB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CFB/NOPADDING", 16);
setExpectedBlockSize("AES/CTR/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CTR/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CTR/NOPADDING", 16);
setExpectedBlockSize("AES/CTS/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CTS/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CTS/NOPADDING", 16);
setExpectedBlockSize("AES/ECB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/ECB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/ECB/NOPADDING", 16);
setExpectedBlockSize("AES/OFB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/OFB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/OFB/NOPADDING", 16);
setExpectedBlockSize("GCM", 16);
setExpectedBlockSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16);
@@ -317,16 +327,22 @@
setExpectedBlockSize("DESEDE", 8);
setExpectedBlockSize("DESEDE/CBC/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CBC/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/CBC/NOPADDING", 8);
setExpectedBlockSize("DESEDE/CFB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CFB/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/CFB/NOPADDING", 8);
setExpectedBlockSize("DESEDE/CTR/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTR/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/CTR/NOPADDING", 8);
setExpectedBlockSize("DESEDE/CTS/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTS/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/CTS/NOPADDING", 8);
setExpectedBlockSize("DESEDE/ECB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/ECB/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/ECB/NOPADDING", 8);
setExpectedBlockSize("DESEDE/OFB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/OFB/PKCS7PADDING", 8);
setExpectedBlockSize("DESEDE/OFB/NOPADDING", 8);
setExpectedBlockSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", 8);
setExpectedBlockSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", 8);
@@ -427,11 +443,17 @@
setExpectedOutputSize("AES", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("GCM", Cipher.ENCRYPT_MODE, GCM_TAG_SIZE_BITS / 8);
setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16);
setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", 16);
@@ -444,17 +466,27 @@
setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", 16);
// AndroidOpenSSL returns zero for the non-block ciphers
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("GCM", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0);
@@ -467,9 +499,13 @@
setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", Cipher.DECRYPT_MODE, 0);
// AndroidOpenSSL returns the block size for the block ciphers
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
if (StandardNames.IS_RI) {
setExpectedOutputSize("AESWRAP", Cipher.WRAP_MODE, 8);
@@ -503,11 +539,17 @@
setExpectedOutputSize("DESEDE", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.ENCRYPT_MODE, 8);
@@ -515,11 +557,17 @@
setExpectedOutputSize("DESEDE", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.DECRYPT_MODE, 0);
@@ -708,6 +756,7 @@
}
if (algorithm.equals("AES/CBC/NOPADDING")
|| algorithm.equals("AES/CBC/PKCS5PADDING")
+ || algorithm.equals("AES/CBC/PKCS7PADDING")
|| algorithm.equals("AES/CFB/NOPADDING")
|| algorithm.equals("AES/CTR/NOPADDING")
|| algorithm.equals("AES/CTS/NOPADDING")
@@ -718,6 +767,7 @@
}
if (algorithm.equals("DESEDE/CBC/NOPADDING")
|| algorithm.equals("DESEDE/CBC/PKCS5PADDING")
+ || algorithm.equals("DESEDE/CBC/PKCS7PADDING")
|| algorithm.equals("DESEDE/CFB/NOPADDING")
|| algorithm.equals("DESEDE/CTR/NOPADDING")
|| algorithm.equals("DESEDE/CTS/NOPADDING")
@@ -986,7 +1036,8 @@
getExpectedBlockSize(algorithm, encryptMode, providerName), c.getBlockSize());
assertEquals(cipherID + " getOutputSize(0) encryptMode",
getExpectedOutputSize(algorithm, encryptMode, providerName), c.getOutputSize(0));
- if (algorithm.endsWith("/PKCS5PADDING") && isStreamMode(algorithm)) {
+ if ((algorithm.endsWith("/PKCS5PADDING") || algorithm.endsWith("/PKCS7PADDING"))
+ && isStreamMode(algorithm)) {
assertEquals(getExpectedOutputSize(algorithm, encryptMode, providerName),
c.doFinal(new byte[1]).length);
}
@@ -2334,7 +2385,7 @@
};
private static class CipherTestParam {
- public final String mode;
+ public final String transformation;
public final byte[] key;
@@ -2346,9 +2397,9 @@
public final byte[] plaintextPadded;
- public CipherTestParam(String mode, byte[] key, byte[] iv, byte[] plaintext,
+ public CipherTestParam(String transformation, byte[] key, byte[] iv, byte[] plaintext,
byte[] plaintextPadded, byte[] ciphertext) {
- this.mode = mode;
+ this.transformation = transformation;
this.key = key;
this.iv = iv;
this.plaintext = plaintext;
@@ -2359,13 +2410,24 @@
private static List<CipherTestParam> CIPHER_TEST_PARAMS = new ArrayList<CipherTestParam>();
static {
- CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB", AES_128_KEY,
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS5Padding", AES_128_KEY,
+ null,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted));
+ // PKCS#5 is assumed to be equivalent to PKCS#7 -- same test vectors are thus used for both.
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS7Padding", AES_128_KEY,
null,
AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext,
AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded,
AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted));
if (IS_UNLIMITED) {
- CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC", AES_256_KEY,
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS5Padding", AES_256_KEY,
+ AES_256_CBC_PKCS5Padding_TestVector_1_IV,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Ciphertext));
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS7Padding", AES_256_KEY,
AES_256_CBC_PKCS5Padding_TestVector_1_IV,
AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext,
AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded,
@@ -2386,7 +2448,7 @@
try {
checkCipher(p, provider);
} catch (Exception e) {
- out.append("Error encountered checking " + p.mode + ", keySize="
+ out.append("Error encountered checking " + p.transformation + ", keySize="
+ (p.key.length * 8)
+ " with provider " + provider + "\n");
@@ -2401,7 +2463,7 @@
private void checkCipher(CipherTestParam p, String provider) throws Exception {
SecretKey key = new SecretKeySpec(p.key, "AES");
- Cipher c = Cipher.getInstance(p.mode + "/PKCS5Padding", provider);
+ Cipher c = Cipher.getInstance(p.transformation, provider);
AlgorithmParameterSpec spec = null;
if (p.iv != null) {
spec = new IvParameterSpec(p.iv);
@@ -2486,7 +2548,8 @@
Arrays.toString(Arrays.copyOfRange(actualPlaintext, 1, p.plaintext.length + 1)));
}
- Cipher cNoPad = Cipher.getInstance(p.mode + "/NoPadding", provider);
+ Cipher cNoPad = Cipher.getInstance(
+ getCipherTransformationWithNoPadding(p.transformation), provider);
cNoPad.init(Cipher.DECRYPT_MODE, key, spec);
final byte[] actualPlaintextPadded = cNoPad.doFinal(p.ciphertext);
@@ -2516,6 +2579,23 @@
}
}
+ /**
+ * Gets the Cipher transformation with the same algorithm and mode as the provided one but
+ * which uses no padding.
+ */
+ private static String getCipherTransformationWithNoPadding(String transformation) {
+ // The transformation is assumed to be in the Algorithm/Mode/Padding format.
+ int paddingModeDelimiterIndex = transformation.lastIndexOf('/');
+ if (paddingModeDelimiterIndex == -1) {
+ fail("No padding mode delimiter: " + transformation);
+ }
+ String paddingMode = transformation.substring(paddingModeDelimiterIndex + 1);
+ if (!paddingMode.toLowerCase().endsWith("padding")) {
+ fail("No padding mode specified:" + transformation);
+ }
+ return transformation.substring(0, paddingModeDelimiterIndex) + "/NoPadding";
+ }
+
public void testCipher_updateAAD_BeforeInit_Failure() throws Exception {
Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
@@ -2605,7 +2685,7 @@
try {
checkCipher_ShortBlock_Failure(p, provider);
} catch (Exception e) {
- out.append("Error encountered checking " + p.mode + ", keySize="
+ out.append("Error encountered checking " + p.transformation + ", keySize="
+ (p.key.length * 8)
+ " with provider " + provider + "\n");
e.printStackTrace(out);
@@ -2619,7 +2699,8 @@
private void checkCipher_ShortBlock_Failure(CipherTestParam p, String provider) throws Exception {
SecretKey key = new SecretKeySpec(p.key, "AES");
- Cipher c = Cipher.getInstance(p.mode + "/NoPadding", provider);
+ Cipher c = Cipher.getInstance(
+ getCipherTransformationWithNoPadding(p.transformation), provider);
if (c.getBlockSize() == 0) {
return;
}
diff --git a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
index 7ee5778..571aa9c 100644
--- a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
+++ b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
@@ -57,20 +57,21 @@
*/
public void testGetName() throws Exception {
CertificateFactory certFactBC = CertificateFactory.getInstance("X.509", "BC");
- CertificateFactory certFactDRL = CertificateFactory.getInstance("X.509", "DRLCertFactory");
+ CertificateFactory certFactOpenSSL = CertificateFactory.getInstance("X.509",
+ "AndroidOpenSSL");
X509Certificate certBC = (X509Certificate)
certFactBC.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
- X509Certificate certDRL = (X509Certificate)
- certFactDRL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
+ X509Certificate certOpenSSL = (X509Certificate)
+ certFactOpenSSL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
- assertEquals(certBC, certDRL);
+ assertEquals(certBC, certOpenSSL);
assertEquals(certBC.getSubjectX500Principal(), certBC.getSubjectX500Principal());
- assertEquals(certDRL.getIssuerX500Principal(), certDRL.getIssuerX500Principal());
+ assertEquals(certOpenSSL.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal());
- assertEquals(certBC.getSubjectX500Principal(), certDRL.getSubjectX500Principal());
- assertEquals(certBC.getIssuerX500Principal(), certDRL.getIssuerX500Principal());
+ assertEquals(certBC.getSubjectX500Principal(), certOpenSSL.getSubjectX500Principal());
+ assertEquals(certBC.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal());
String[] formats = {
X500Principal.CANONICAL,
@@ -79,9 +80,9 @@
};
for (String format : formats) {
assertEquals(certBC.getSubjectX500Principal().getName(format),
- certDRL.getSubjectX500Principal().getName(format));
+ certOpenSSL.getSubjectX500Principal().getName(format));
assertEquals(certBC.getIssuerX500Principal().getName(format),
- certDRL.getIssuerX500Principal().getName(format));
+ certOpenSSL.getIssuerX500Principal().getName(format));
}
String expected = ""
+ "cn=entrust.net certification authority (2048),"
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
index 0b8f017..85c2438 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
@@ -18,7 +18,7 @@
import junit.framework.TestCase;
public class CipherAesTest extends TestCase {
-// 216 cases checked
+// 324 cases checked
public void test_AesNoISO() {
CipherSymmetricKeyThread aesNoISO = new CipherSymmetricKeyThread("AES",
new int[] {128, 192, 256}, // Keysize must be 128, 192, 256.
@@ -29,7 +29,8 @@
"CFB128", "OFB", "OFB8", "OFB16", "OFB24", "OFB32",
"OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80",
"OFB88", "OFB96", "OFB104", "OFB112", "OFB120",
- "OFB128"}, new String[] {"NoPadding", "PKCS5Padding"});
+ "OFB128"},
+ new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"});
aesNoISO.launcher();
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
index d8565f1..c7b4f20 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
@@ -18,7 +18,7 @@
import junit.framework.TestCase;
public class CipherDESedeTest extends TestCase {
-// 80 cases checked
+// 120 cases checked
public void test_DESedeNoISO() {
CipherSymmetricKeyThread DESedeNoISO = new CipherSymmetricKeyThread(
"DESede", new int[] {112, 168},// Keysize must be 112 or 168.
@@ -26,7 +26,8 @@
"ECB", "CBC", "CFB", "CFB8", "CFB16", "CFB24", "CFB32",
"CFB40", "CFB48", "CFB56", "CFB64", "OFB", "OFB8",
"OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56",
- "OFB64"}, new String[] {"NoPadding", "PKCS5Padding"});
+ "OFB64"},
+ new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"});
DESedeNoISO.launcher();
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
index c9eb26e..ff4babc 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
@@ -52,7 +52,8 @@
@Override
protected void engineSetPadding(String padding)
throws NoSuchPaddingException {
- if (!"PKCS5Padding".equals(padding)) {
+ if ((!"PKCS5Padding".equals(padding))
+ && (!"PKCS7Padding".equals(padding))) {
throw new NoSuchPaddingException(padding);
}
}
diff --git a/support/src/test/java/libcore/java/security/StandardNames.java b/support/src/test/java/libcore/java/security/StandardNames.java
index b33aefe..1d7a71f 100644
--- a/support/src/test/java/libcore/java/security/StandardNames.java
+++ b/support/src/test/java/libcore/java/security/StandardNames.java
@@ -441,22 +441,34 @@
// Needed by our OpenSSL provider
provide("Cipher", "AES/CBC/NOPADDING");
provide("Cipher", "AES/CBC/PKCS5PADDING");
+ provide("Cipher", "AES/CBC/PKCS7PADDING");
provide("Cipher", "AES/CFB/NOPADDING");
provide("Cipher", "AES/CFB/PKCS5PADDING");
+ provide("Cipher", "AES/CFB/PKCS7PADDING");
provide("Cipher", "AES/CTR/NOPADDING");
provide("Cipher", "AES/CTR/PKCS5PADDING");
+ provide("Cipher", "AES/CTR/PKCS7PADDING");
provide("Cipher", "AES/ECB/NOPADDING");
provide("Cipher", "AES/ECB/PKCS5PADDING");
+ provide("Cipher", "AES/ECB/PKCS7PADDING");
provide("Cipher", "AES/OFB/NOPADDING");
provide("Cipher", "AES/OFB/PKCS5PADDING");
+ provide("Cipher", "AES/OFB/PKCS7PADDING");
provide("Cipher", "DESEDE/CBC/NOPADDING");
provide("Cipher", "DESEDE/CBC/PKCS5PADDING");
+ provide("Cipher", "DESEDE/CBC/PKCS7PADDING");
provide("Cipher", "DESEDE/CFB/NOPADDING");
provide("Cipher", "DESEDE/CFB/PKCS5PADDING");
+ provide("Cipher", "DESEDE/CFB/PKCS7PADDING");
provide("Cipher", "DESEDE/ECB/NOPADDING");
provide("Cipher", "DESEDE/ECB/PKCS5PADDING");
+ provide("Cipher", "DESEDE/ECB/PKCS7PADDING");
provide("Cipher", "DESEDE/OFB/NOPADDING");
provide("Cipher", "DESEDE/OFB/PKCS5PADDING");
+ provide("Cipher", "DESEDE/OFB/PKCS7PADDING");
+
+ // Provided by our OpenSSL provider
+ provideCipherPaddings("AES", new String[] { "PKCS7Padding" });
// removed LDAP
unprovide("CertStore", "LDAP");