summaryrefslogtreecommitdiff
path: root/libjava/classpath/gnu/java/security/util
diff options
context:
space:
mode:
authorupstream source tree <ports@midipix.org>2015-03-15 20:14:05 -0400
committerupstream source tree <ports@midipix.org>2015-03-15 20:14:05 -0400
commit554fd8c5195424bdbcabf5de30fdc183aba391bd (patch)
tree976dc5ab7fddf506dadce60ae936f43f58787092 /libjava/classpath/gnu/java/security/util
downloadcbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.bz2
cbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.xz
obtained gcc-4.6.4.tar.bz2 from upstream website;upstream
verified gcc-4.6.4.tar.bz2.sig; imported gcc-4.6.4 source tree from verified upstream tarball. downloading a git-generated archive based on the 'upstream' tag should provide you with a source tree that is binary identical to the one extracted from the above tarball. if you have obtained the source via the command 'git clone', however, do note that line-endings of files in your working directory might differ from line-endings of the respective files in the upstream repository.
Diffstat (limited to 'libjava/classpath/gnu/java/security/util')
-rw-r--r--libjava/classpath/gnu/java/security/util/ByteArray.java111
-rw-r--r--libjava/classpath/gnu/java/security/util/ByteBufferOutputStream.java118
-rw-r--r--libjava/classpath/gnu/java/security/util/DerUtil.java64
-rw-r--r--libjava/classpath/gnu/java/security/util/ExpirableObject.java150
-rw-r--r--libjava/classpath/gnu/java/security/util/FormatUtil.java140
-rw-r--r--libjava/classpath/gnu/java/security/util/IntegerUtil.java109
-rw-r--r--libjava/classpath/gnu/java/security/util/PRNG.java141
-rw-r--r--libjava/classpath/gnu/java/security/util/Prime.java164
-rw-r--r--libjava/classpath/gnu/java/security/util/Sequence.java133
-rw-r--r--libjava/classpath/gnu/java/security/util/SimpleList.java155
-rw-r--r--libjava/classpath/gnu/java/security/util/Util.java629
-rw-r--r--libjava/classpath/gnu/java/security/util/package.html46
12 files changed, 1960 insertions, 0 deletions
diff --git a/libjava/classpath/gnu/java/security/util/ByteArray.java b/libjava/classpath/gnu/java/security/util/ByteArray.java
new file mode 100644
index 000000000..a9b9e5d00
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/ByteArray.java
@@ -0,0 +1,111 @@
+/* ByteArray.java -- wrapper around a byte array, with nice toString output.
+ Copyright (C) 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import gnu.java.lang.CPStringBuilder;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+public final class ByteArray
+{
+ private final byte[] value;
+
+ public ByteArray (final byte[] value)
+ {
+ this.value = value;
+ }
+
+ public byte[] getValue ()
+ {
+ return value;
+ }
+
+ public String toString ()
+ {
+ StringWriter str = new StringWriter ();
+ PrintWriter out = new PrintWriter (str);
+ int i = 0;
+ int len = value.length;
+ while (i < len)
+ {
+ out.print (formatInt (i, 16, 8));
+ out.print (" ");
+ int l = Math.min (16, len - i);
+ String s = toHexString (value, i, l, ' ');
+ out.print (s);
+ for (int j = 56 - (56 - s.length ()); j < 56; j++)
+ out.print (" ");
+ for (int j = 0; j < l; j++)
+ {
+ byte b = value[i+j];
+ if ((b & 0xFF) < 0x20 || (b & 0xFF) > 0x7E)
+ out.print (".");
+ else
+ out.print ((char) (b & 0xFF));
+ }
+ out.println ();
+ i += 16;
+ }
+ return str.toString ();
+ }
+
+ public static String toHexString (byte[] buf, int off, int len, char sep)
+ {
+ CPStringBuilder str = new CPStringBuilder();
+ for (int i = 0; i < len; i++)
+ {
+ str.append (Character.forDigit (buf[i+off] >>> 4 & 0x0F, 16));
+ str.append (Character.forDigit (buf[i+off] & 0x0F, 16));
+ if (i < len - 1)
+ str.append(sep);
+ }
+ return str.toString();
+ }
+
+ public static String formatInt (int value, int radix, int len)
+ {
+ String s = Integer.toString (value, radix);
+ CPStringBuilder buf = new CPStringBuilder ();
+ for (int j = 0; j < len - s.length(); j++)
+ buf.append ("0");
+ buf.append (s);
+ return buf.toString();
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/ByteBufferOutputStream.java b/libjava/classpath/gnu/java/security/util/ByteBufferOutputStream.java
new file mode 100644
index 000000000..642ccdf68
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/ByteBufferOutputStream.java
@@ -0,0 +1,118 @@
+/* ByteBufferOutputStream.java -- output stream with a growable underlying
+ byte buffer.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import java.nio.ByteBuffer;
+
+/**
+ * An output stream that writes bytes to a ByteBuffer, which will be resized
+ * if more space is needed.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class ByteBufferOutputStream extends OutputStream
+{
+ private ByteBuffer buffer;
+
+ public ByteBufferOutputStream()
+ {
+ this(256);
+ }
+
+ public ByteBufferOutputStream(int initialCapacity)
+ {
+ buffer = ByteBuffer.allocate(initialCapacity);
+ }
+
+ /* (non-Javadoc)
+ * @see java.io.OutputStream#write(int)
+ */
+ public @Override synchronized void write(int b) throws IOException
+ {
+ if (!buffer.hasRemaining())
+ growBuffer();
+ buffer.put((byte) b);
+ }
+
+ public @Override synchronized void write(byte[] b, int offset, int length)
+ {
+ if (buffer.remaining() < length)
+ growBuffer();
+ buffer.put(b, offset, length);
+ }
+
+ public @Override void write(byte[] b)
+ {
+ write(b, 0, b.length);
+ }
+
+ /**
+ * Get the current state of the buffer. The returned buffer will have
+ * its position set to zero, its capacity set to the current limit,
+ * and its limit set to its capacity.
+ *
+ * @return The buffer.
+ */
+ public ByteBuffer buffer()
+ {
+ return ((ByteBuffer) buffer.duplicate().flip()).slice();
+ }
+
+ public String toString()
+ {
+ return super.toString() + " [ buffer: " + buffer + " ]";
+ }
+
+ private void growBuffer()
+ {
+ int newCapacity = buffer.capacity();
+ if (newCapacity < 16384) // If the buffer isn't huge yet, double its size
+ newCapacity = newCapacity << 1;
+ else // Otherwize, increment by a bit.
+ newCapacity += 4096;
+ ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
+ buffer.flip();
+ newBuffer.put(buffer);
+ buffer = newBuffer;
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/DerUtil.java b/libjava/classpath/gnu/java/security/util/DerUtil.java
new file mode 100644
index 000000000..26232ba98
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/DerUtil.java
@@ -0,0 +1,64 @@
+/* DerUtil.java -- Utility methods for DER read/write operations
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import gnu.java.security.der.DEREncodingException;
+import gnu.java.security.der.DERValue;
+
+import java.math.BigInteger;
+
+/**
+ * Utility methods for DER encoding handling.
+ */
+public abstract class DerUtil
+{
+ public static final void checkIsConstructed(DERValue v, String msg)
+ throws DEREncodingException
+ {
+ if (! v.isConstructed())
+ throw new DEREncodingException(msg);
+ }
+
+ public static final void checkIsBigInteger(DERValue v, String msg)
+ throws DEREncodingException
+ {
+ if (! (v.getValue() instanceof BigInteger))
+ throw new DEREncodingException(msg);
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/ExpirableObject.java b/libjava/classpath/gnu/java/security/util/ExpirableObject.java
new file mode 100644
index 000000000..e24af249a
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/ExpirableObject.java
@@ -0,0 +1,150 @@
+/* ExpirableObject.java -- an object that is automatically destroyed.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import javax.security.auth.DestroyFailedException;
+import javax.security.auth.Destroyable;
+
+/**
+ * The base class for objects with sensitive data that are automatically
+ * destroyed after a timeout elapses. On creation, an object that extends this
+ * class will automatically be added to a {@link Timer} object that, once a
+ * timeout elapses, will automatically call the {@link Destroyable#destroy()}
+ * method.
+ * <p>
+ * Concrete subclasses must implement the {@link #doDestroy()} method instead of
+ * {@link Destroyable#destroy()}; the behavior of that method should match
+ * exactly the behavior desired of <code>destroy()</code>.
+ * <p>
+ * Note that if a {@link DestroyFailedException} occurs when the timeout
+ * expires, it will not be reported.
+ *
+ * @see Destroyable
+ */
+public abstract class ExpirableObject
+ implements Destroyable
+{
+ /**
+ * The default timeout, used in the default constructor.
+ */
+ public static final long DEFAULT_TIMEOUT = 3600000L;
+
+ /**
+ * The timer that expires instances.
+ */
+ private static final Timer EXPIRER = new Timer(true);
+
+ /**
+ * A reference to the task that will destroy this object when the timeout
+ * expires.
+ */
+ private final Destroyer destroyer;
+
+ /**
+ * Create a new expirable object that will expire after one hour.
+ */
+ protected ExpirableObject()
+ {
+ this(DEFAULT_TIMEOUT);
+ }
+
+ /**
+ * Create a new expirable object that will expire after the specified timeout.
+ *
+ * @param delay The delay before expiration.
+ * @throws IllegalArgumentException If <i>delay</i> is negative, or if
+ * <code>delay + System.currentTimeMillis()</code> is negative.
+ */
+ protected ExpirableObject(final long delay)
+ {
+ destroyer = new Destroyer(this);
+ EXPIRER.schedule(destroyer, delay);
+ }
+
+ /**
+ * Destroys this object. This method calls {@link #doDestroy}, then, if no
+ * exception is thrown, cancels the task that would destroy this object when
+ * the timeout is reached.
+ *
+ * @throws DestroyFailedException If this operation fails.
+ */
+ public final void destroy() throws DestroyFailedException
+ {
+ doDestroy();
+ destroyer.cancel();
+ }
+
+ /**
+ * Subclasses must implement this method instead of the {@link
+ * Destroyable#destroy()} method.
+ *
+ * @throws DestroyFailedException If this operation fails.
+ */
+ protected abstract void doDestroy() throws DestroyFailedException;
+
+ /**
+ * The task that destroys the target when the timeout elapses.
+ */
+ private final class Destroyer
+ extends TimerTask
+ {
+ private final ExpirableObject target;
+
+ Destroyer(final ExpirableObject target)
+ {
+ super();
+ this.target = target;
+ }
+
+ public void run()
+ {
+ try
+ {
+ if (! target.isDestroyed())
+ target.doDestroy();
+ }
+ catch (DestroyFailedException dfe)
+ {
+ }
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/FormatUtil.java b/libjava/classpath/gnu/java/security/util/FormatUtil.java
new file mode 100644
index 000000000..35da322b8
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/FormatUtil.java
@@ -0,0 +1,140 @@
+/* FormatUtil.java -- Encoding and decoding format utility methods
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import gnu.java.security.Registry;
+
+/**
+ * Encoding and decoding format utility methods.
+ */
+public class FormatUtil
+{
+ /** Trivial constructor to enforce Singleton pattern. */
+ private FormatUtil()
+ {
+ super();
+ }
+
+ /**
+ * Returns the fully qualified name of the designated encoding ID.
+ *
+ * @param formatID the unique identifier of the encoding format.
+ * @return the fully qualified name of the designated format. Returns
+ * <code>null</code> if no such encoding format is known.
+ */
+ public static final String getEncodingName(int formatID)
+ {
+ String result = null;
+ switch (formatID)
+ {
+ case Registry.RAW_ENCODING_ID:
+ result = Registry.RAW_ENCODING;
+ break;
+ case Registry.X509_ENCODING_ID:
+ result = Registry.X509_ENCODING;
+ break;
+ case Registry.PKCS8_ENCODING_ID:
+ result = Registry.PKCS8_ENCODING;
+ break;
+ case Registry.ASN1_ENCODING_ID:
+ result = Registry.ASN1_ENCODING;
+ break;
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the short name of the designated encoding ID. This is used by the
+ * JCE Adapters.
+ *
+ * @param formatID the unique identifier of the encoding format.
+ * @return the short name of the designated format. Returns <code>null</code>
+ * if no such encoding format is known.
+ */
+ public static final String getEncodingShortName(int formatID)
+ {
+ String result = null;
+ switch (formatID)
+ {
+ case Registry.RAW_ENCODING_ID:
+ result = Registry.RAW_ENCODING_SHORT_NAME;
+ break;
+ case Registry.X509_ENCODING_ID:
+ result = Registry.X509_ENCODING_SORT_NAME;
+ break;
+ case Registry.PKCS8_ENCODING_ID:
+ result = Registry.PKCS8_ENCODING_SHORT_NAME;
+ break;
+ case Registry.ASN1_ENCODING_ID:
+ result = Registry.ASN1_ENCODING_SHORT_NAME;
+ break;
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the identifier of the encoding format given its short name.
+ *
+ * @param name the case-insensitive canonical short name of an encoding
+ * format.
+ * @return the identifier of the designated encoding format, or <code>0</code>
+ * if the name does not correspond to any known format.
+ */
+ public static final int getFormatID(String name)
+ {
+ if (name == null)
+ return 0;
+
+ name = name.trim();
+ if (name.length() == 0)
+ return 0;
+
+ int result = 0;
+ if (name.equalsIgnoreCase(Registry.RAW_ENCODING_SHORT_NAME))
+ result = Registry.RAW_ENCODING_ID;
+ else if (name.equalsIgnoreCase(Registry.X509_ENCODING_SORT_NAME))
+ result = Registry.X509_ENCODING_ID;
+ else if (name.equalsIgnoreCase(Registry.PKCS8_ENCODING_SHORT_NAME))
+ result = Registry.PKCS8_ENCODING_ID;
+
+ return result;
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/IntegerUtil.java b/libjava/classpath/gnu/java/security/util/IntegerUtil.java
new file mode 100644
index 000000000..106dc4d66
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/IntegerUtil.java
@@ -0,0 +1,109 @@
+/* IntegerUtil.java -- JDK 5 Integer methods with 1.4 API
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Utility class which offers Integer related methods found in RI's version 5
+ * but written with RI's 1.4 API.
+ */
+public abstract class IntegerUtil
+{
+ /** Maximum size of our cache of constructed Integers. */
+ private static final int CACHE_SIZE = 100;
+ /** LRU (Least Recently Used) cache, of the last accessed 100 Integers. */
+ private static final Map cache = new LinkedHashMap(CACHE_SIZE + 1, 0.75F, true)
+ {
+ public boolean removeEldestEntry(Map.Entry entry)
+ {
+ return size() > CACHE_SIZE;
+ }
+ };
+
+ /** Trivial private constructor to enforce Singleton usage. */
+ private IntegerUtil()
+ {
+ super();
+ }
+
+ /**
+ * Similar to {@link Integer#valueOf(String)} except it caches the result in
+ * a local LRU cache of 100 elements, organized by access order.
+ * <p>
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param aString a string representation of an integer.
+ * @return the {@link Integer} object representing the designated string.
+ */
+ public static final Integer valueOf(String aString)
+ {
+ Integer result;
+ synchronized (cache)
+ {
+ result = (Integer) cache.get(aString);
+ if (result == null)
+ {
+ result = Integer.valueOf(aString);
+ cache.put(aString, result);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Simulates the <code>valueOf(int)</code> method found in {@link Integer} of
+ * the RI's version 1.5 using a local LRU cache of 100 elements, organized by
+ * access order.
+ * <p>
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param anInt a decimal integer.
+ * @return the {@link Integer} object representing the designated primitive.
+ */
+ public static final Integer valueOf(int anInt)
+ {
+ return valueOf(Integer.toString(anInt, 10));
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/PRNG.java b/libjava/classpath/gnu/java/security/util/PRNG.java
new file mode 100644
index 000000000..1bed04dcd
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/PRNG.java
@@ -0,0 +1,141 @@
+/* PRNG.java -- A Utility methods for default source of randomness
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.HashMap;
+
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.prng.MDGenerator;
+
+/**
+ * A useful hash-based (SHA) pseudo-random number generator used throughout this
+ * library.
+ *
+ * @see MDGenerator
+ */
+public class PRNG
+{
+ /** The underlying {@link IRandom}. */
+ private IRandom delegate;
+
+ /**
+ * Private constructor to enforce using the Factory method.
+ *
+ * @param delegate the undelying {@link IRandom} object used.
+ */
+ private PRNG(IRandom delegate)
+ {
+ super();
+
+ this.delegate = delegate;
+ }
+
+ public static final PRNG getInstance()
+ {
+ IRandom delegate = new MDGenerator();
+ try
+ {
+ HashMap map = new HashMap();
+ // initialise it with a seed
+ long t = System.currentTimeMillis();
+ byte[] seed = new byte[] {
+ (byte)(t >>> 56), (byte)(t >>> 48),
+ (byte)(t >>> 40), (byte)(t >>> 32),
+ (byte)(t >>> 24), (byte)(t >>> 16),
+ (byte)(t >>> 8), (byte) t };
+ map.put(MDGenerator.SEEED, seed);
+ delegate.init(map); // default is to use SHA-1 hash
+ }
+ catch (Exception x)
+ {
+ throw new ExceptionInInitializerError(x);
+ }
+ return new PRNG(delegate);
+ }
+
+ /**
+ * Completely fills the designated <code>buffer</code> with random data
+ * generated by the underlying delegate.
+ *
+ * @param buffer the place holder of random bytes generated by the underlying
+ * delegate. On output, the contents of <code>buffer</code> are
+ * replaced with pseudo-random data, iff the <code>buffer</code>
+ * size is not zero.
+ */
+ public void nextBytes(byte[] buffer)
+ {
+ nextBytes(buffer, 0, buffer.length);
+ }
+
+ /**
+ * Fills the designated <code>buffer</code>, starting from byte at position
+ * <code>offset</code> with, at most, <code>length</code> bytes of random
+ * data generated by the underlying delegate.
+ *
+ * @see IRandom#nextBytes
+ */
+ public void nextBytes(byte[] buffer, int offset, int length)
+ {
+ try
+ {
+ delegate.nextBytes(buffer, offset, length);
+ }
+ catch (LimitReachedException x) // re-initialise with a seed
+ {
+ try
+ {
+ HashMap map = new HashMap();
+ long t = System.currentTimeMillis();
+ byte[] seed = new byte[] {
+ (byte)(t >>> 56), (byte)(t >>> 48),
+ (byte)(t >>> 40), (byte)(t >>> 32),
+ (byte)(t >>> 24), (byte)(t >>> 16),
+ (byte)(t >>> 8), (byte) t };
+ map.put(MDGenerator.SEEED, seed);
+ delegate.init(map); // default is to use SHA-1 hash
+ delegate.nextBytes(buffer, offset, length);
+ }
+ catch (Exception y)
+ {
+ throw new ExceptionInInitializerError(y);
+ }
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/Prime.java b/libjava/classpath/gnu/java/security/util/Prime.java
new file mode 100644
index 000000000..82c584ff4
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/Prime.java
@@ -0,0 +1,164 @@
+/* Prime.java --- Prime number generation utilities
+ Copyright (C) 1999, 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+import java.math.BigInteger;
+import java.util.Random;
+//import java.security.SecureRandom;
+
+public final class Prime
+{
+
+ /*
+ See IEEE P1363 A.15.4 (10/05/98 Draft)
+ */
+ public static BigInteger generateRandomPrime( int pmin, int pmax, BigInteger f )
+ {
+ BigInteger d;
+
+ //Step 1 - generate prime
+ BigInteger p = new BigInteger( (pmax + pmin)/2, new Random() );
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmin ) ) <= 0 )
+ {
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin ).subtract( p ) );
+ }
+
+ //Step 2 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( BigInteger.valueOf( 1 ) );
+
+ for(;;)
+ {
+ //Step 3
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmax)) > 0)
+ {
+ //Step 3.1
+ p = p.subtract( BigInteger.valueOf( 1 ).shiftLeft( pmax) );
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin) );
+ p = p.subtract( BigInteger.valueOf( 1 ) );
+
+ //Step 3.2
+ // put step 2 code here so looping code is cleaner
+ //Step 2 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( BigInteger.valueOf( 1 ) );
+ continue;
+ }
+
+ //Step 4 - compute GCD
+ d = p.subtract( BigInteger.valueOf(1) );
+ d = d.gcd( f );
+
+ //Step 5 - test d
+ if( d.compareTo( BigInteger.valueOf( 1 ) ) == 0)
+ {
+ //Step 5.1 - test primality
+ if( p.isProbablePrime( 1 ) == true )
+ {
+ //Step 5.2;
+ return p;
+ }
+ }
+ //Step 6
+ p = p.add( BigInteger.valueOf( 2 ) );
+
+ //Step 7
+ }
+ }
+
+
+ /*
+ See IEEE P1363 A.15.5 (10/05/98 Draft)
+ */
+ public static BigInteger generateRandomPrime( BigInteger r, BigInteger a, int pmin, int pmax, BigInteger f )
+ {
+ BigInteger d, w;
+
+ //Step 1 - generate prime
+ BigInteger p = new BigInteger( (pmax + pmin)/2, new Random() );
+
+ steptwo:{ //Step 2
+ w = p.mod( r.multiply( BigInteger.valueOf(2) ));
+
+ //Step 3
+ p = p.add( r.multiply( BigInteger.valueOf(2) ) );
+ p = p.subtract( w );
+ p = p.add(a);
+
+ //Step 4 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( r );
+
+ for(;;)
+ {
+ //Step 5
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmax)) > 0)
+ {
+ //Step 5.1
+ p = p.subtract( BigInteger.valueOf( 1 ).shiftLeft( pmax) );
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin) );
+ p = p.subtract( BigInteger.valueOf( 1 ) );
+
+ //Step 5.2 - goto to Step 2
+ break steptwo;
+ }
+
+ //Step 6
+ d = p.subtract( BigInteger.valueOf(1) );
+ d = d.gcd( f );
+
+ //Step 7 - test d
+ if( d.compareTo( BigInteger.valueOf( 1 ) ) == 0)
+ {
+ //Step 7.1 - test primality
+ if( p.isProbablePrime( 1 ) == true )
+ {
+ //Step 7.2;
+ return p;
+ }
+ }
+ //Step 8
+ p = p.add( r.multiply( BigInteger.valueOf(2) ) );
+
+ //Step 9
+ }
+ }
+ //Should never reach here but makes the compiler happy
+ return BigInteger.valueOf(0);
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/Sequence.java b/libjava/classpath/gnu/java/security/util/Sequence.java
new file mode 100644
index 000000000..63086d2bd
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/Sequence.java
@@ -0,0 +1,133 @@
+/* Sequence.java -- a sequence of integers.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.AbstractList;
+import java.util.LinkedList;
+
+/**
+ * A monotonic sequence of integers in the finite field 2<sup>32</sup>.
+ */
+public final class Sequence
+ extends AbstractList
+{
+ private final Integer[] sequence;
+
+ /**
+ * Create a sequence of integers from 0 to <i>end</i>, with an increment of
+ * 1. If <i>end</i> is less than 0, then the sequence will wrap around
+ * through all positive integers then negative integers until the end value is
+ * reached. Naturally, this will result in an enormous object, so don't do
+ * this.
+ *
+ * @param end The ending value.
+ */
+ public Sequence(int end)
+ {
+ this(0, end, 1);
+ }
+
+ /**
+ * Create a sequence of integers from <i>start</i> to <i>end</i>, with an
+ * increment of 1. If <i>end</i> is less than <i>start</i>, then the
+ * sequence will wrap around until the end value is reached. Naturally, this
+ * will result in an enormous object, so don't do this.
+ *
+ * @param start The starting value.
+ * @param end The ending value.
+ */
+ public Sequence(int start, int end)
+ {
+ this(start, end, 1);
+ }
+
+ /**
+ * Create a sequence of integers from <i>start</i> to <i>end</i>, with an
+ * increment of <i>span</i>. If <i>end</i> is less than <i>start</i>, then
+ * the sequence will wrap around until the end value is reached. Naturally,
+ * this will result in an enormous object, so don't do this.
+ * <p>
+ * <i>span</i> can be negative, resulting in a decresing sequence.
+ * <p>
+ * If <i>span</i> is 0, then the sequence will contain {<i>start</i>,
+ * <i>end</i>} if <i>start</i> != <i>end</i>, or just the singleton
+ * <i>start</i> if <i>start</i> == <i>end</i>.
+ *
+ * @param start The starting value.
+ * @param end The ending value.
+ * @param span The increment value.
+ */
+ public Sequence(int start, int end, int span)
+ {
+ if (span == 0)
+ {
+ if (start != end)
+ sequence = new Integer[] { Integer.valueOf(start),
+ Integer.valueOf(end) };
+ else
+ sequence = new Integer[] { Integer.valueOf(start) };
+ }
+ else
+ {
+ LinkedList l = new LinkedList();
+ for (int i = start; i != end; i += span)
+ l.add(Integer.valueOf(i));
+
+ l.add(Integer.valueOf(end));
+ sequence = (Integer[]) l.toArray(new Integer[l.size()]);
+ }
+ }
+
+ public Object get(int index)
+ {
+ if (index < 0 || index >= size())
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
+ return sequence[index];
+ }
+
+ public int size()
+ {
+ return sequence.length;
+ }
+
+ public Object[] toArray()
+ {
+ return (Object[]) sequence.clone();
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/SimpleList.java b/libjava/classpath/gnu/java/security/util/SimpleList.java
new file mode 100644
index 000000000..15d54c988
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/SimpleList.java
@@ -0,0 +1,155 @@
+/* SimpleList.java -- simple way to make tuples.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.AbstractList;
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * A simple way to create immutable n-tuples. This class can be created with up
+ * to four elements specified via one of the constructors, or with a collection
+ * of arbitrary size.
+ */
+public final class SimpleList
+ extends AbstractList
+{
+ private final Object[] elements;
+
+ /**
+ * Create a singleton list.
+ *
+ * @param element The first element.
+ */
+ public SimpleList(final Object element)
+ {
+ elements = new Object[1];
+ elements[0] = element;
+ }
+
+ /**
+ * Create an ordered pair (2-tuple).
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ */
+ public SimpleList(final Object e1, final Object e2)
+ {
+ elements = new Object[2];
+ elements[0] = e1;
+ elements[1] = e2;
+ }
+
+ /**
+ * Create a 3-tuple.
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ * @param e3 The third element.
+ */
+ public SimpleList(final Object e1, final Object e2, final Object e3)
+ {
+ elements = new Object[3];
+ elements[0] = e1;
+ elements[1] = e2;
+ elements[2] = e3;
+ }
+
+ /**
+ * Create a 4-tuple.
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ * @param e3 The third element.
+ * @param e4 The fourth element.
+ */
+ public SimpleList(final Object e1, final Object e2, final Object e3,
+ final Object e4)
+ {
+ elements = new Object[4];
+ elements[0] = e1;
+ elements[1] = e2;
+ elements[2] = e3;
+ elements[3] = e4;
+ }
+
+ /**
+ * Create the empty list.
+ */
+ public SimpleList()
+ {
+ elements = null;
+ }
+
+ /**
+ * Create an n-tuple of arbitrary size. Even if the supplied collection has no
+ * natural order, the created n-tuple will have the order that the elements
+ * are returned by the collection's iterator.
+ *
+ * @param c The collection.
+ */
+ public SimpleList(Collection c)
+ {
+ elements = new Object[c.size()];
+ int i = 0;
+ for (Iterator it = c.iterator(); it.hasNext() && i < elements.length;)
+ elements[i++] = it.next();
+ }
+
+ public int size()
+ {
+ if (elements == null)
+ return 0;
+ return elements.length;
+ }
+
+ public Object get(int index)
+ {
+ if (elements == null)
+ throw new IndexOutOfBoundsException("list is empty");
+ if (index < 0 || index >= elements.length)
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
+ return elements[index];
+ }
+
+ public String toString()
+ {
+ return SimpleList.class.getName() + "(" + size() + ") " + super.toString();
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/Util.java b/libjava/classpath/gnu/java/security/util/Util.java
new file mode 100644
index 000000000..ef3d480a0
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/Util.java
@@ -0,0 +1,629 @@
+/* Util.java -- various utility routines.
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import gnu.java.lang.CPStringBuilder;
+
+import java.math.BigInteger;
+
+/**
+ * A collection of utility methods used throughout this project.
+ */
+public class Util
+{
+ // Hex charset
+ private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
+
+ // Base-64 charset
+ private static final String BASE64_CHARS =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
+
+ private static final char[] BASE64_CHARSET = BASE64_CHARS.toCharArray();
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private Util()
+ {
+ super();
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array. Each byte is
+ * converted to 2 hex symbols; zero(es) included.
+ * <p>
+ * This method calls the method with same name and three arguments as:
+ * <pre>
+ * toString(ba, 0, ba.length);
+ * </pre>
+ *
+ * @param ba the byte array to convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
+ */
+ public static String toString(byte[] ba)
+ {
+ return toString(ba, 0, ba.length);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array, starting at
+ * <code>offset</code> and consisting of <code>length</code> bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ *
+ * @param ba the byte array to convert.
+ * @param offset the index from which to start considering the bytes to
+ * convert.
+ * @param length the count of bytes, starting from the designated offset to
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
+ */
+ public static final String toString(byte[] ba, int offset, int length)
+ {
+ char[] buf = new char[length * 2];
+ for (int i = 0, j = 0, k; i < length;)
+ {
+ k = ba[offset + i++];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array. Each byte is
+ * converted to 2 hex symbols; zero(es) included. The argument is treated as a
+ * large little-endian integer and is returned as a large big-endian integer.
+ * <p>
+ * This method calls the method with same name and three arguments as:
+ * <pre>
+ * toReversedString(ba, 0, ba.length);
+ * </pre>
+ *
+ * @param ba the byte array to convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
+ */
+ public static String toReversedString(byte[] ba)
+ {
+ return toReversedString(ba, 0, ba.length);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array, starting at
+ * <code>offset</code> and consisting of <code>length</code> bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ * <p>
+ * The byte array is treated as a large little-endian integer, and is returned
+ * as a large big-endian integer.
+ *
+ * @param ba the byte array to convert.
+ * @param offset the index from which to start considering the bytes to
+ * convert.
+ * @param length the count of bytes, starting from the designated offset to
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
+ */
+ public static final String toReversedString(byte[] ba, int offset, int length)
+ {
+ char[] buf = new char[length * 2];
+ for (int i = offset + length - 1, j = 0, k; i >= offset;)
+ {
+ k = ba[offset + i--];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * <p>
+ * Returns a byte array from a string of hexadecimal digits.
+ * </p>
+ *
+ * @param s a string of hexadecimal ASCII characters
+ * @return the decoded byte array from the input hexadecimal string.
+ */
+ public static byte[] toBytesFromString(String s)
+ {
+ int limit = s.length();
+ byte[] result = new byte[((limit + 1) / 2)];
+ int i = 0, j = 0;
+ if ((limit % 2) == 1)
+ result[j++] = (byte) fromDigit(s.charAt(i++));
+ while (i < limit)
+ {
+ result[j ] = (byte) (fromDigit(s.charAt(i++)) << 4);
+ result[j++] |= (byte) fromDigit(s.charAt(i++));
+ }
+ return result;
+ }
+
+ /**
+ * Returns a byte array from a string of hexadecimal digits, interpreting them
+ * as a large big-endian integer and returning it as a large little-endian
+ * integer.
+ *
+ * @param s a string of hexadecimal ASCII characters
+ * @return the decoded byte array from the input hexadecimal string.
+ */
+ public static byte[] toReversedBytesFromString(String s)
+ {
+ int limit = s.length();
+ byte[] result = new byte[((limit + 1) / 2)];
+ int i = 0;
+ if ((limit % 2) == 1)
+ result[i++] = (byte) fromDigit(s.charAt(--limit));
+ while (limit > 0)
+ {
+ result[i ] = (byte) fromDigit(s.charAt(--limit));
+ result[i++] |= (byte) (fromDigit(s.charAt(--limit)) << 4);
+ }
+ return result;
+ }
+
+ /**
+ * Returns a number from <code>0</code> to <code>15</code> corresponding
+ * to the designated hexadecimal digit.
+ *
+ * @param c a hexadecimal ASCII symbol.
+ */
+ public static int fromDigit(char c)
+ {
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ else if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ else
+ throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
+ }
+
+ /**
+ * Returns a string of 8 hexadecimal digits (most significant digit first)
+ * corresponding to the unsigned integer <code>n</code>.
+ *
+ * @param n the unsigned integer to convert.
+ * @return a hexadecimal string 8-character long.
+ */
+ public static String toString(int n)
+ {
+ char[] buf = new char[8];
+ for (int i = 7; i >= 0; i--)
+ {
+ buf[i] = HEX_DIGITS[n & 0x0F];
+ n >>>= 4;
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from an integer array. Each int is
+ * converted to 4 hex symbols.
+ */
+ public static String toString(int[] ia)
+ {
+ int length = ia.length;
+ char[] buf = new char[length * 8];
+ for (int i = 0, j = 0, k; i < length; i++)
+ {
+ k = ia[i];
+ buf[j++] = HEX_DIGITS[(k >>> 28) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 24) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 20) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 16) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 12) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 8) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of 16 hexadecimal digits (most significant digit first)
+ * corresponding to the unsigned long <code>n</code>.
+ *
+ * @param n the unsigned long to convert.
+ * @return a hexadecimal string 16-character long.
+ */
+ public static String toString(long n)
+ {
+ char[] b = new char[16];
+ for (int i = 15; i >= 0; i--)
+ {
+ b[i] = HEX_DIGITS[(int)(n & 0x0FL)];
+ n >>>= 4;
+ }
+ return new String(b);
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise byte arrays that will be constructed later from such strings;
+ * eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is odd.
+ */
+ public static String toUnicodeString(byte[] ba)
+ {
+ return toUnicodeString(ba, 0, ba.length);
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise byte arrays that will be constructed later from such strings;
+ * eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is odd.
+ */
+ public static final String toUnicodeString(byte[] ba, int offset, int length)
+ {
+ CPStringBuilder sb = new CPStringBuilder();
+ int i = 0;
+ int j = 0;
+ int k;
+ sb.append('\n').append("\"");
+ while (i < length)
+ {
+ sb.append("\\u");
+ k = ba[offset + i++];
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ k = ba[offset + i++];
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ if ((++j % 8) == 0)
+ sb.append("\"+").append('\n').append("\"");
+ }
+ sb.append("\"").append('\n');
+ return sb.toString();
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise integer arrays that will be constructed later from such
+ * strings; eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of
+ * 4.
+ */
+ public static String toUnicodeString(int[] ia)
+ {
+ CPStringBuilder sb = new CPStringBuilder();
+ int i = 0;
+ int j = 0;
+ int k;
+ sb.append('\n').append("\"");
+ while (i < ia.length)
+ {
+ k = ia[i++];
+ sb.append("\\u");
+ sb.append(HEX_DIGITS[(k >>> 28) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 24) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 20) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 16) & 0x0F]);
+ sb.append("\\u");
+ sb.append(HEX_DIGITS[(k >>> 12) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 8) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ if ((++j % 4) == 0)
+ sb.append("\"+").append('\n').append("\"");
+ }
+ sb.append("\"").append('\n');
+ return sb.toString();
+ }
+
+ public static byte[] toBytesFromUnicode(String s)
+ {
+ int limit = s.length() * 2;
+ byte[] result = new byte[limit];
+ char c;
+ for (int i = 0; i < limit; i++)
+ {
+ c = s.charAt(i >>> 1);
+ result[i] = (byte)(((i & 1) == 0) ? c >>> 8 : c);
+ }
+ return result;
+ }
+
+ /**
+ * Dumps a byte array as a string, in a format that is easy to read for
+ * debugging. The string <code>m</code> is prepended to the start of each
+ * line.
+ * <p>
+ * If <code>offset</code> and <code>length</code> are omitted, the whole
+ * array is used. If <code>m</code> is omitted, nothing is prepended to each
+ * line.
+ *
+ * @param data the byte array to be dumped.
+ * @param offset the offset within <i>data</i> to start from.
+ * @param length the number of bytes to dump.
+ * @param m a string to be prepended to each line.
+ * @return a string containing the result.
+ */
+ public static String dumpString(byte[] data, int offset, int length, String m)
+ {
+ if (data == null)
+ return m + "null\n";
+ CPStringBuilder sb = new CPStringBuilder(length * 3);
+ if (length > 32)
+ sb.append(m).append("Hexadecimal dump of ")
+ .append(length).append(" bytes...\n");
+ // each line will list 32 bytes in 4 groups of 8 each
+ int end = offset + length;
+ String s;
+ int l = Integer.toString(length).length();
+ if (l < 4)
+ l = 4;
+ for (; offset < end; offset += 32)
+ {
+ if (length > 32)
+ {
+ s = " " + offset;
+ sb.append(m).append(s.substring(s.length() - l)).append(": ");
+ }
+ int i = 0;
+ for (; i < 32 && offset + i + 7 < end; i += 8)
+ sb.append(toString(data, offset + i, 8)).append(' ');
+ if (i < 32)
+ for (; i < 32 && offset + i < end; i++)
+ sb.append(byteToString(data[offset + i]));
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
+
+ public static String dumpString(byte[] data)
+ {
+ return (data == null) ? "null\n" : dumpString(data, 0, data.length, "");
+ }
+
+ public static String dumpString(byte[] data, String m)
+ {
+ return (data == null) ? "null\n" : dumpString(data, 0, data.length, m);
+ }
+
+ public static String dumpString(byte[] data, int offset, int length)
+ {
+ return dumpString(data, offset, length, "");
+ }
+
+ /**
+ * Returns a string of 2 hexadecimal digits (most significant digit first)
+ * corresponding to the lowest 8 bits of <code>n</code>.
+ *
+ * @param n the byte value to convert.
+ * @return a string of 2 hex characters representing the input.
+ */
+ public static String byteToString(int n)
+ {
+ char[] buf = { HEX_DIGITS[(n >>> 4) & 0x0F], HEX_DIGITS[n & 0x0F] };
+ return new String(buf);
+ }
+
+ /**
+ * Converts a designated byte array to a Base-64 representation, with the
+ * exceptions that (a) leading 0-byte(s) are ignored, and (b) the character
+ * '.' (dot) shall be used instead of "+' (plus).
+ * <p>
+ * Used by SASL password file manipulation primitives.
+ *
+ * @param buffer an arbitrary sequence of bytes to represent in Base-64.
+ * @return unpadded (without the '=' character(s)) Base-64 representation of
+ * the input.
+ */
+ public static final String toBase64(byte[] buffer)
+ {
+ int len = buffer.length, pos = len % 3;
+ byte b0 = 0, b1 = 0, b2 = 0;
+ switch (pos)
+ {
+ case 1:
+ b2 = buffer[0];
+ break;
+ case 2:
+ b1 = buffer[0];
+ b2 = buffer[1];
+ break;
+ }
+ CPStringBuilder sb = new CPStringBuilder();
+ int c;
+ boolean notleading = false;
+ do
+ {
+ c = (b0 & 0xFC) >>> 2;
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = ((b0 & 0x03) << 4) | ((b1 & 0xF0) >>> 4);
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >>> 6);
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = b2 & 0x3F;
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ if (pos >= len)
+ break;
+ else
+ {
+ try
+ {
+ b0 = buffer[pos++];
+ b1 = buffer[pos++];
+ b2 = buffer[pos++];
+ }
+ catch (ArrayIndexOutOfBoundsException x)
+ {
+ break;
+ }
+ }
+ }
+ while (true);
+
+ if (notleading)
+ return sb.toString();
+ return "0";
+ }
+
+ /**
+ * The inverse function of the above.
+ * <p>
+ * Converts a string representing the encoding of some bytes in Base-64 to
+ * their original form.
+ *
+ * @param str the Base-64 encoded representation of some byte(s).
+ * @return the bytes represented by the <code>str</code>.
+ * @throws NumberFormatException if <code>str</code> is <code>null</code>,
+ * or <code>str</code> contains an illegal Base-64 character.
+ * @see #toBase64(byte[])
+ */
+ public static final byte[] fromBase64(String str)
+ {
+ int len = str.length();
+ if (len == 0)
+ throw new NumberFormatException("Empty string");
+ byte[] a = new byte[len + 1];
+ int i, j;
+ for (i = 0; i < len; i++)
+ try
+ {
+ a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
+ }
+ catch (ArrayIndexOutOfBoundsException x)
+ {
+ throw new NumberFormatException("Illegal character at #" + i);
+ }
+ i = len - 1;
+ j = len;
+ try
+ {
+ while (true)
+ {
+ a[j] = a[i];
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] & 0x03) << 6;
+ j--;
+ a[j] = (byte)((a[i] & 0x3C) >>> 2);
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] & 0x0F) << 4;
+ j--;
+ a[j] = (byte)((a[i] & 0x30) >>> 4);
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] << 2);
+ j--;
+ a[j] = 0;
+ if (--i < 0)
+ break;
+ }
+ }
+ catch (Exception ignored)
+ {
+ }
+ try
+ { // ignore leading 0-bytes
+ while (a[j] == 0)
+ j++;
+ }
+ catch (Exception x)
+ {
+ return new byte[1]; // one 0-byte
+ }
+ byte[] result = new byte[len - j + 1];
+ System.arraycopy(a, j, result, 0, len - j + 1);
+ return result;
+ }
+
+ // BigInteger utilities ----------------------------------------------------
+
+ /**
+ * Treats the input as the MSB representation of a number, and discards
+ * leading zero elements. For efficiency, the input is simply returned if no
+ * leading zeroes are found.
+ *
+ * @param n the {@link BigInteger} to trim.
+ * @return the byte array representation of the designated {@link BigInteger}
+ * with no leading 0-bytes.
+ */
+ public static final byte[] trim(BigInteger n)
+ {
+ byte[] in = n.toByteArray();
+ if (in.length == 0 || in[0] != 0)
+ return in;
+ int len = in.length;
+ int i = 1;
+ while (in[i] == 0 && i < len)
+ ++i;
+ byte[] result = new byte[len - i];
+ System.arraycopy(in, i, result, 0, len - i);
+ return result;
+ }
+
+ /**
+ * Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}.
+ *
+ * @param x the {@link BigInteger} to display.
+ * @return the string representation of the designated {@link BigInteger}.
+ */
+ public static final String dump(BigInteger x)
+ {
+ return dumpString(trim(x));
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/package.html b/libjava/classpath/gnu/java/security/util/package.html
new file mode 100644
index 000000000..36dd33b79
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/package.html
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.security.util package.
+ Copyright (C) 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.security.util</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>