[llvm-commits] [llvm-gcc-4.2] r43913 [26/80] - in /llvm-gcc-4.2/trunk: boehm-gc/ boehm-gc/Mac_files/ boehm-gc/cord/ boehm-gc/doc/ boehm-gc/include/ boehm-gc/include/private/ boehm-gc/tests/ libffi/ libffi/include/ libffi/src/ libffi/src/alpha/ libffi/src/arm/ libffi/src/cris/ libffi/src/frv/ libffi/src/ia64/ libffi/src/m32r/ libffi/src/m68k/ libffi/src/mips/ libffi/src/pa/ libffi/src/powerpc/ libffi/src/s390/ libffi/src/sh/ libffi/src/sh64/ libffi/src/sparc/ libffi/src/x86/ libffi/testsuite/ libffi/testsuite/config/ li...
Bill Wendling
isanbard at gmail.com
Thu Nov 8 14:57:11 PST 2007
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,158 @@
+/* BaseKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Registry;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+public abstract class BaseKeyring
+ implements IKeyring
+{
+ /** The top-level keyring data. */
+ protected PasswordAuthenticatedEntry keyring;
+ protected CompressedEntry keyring2;
+
+ public BaseKeyring()
+ {
+ }
+
+ public void load(Map attributes) throws IOException
+ {
+ InputStream in = (InputStream) attributes.get(KEYRING_DATA_IN);
+ if (in == null)
+ throw new IllegalArgumentException("no input stream");
+ char[] password = (char[]) attributes.get(KEYRING_PASSWORD);
+ if (password == null)
+ password = new char[0];
+
+ if (in.read() != Registry.GKR_MAGIC[0]
+ || in.read() != Registry.GKR_MAGIC[1]
+ || in.read() != Registry.GKR_MAGIC[2]
+ || in.read() != Registry.GKR_MAGIC[3])
+ throw new MalformedKeyringException("magic");
+
+ load(in, password);
+ List l = keyring.getEntries();
+ if (l.size() == 1 && (l.get(0) instanceof CompressedEntry))
+ keyring2 = (CompressedEntry) l.get(0);
+ }
+
+ public void store(Map attributes) throws IOException
+ {
+ OutputStream out = (OutputStream) attributes.get(KEYRING_DATA_OUT);
+ if (out == null)
+ throw new IllegalArgumentException("no output stream");
+ char[] password = (char[]) attributes.get(KEYRING_PASSWORD);
+ if (password == null)
+ password = new char[0];
+ if (keyring == null)
+ throw new IllegalStateException("empty keyring");
+
+ out.write(Registry.GKR_MAGIC);
+ store(out, password);
+ }
+
+ public void reset()
+ {
+ keyring = null;
+ }
+
+ public int size()
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ return ((StringTokenizer) aliases()).countTokens();
+ }
+
+ public Enumeration aliases()
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ return new StringTokenizer(keyring.getAliasList(), ";");
+ }
+
+ public boolean containsAlias(String alias)
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ return keyring.containsAlias(alias);
+ }
+
+ public List get(String alias)
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ return keyring.get(alias);
+ }
+
+ public void add(Entry entry)
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ if (keyring2 != null)
+ keyring2.add(entry);
+ else
+ keyring.add(entry);
+ }
+
+ public void remove(String alias)
+ {
+ if (keyring == null)
+ throw new IllegalStateException("keyring not loaded");
+ keyring.remove(alias);
+ }
+
+ protected String fixAlias(String alias)
+ {
+ return alias.replace(';', '_');
+ }
+
+ protected abstract void load(InputStream in, char[] password)
+ throws IOException;
+
+ protected abstract void store(OutputStream out, char[] password)
+ throws IOException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* BinaryDataEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.util.Date;
+
+/**
+ * A binary data entry is a primitive entry that simply contains some amount of
+ * arbitrary binary data and an optional content type.
+ */
+public class BinaryDataEntry
+ extends PrimitiveEntry
+{
+ public static final int TYPE = 9;
+
+ /**
+ * Creates a new binary data entry.
+ *
+ * @param contentType The content type of this entry. This parameter can be
+ * <code>null</code> if no content type is needed.
+ * @param data The data.
+ * @param creationDate The creation date.
+ * @param properties This entry's properties.
+ */
+ public BinaryDataEntry(String contentType, byte[] data, Date creationDate,
+ Properties properties)
+ {
+ super(TYPE, creationDate, properties);
+ if (data == null)
+ throw new IllegalArgumentException("no data");
+ payload = (byte[]) data.clone();
+ if (contentType != null)
+ this.properties.put("content-type", contentType);
+ }
+
+ private BinaryDataEntry()
+ {
+ super(TYPE);
+ }
+
+ public static BinaryDataEntry decode(DataInputStream in) throws IOException
+ {
+ BinaryDataEntry entry = new BinaryDataEntry();
+ entry.defaultDecode(in);
+ return entry;
+ }
+
+ /**
+ * Returns the content type of this entry, or <code>null</code> if this
+ * property is not set.
+ *
+ * @return The content type.
+ */
+ public String getContentType()
+ {
+ return properties.get("content-type");
+ }
+
+ /**
+ * Returns this object's data field.
+ *
+ * @return The data.
+ */
+ public byte[] getData()
+ {
+ return getPayload();
+ }
+
+ protected void encodePayload()
+ {
+ // Empty.
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* CertPathEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.util.Date;
+
+/**
+ * A primitive entry that contains a path of X.509 certificates.
+ */
+public final class CertPathEntry
+ extends PrimitiveEntry
+{
+ public static final int TYPE = 8;
+ private Certificate[] path;
+
+ public CertPathEntry(Certificate[] path, Date creationDate,
+ Properties properties)
+ {
+ super(TYPE, creationDate, properties);
+ if (path == null || path.length == 0)
+ throw new IllegalArgumentException("no certificate path");
+ this.path = (Certificate[]) path.clone();
+ }
+
+ private CertPathEntry()
+ {
+ super(TYPE);
+ }
+
+ public static CertPathEntry decode(DataInputStream in) throws IOException
+ {
+ CertPathEntry entry = new CertPathEntry();
+ entry.properties.decode(in);
+ entry.makeCreationDate();
+ int len = in.readInt();
+ MeteredInputStream in2 = new MeteredInputStream(in, len);
+ try
+ {
+ CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ entry.path = (Certificate[]) fact.generateCertificates(in2).toArray(new Certificate[0]);
+ }
+ catch (CertificateException ce)
+ {
+ throw new MalformedKeyringException(ce.toString());
+ }
+ return entry;
+ }
+
+ public Certificate[] getCertPath()
+ {
+ return path;
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ byte[] enc = null;
+ try
+ {
+ for (int i = 0; i < path.length; i++)
+ bout.write(path[i].getEncoded());
+ }
+ catch (CertificateEncodingException cee)
+ {
+ throw new IOException(cee.toString());
+ }
+ payload = bout.toByteArray();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* CertificateEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.util.Date;
+
+/**
+ * An immutable class representing a trusted certificate entry.
+ */
+public final class CertificateEntry
+ extends PrimitiveEntry
+{
+ public static final int TYPE = 5;
+ /** The certificate. */
+ private Certificate certificate;
+
+ /**
+ * Creates a new certificate entry.
+ *
+ * @param certificate The certificate.
+ * @param creationDate The creation date.
+ * @param properties The alias.
+ * @throws IllegalArgumentException If any argument is null, or if the alias
+ * is empty.
+ */
+ public CertificateEntry(Certificate certificate, Date creationDate,
+ Properties properties)
+ {
+ super(TYPE, creationDate, properties);
+ if (certificate == null)
+ throw new IllegalArgumentException("no certificate");
+ this.certificate = certificate;
+ this.properties.put("type", certificate.getType());
+ }
+
+ private CertificateEntry()
+ {
+ super(TYPE);
+ }
+
+ public static CertificateEntry decode(DataInputStream in) throws IOException
+ {
+ CertificateEntry entry = new CertificateEntry();
+ entry.properties.decode(in);
+ entry.makeCreationDate();
+ String type = entry.properties.get("type");
+ if (type == null)
+ throw new MalformedKeyringException("no certificate type");
+ int len = in.readInt();
+ MeteredInputStream in2 = new MeteredInputStream(in, len);
+ try
+ {
+ CertificateFactory fact = CertificateFactory.getInstance(type);
+ entry.certificate = fact.generateCertificate(in2);
+ }
+ catch (CertificateException ce)
+ {
+ throw new MalformedKeyringException(ce.toString());
+ }
+ if (! in2.limitReached())
+ throw new MalformedKeyringException("extra data at end of payload");
+ return entry;
+ }
+
+ /**
+ * Returns this entry's certificate.
+ *
+ * @return The certificate.
+ */
+ public Certificate getCertificate()
+ {
+ return certificate;
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ try
+ {
+ payload = certificate.getEncoded();
+ }
+ catch (CertificateEncodingException cee)
+ {
+ throw new IOException(cee.toString());
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CompressedEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CompressedEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CompressedEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/CompressedEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,93 @@
+/* CompressedEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.InflaterInputStream;
+
+public class CompressedEntry
+ extends EnvelopeEntry
+{
+ public static final int TYPE = 4;
+
+ public CompressedEntry(Properties properties)
+ {
+ super(TYPE, properties);
+ this.properties.put("algorithm", "DEFLATE");
+ }
+
+ private CompressedEntry()
+ {
+ this(new Properties());
+ }
+
+ public static CompressedEntry decode(DataInputStream in) throws IOException
+ {
+ CompressedEntry entry = new CompressedEntry();
+ entry.properties.decode(in);
+ String alg = entry.properties.get("algorithm");
+ if (alg == null)
+ throw new MalformedKeyringException("no compression algorithm");
+ if (! alg.equalsIgnoreCase("DEFLATE"))
+ throw new MalformedKeyringException("unsupported compression algorithm: "
+ + alg);
+ int len = in.readInt();
+ MeteredInputStream min = new MeteredInputStream(in, len);
+ InflaterInputStream infin = new InflaterInputStream(min);
+ DataInputStream in2 = new DataInputStream(infin);
+ entry.decodeEnvelope(in2);
+ return entry;
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream(1024);
+ DeflaterOutputStream dout = new DeflaterOutputStream(buf);
+ DataOutputStream out2 = new DataOutputStream(dout);
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ ((Entry) it.next()).encode(out2);
+ dout.finish();
+ payload = buf.toByteArray();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EncryptedEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EncryptedEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EncryptedEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EncryptedEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,191 @@
+/* EncryptedEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.mode.IMode;
+import gnu.javax.crypto.mode.ModeFactory;
+import gnu.javax.crypto.pad.IPad;
+import gnu.javax.crypto.pad.PadFactory;
+import gnu.javax.crypto.pad.WrongPaddingException;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Iterator;
+
+public class EncryptedEntry extends MaskableEnvelopeEntry implements Registry
+{
+ public static final int TYPE = 0;
+
+ public EncryptedEntry(String cipher, String mode, Properties properties)
+ {
+ super(TYPE, properties);
+ if (cipher == null || mode == null)
+ throw new IllegalArgumentException("neither cipher nor mode can be null");
+ properties.put("cipher", cipher);
+ properties.put("mode", mode);
+ setMasked(false);
+ }
+
+ private EncryptedEntry()
+ {
+ super(TYPE, new Properties());
+ setMasked(true);
+ }
+
+ public static EncryptedEntry decode(DataInputStream in) throws IOException
+ {
+ EncryptedEntry entry = new EncryptedEntry();
+ entry.defaultDecode(in);
+ if (! entry.properties.containsKey("cipher"))
+ throw new MalformedKeyringException("no cipher");
+ if (! entry.properties.containsKey("cipher"))
+ throw new MalformedKeyringException("no cipher");
+ return entry;
+ }
+
+ public void decrypt(byte[] key, byte[] iv) throws IllegalArgumentException,
+ WrongPaddingException
+ {
+ if (! isMasked() || payload == null)
+ return;
+ IMode mode = getMode(key, iv, IMode.DECRYPTION);
+ IPad padding = null;
+ padding = PadFactory.getInstance("PKCS7");
+ padding.init(mode.currentBlockSize());
+ byte[] buf = new byte[payload.length];
+ int count = 0;
+ for (int i = 0; i < payload.length; i++)
+ {
+ mode.update(payload, count, buf, count);
+ count += mode.currentBlockSize();
+ }
+ int padlen = padding.unpad(buf, 0, buf.length);
+ int len = buf.length - padlen;
+ DataInputStream in = new DataInputStream(new ByteArrayInputStream(buf, 0, len));
+ try
+ {
+ decodeEnvelope(in);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalArgumentException("decryption failed");
+ }
+ setMasked(false);
+ payload = null;
+ }
+
+ public void encrypt(byte[] key, byte[] iv) throws IOException
+ {
+ IMode mode = getMode(key, iv, IMode.ENCRYPTION);
+ IPad pad = PadFactory.getInstance("PKCS7");
+ pad.init(mode.currentBlockSize());
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ DataOutputStream out2 = new DataOutputStream(bout);
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry entry = (Entry) it.next();
+ entry.encode(out2);
+ }
+ byte[] plaintext = bout.toByteArray();
+ byte[] padding = pad.pad(plaintext, 0, plaintext.length);
+ payload = new byte[plaintext.length + padding.length];
+ byte[] lastBlock = new byte[mode.currentBlockSize()];
+ int l = mode.currentBlockSize() - padding.length;
+ System.arraycopy(plaintext, plaintext.length - l, lastBlock, 0, l);
+ System.arraycopy(padding, 0, lastBlock, l, padding.length);
+ int count = 0;
+ while (count + mode.currentBlockSize() < plaintext.length)
+ {
+ mode.update(plaintext, count, payload, count);
+ count += mode.currentBlockSize();
+ }
+ mode.update(lastBlock, 0, payload, count);
+ }
+
+ public void encodePayload() throws IOException
+ {
+ if (payload == null)
+ throw new IOException("not encrypted");
+ }
+
+ private IMode getMode(byte[] key, byte[] iv, int state)
+ {
+ IBlockCipher cipher = CipherFactory.getInstance(properties.get("cipher"));
+ if (cipher == null)
+ throw new IllegalArgumentException("no such cipher: " + properties.get("cipher"));
+ int blockSize = cipher.defaultBlockSize();
+ if (properties.containsKey("block-size"))
+ {
+ try
+ {
+ blockSize = Integer.parseInt(properties.get("block-size"));
+ }
+ catch (NumberFormatException nfe)
+ {
+ throw new IllegalArgumentException("bad block size: "
+ + nfe.getMessage());
+ }
+ }
+ IMode mode = ModeFactory.getInstance(properties.get("mode"), cipher, blockSize);
+ if (mode == null)
+ throw new IllegalArgumentException("no such mode: " + properties.get("mode"));
+
+ HashMap modeAttr = new HashMap();
+ modeAttr.put(IMode.KEY_MATERIAL, key);
+ modeAttr.put(IMode.STATE, Integer.valueOf(state));
+ modeAttr.put(IMode.IV, iv);
+ try
+ {
+ mode.init(modeAttr);
+ }
+ catch (InvalidKeyException ike)
+ {
+ throw new IllegalArgumentException(ike.toString());
+ }
+ return mode;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Entry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Entry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Entry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Entry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,179 @@
+/* Entry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.logging.Logger;
+
+/**
+ * An immutable class representing a single entry in a keyring.
+ */
+public abstract class Entry
+{
+ private static final Logger log = Logger.getLogger(Entry.class.getName());
+ private static final String[] TYPES = new String[] {
+ "Encrypted",
+ "PasswordEncrypted",
+ "Authenticated",
+ "PasswordAuthenticated",
+ "Compressed",
+ "Certificate",
+ "PublicKey",
+ "PrivateKey",
+ "CertPath",
+ "BinaryData" };
+ /** This entry's type identifier. */
+ protected int type;
+ /** This entry's property set. */
+ protected Properties properties;
+ /** This entry's payload. */
+ protected byte[] payload;
+
+ /**
+ * Creates a new Entry.
+ *
+ * @param type This entry's type.
+ * @param properties This entry's properties.
+ * @throws IllegalArgumentException If the properties argument is null, or if
+ * the type is out of range.
+ */
+ protected Entry(int type, Properties properties)
+ {
+ if (type < 0 || type > 255)
+ throw new IllegalArgumentException("invalid packet type");
+ if (properties == null)
+ throw new IllegalArgumentException("no properties");
+ this.type = type;
+ this.properties = (Properties) properties.clone();
+ }
+
+ /**
+ * Constructor for use by subclasses.
+ */
+ protected Entry(final int type)
+ {
+ if (type < 0 || type > 255)
+ throw new IllegalArgumentException("invalid packet type");
+ this.type = type;
+ properties = new Properties();
+ }
+
+ /**
+ * Returns this entry's properties object. The properties are cloned before
+ * being returned.
+ *
+ * @return The properties.
+ */
+ public Properties getProperties()
+ {
+ return (Properties) properties.clone();
+ }
+
+ /**
+ * Returns this entry's payload data, or null if
+ */
+ public byte[] getPayload()
+ {
+ if (payload == null)
+ return null;
+ return (byte[]) payload.clone();
+ }
+
+ /**
+ * This method is called when this entry needs to be written to an output
+ * stream.
+ *
+ * @param out The stream to write to.
+ * @throws IOException If an I/O exception occurs.
+ */
+ public void encode(DataOutputStream out) throws IOException
+ {
+ if (payload == null)
+ encodePayload();
+ if (out == null)
+ return;
+ out.write(type);
+ properties.encode(out);
+ out.writeInt(payload.length);
+ out.write(payload);
+ }
+
+ public String toString()
+ {
+ return new StringBuilder("Entry{")
+ .append("type=").append(TYPES[type])
+ .append(", properties=").append(properties)
+ .append(", payload=")
+ .append(payload == null ? "-" : "byte[" + payload.length + "]")
+ .append( "}")
+ .toString();
+ }
+
+ /**
+ * Generic decoding method, which simply decodes the properties field
+ * and reads the payload field.
+ *
+ * @param in The input data stream.
+ * @throws IOException If an I/O error occurs.
+ */
+ protected void defaultDecode(DataInputStream in) throws IOException
+ {
+ properties = new Properties();
+ properties.decode(in);
+ int len = in.readInt();
+ if (len < 0)
+ throw new IOException("corrupt length");
+ if (Configuration.DEBUG)
+ log.fine("About to instantiate new payload byte array for " + this);
+ payload = new byte[len];
+ in.readFully(payload);
+ }
+
+ /**
+ * This method is called of subclasses when the payload data needs to be
+ * created.
+ *
+ * @throws IOException If an encoding error occurs.
+ */
+ protected abstract void encodePayload() throws IOException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EnvelopeEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EnvelopeEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EnvelopeEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/EnvelopeEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,439 @@
+/* EnvelopeEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.logging.Logger;
+
+/**
+ * An envelope entry is a generic container for some number of primitive and
+ * other envelope entries.
+ */
+public abstract class EnvelopeEntry
+ extends Entry
+{
+ private static final Logger log = Logger.getLogger(EnvelopeEntry.class.getName());
+ /** The envelope that contains this one (if any). */
+ protected EnvelopeEntry containingEnvelope;
+ /** The contained entries. */
+ protected List entries;
+
+ public EnvelopeEntry(int type, Properties properties)
+ {
+ super(type, properties);
+ entries = new LinkedList();
+ if (this.properties.get("alias-list") != null)
+ this.properties.remove("alias-list");
+ }
+
+ protected EnvelopeEntry(int type)
+ {
+ super(type);
+ entries = new LinkedList();
+ }
+
+ /**
+ * Adds an entry to this envelope.
+ *
+ * @param entry The entry to add.
+ */
+ public void add(Entry entry)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "add", entry);
+ if (! containsEntry(entry))
+ {
+ if (entry instanceof EnvelopeEntry)
+ ((EnvelopeEntry) entry).setContainingEnvelope(this);
+ entries.add(entry);
+ if (Configuration.DEBUG)
+ log.fine("Payload is " + (payload == null ? "" : "not ") + "null");
+ makeAliasList();
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "add");
+ }
+
+ /**
+ * Tests if this envelope contains a primitive entry with the given alias.
+ *
+ * @param alias The alias to test.
+ * @return True if this envelope (or one of the contained envelopes) contains
+ * a primitive entry with the given alias.
+ */
+ public boolean containsAlias(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsAlias", alias);
+ String aliases = getAliasList();
+ if (Configuration.DEBUG)
+ log.fine("aliases = [" + aliases + "]");
+ boolean result = false;
+ if (aliases != null)
+ {
+ StringTokenizer tok = new StringTokenizer(aliases, ";");
+ while (tok.hasMoreTokens())
+ if (tok.nextToken().equals(alias))
+ {
+ result = true;
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsAlias",
+ Boolean.valueOf(result));
+ return result;
+ }
+
+ /**
+ * Tests if this envelope contains the given entry.
+ *
+ * @param entry The entry to test.
+ * @return True if this envelope contains the given entry.
+ */
+ public boolean containsEntry(Entry entry)
+ {
+ if (entry instanceof EnvelopeEntry)
+ return entries.contains(entry);
+ if (entry instanceof PrimitiveEntry)
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e.equals(entry))
+ return true;
+ if ((e instanceof EnvelopeEntry)
+ && ((EnvelopeEntry) e).containsEntry(entry))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns a copy of all entries this envelope contains.
+ *
+ * @return All contained entries.
+ */
+ public List getEntries()
+ {
+ return new ArrayList(entries);
+ }
+
+ /**
+ * Gets all primitive entries that have the given alias. If there are any
+ * masked entries that contain the given alias, they will be returned as well.
+ *
+ * @param alias The alias of the entries to get.
+ * @return A list of all primitive entries that have the given alias.
+ */
+ public List get(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "get", alias);
+ List result = new LinkedList();
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof EnvelopeEntry)
+ {
+ EnvelopeEntry ee = (EnvelopeEntry) e;
+ if (! ee.containsAlias(alias))
+ continue;
+ if (ee instanceof MaskableEnvelopeEntry)
+ {
+ MaskableEnvelopeEntry mee = (MaskableEnvelopeEntry) ee;
+ if (mee.isMasked())
+ {
+ if (Configuration.DEBUG)
+ log.fine("Processing masked entry: " + mee);
+ result.add(mee);
+ continue;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.fine("Processing unmasked entry: " + ee);
+ result.addAll(ee.get(alias));
+ }
+ else if (e instanceof PrimitiveEntry)
+ {
+ PrimitiveEntry pe = (PrimitiveEntry) e;
+ if (pe.getAlias().equals(alias))
+ result.add(e);
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "get", result);
+ return result;
+ }
+
+ /**
+ * Returns the list of all aliases contained by this envelope, separated by a
+ * semicolon (';').
+ *
+ * @return The list of aliases.
+ */
+ public String getAliasList()
+ {
+ String list = properties.get("alias-list");
+ if (list == null)
+ return "";
+ else
+ return list;
+ }
+
+ /**
+ * Removes the specified entry.
+ *
+ * @param entry The entry.
+ * @return True if an entry was removed.
+ */
+ public boolean remove(Entry entry)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "remove", entry);
+ boolean ret = false;
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof EnvelopeEntry)
+ {
+ if (e == entry)
+ {
+ it.remove();
+ ret = true;
+ break;
+ }
+ if (((EnvelopeEntry) e).remove(entry))
+ {
+ ret = true;
+ break;
+ }
+ }
+ else if (e instanceof PrimitiveEntry)
+ {
+ if (((PrimitiveEntry) e).equals(entry))
+ {
+ it.remove();
+ ret = true;
+ break;
+ }
+ }
+ }
+ if (ret)
+ {
+ if (Configuration.DEBUG)
+ log.fine("State before: " + this);
+ payload = null;
+ makeAliasList();
+ if (Configuration.DEBUG)
+ log.fine("State after: " + this);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(ret));
+ return ret;
+ }
+
+ /**
+ * Removes all primitive entries that have the specified alias.
+ *
+ * @param alias The alias of the entries to remove.
+ * @return <code>true</code> if <code>alias</code> was present and was
+ * successfully trmoved. Returns <code>false</code> if
+ * <code>alias</code> was not present in the list of aliases in this
+ * envelope.
+ */
+ public boolean remove(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "remove", alias);
+ boolean result = false;
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof EnvelopeEntry)
+ {
+ EnvelopeEntry ee = (EnvelopeEntry) e;
+ result = ee.remove(alias) || result;
+ }
+ else if (e instanceof PrimitiveEntry)
+ {
+ PrimitiveEntry pe = (PrimitiveEntry) e;
+ if (pe.getAlias().equals(alias))
+ {
+ it.remove();
+ result = true;
+ }
+ }
+ }
+ if (result)
+ {
+ if (Configuration.DEBUG)
+ log.fine("State before: " + this);
+ payload = null;
+ makeAliasList();
+ if (Configuration.DEBUG)
+ log.fine("State after: " + this);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(result));
+ return result;
+ }
+
+ public String toString()
+ {
+ return new StringBuilder("Envelope{")
+ .append(super.toString())
+ .append(", entries=").append(entries)
+ .append("}")
+ .toString();
+ }
+
+ // Protected methods.
+ // ------------------------------------------------------------------------
+
+ protected void encodePayload() throws IOException
+ {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ DataOutputStream out = new DataOutputStream(bout);
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ ((Entry) it.next()).encode(out);
+ }
+
+ protected void setContainingEnvelope(EnvelopeEntry e)
+ {
+ if (containingEnvelope != null)
+ throw new IllegalArgumentException("envelopes may not be shared");
+ containingEnvelope = e;
+ }
+
+ protected void decodeEnvelope(DataInputStream in) throws IOException
+ {
+ this.entries.clear();
+ while (true)
+ {
+ int type = in.read();
+ switch (type)
+ {
+ case EncryptedEntry.TYPE:
+ add(EncryptedEntry.decode(in));
+ break;
+ case PasswordEncryptedEntry.TYPE:
+ add(PasswordEncryptedEntry.decode(in));
+ break;
+ case PasswordAuthenticatedEntry.TYPE:
+ add(PasswordAuthenticatedEntry.decode(in));
+ break;
+ case AuthenticatedEntry.TYPE:
+ add(AuthenticatedEntry.decode(in));
+ break;
+ case CompressedEntry.TYPE:
+ add(CompressedEntry.decode(in));
+ break;
+ case CertificateEntry.TYPE:
+ add(CertificateEntry.decode(in));
+ break;
+ case PublicKeyEntry.TYPE:
+ add(PublicKeyEntry.decode(in));
+ break;
+ case PrivateKeyEntry.TYPE:
+ add(PrivateKeyEntry.decode(in));
+ break;
+ case CertPathEntry.TYPE:
+ add(CertPathEntry.decode(in));
+ break;
+ case BinaryDataEntry.TYPE:
+ add(BinaryDataEntry.decode(in));
+ break;
+ case -1:
+ return;
+ default:
+ throw new MalformedKeyringException("unknown type " + type);
+ }
+ }
+ }
+
+ private void makeAliasList()
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "makeAliasList");
+ if (! entries.isEmpty())
+ {
+ StringBuilder buf = new StringBuilder();
+ String aliasOrList;
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry entry = (Entry) it.next();
+ aliasOrList = null;
+ if (entry instanceof EnvelopeEntry)
+ aliasOrList = ((EnvelopeEntry) entry).getAliasList();
+ else if (entry instanceof PrimitiveEntry)
+ aliasOrList = ((PrimitiveEntry) entry).getAlias();
+ else if (Configuration.DEBUG)
+ log.fine("Entry with no Alias. Ignored: " + entry);
+ if (aliasOrList != null)
+ {
+ aliasOrList = aliasOrList.trim();
+ if (aliasOrList.trim().length() > 0)
+ {
+ buf.append(aliasOrList);
+ if (it.hasNext())
+ buf.append(';');
+ }
+ }
+ }
+ String aliasList = buf.toString();
+ properties.put("alias-list", aliasList);
+ if (Configuration.DEBUG)
+ log.fine("alias-list=[" + aliasList + "]");
+ if (containingEnvelope != null)
+ containingEnvelope.makeAliasList();
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "makeAliasList");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,368 @@
+/* GnuPrivateKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.Key;
+import java.security.PublicKey;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ */
+public class GnuPrivateKeyring
+ extends BaseKeyring
+ implements IPrivateKeyring
+{
+ private static final Logger log = Logger.getLogger(GnuPrivateKeyring.class.getName());
+ public static final int USAGE = Registry.GKR_PRIVATE_KEYS
+ | Registry.GKR_PUBLIC_CREDENTIALS;
+ protected String mac;
+ protected int maclen;
+ protected String cipher;
+ protected String mode;
+ protected int keylen;
+
+ public GnuPrivateKeyring(String mac, int maclen, String cipher, String mode,
+ int keylen)
+ {
+ keyring = new PasswordAuthenticatedEntry(mac, maclen, new Properties());
+ keyring2 = new CompressedEntry(new Properties());
+ keyring.add(keyring2);
+ this.mac = mac;
+ this.maclen = maclen;
+ this.cipher = cipher;
+ this.mode = mode;
+ this.keylen = keylen;
+ }
+
+ public GnuPrivateKeyring()
+ {
+ this("HMAC-SHA-1", 20, "AES", "OFB", 16);
+ }
+
+ public boolean containsPrivateKey(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsPrivateKey", alias);
+ boolean result = false;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ if (it.next() instanceof PasswordAuthenticatedEntry)
+ {
+ result = true;
+ break;
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsPrivateKey",
+ Boolean.valueOf(result));
+ return result;
+ }
+
+ public Key getPrivateKey(String alias, char[] password)
+ throws UnrecoverableKeyException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getPrivateKey", alias);
+ Key result = null;
+ if (containsAlias(alias))
+ {
+ PasswordAuthenticatedEntry e1 = null;
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (Configuration.DEBUG)
+ log.finest("Entry: " + e);
+ if (e instanceof PasswordAuthenticatedEntry)
+ {
+ e1 = (PasswordAuthenticatedEntry) e;
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.fine("e1 = " + e1);
+ if (e1 != null)
+ {
+ try
+ {
+ e1.verify(password);
+ }
+ catch (Exception e)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "getPrivateKey", e);
+ throw new UnrecoverableKeyException("authentication failed");
+ }
+ PasswordEncryptedEntry e2 = null;
+ for (Iterator it = e1.getEntries().iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof PasswordEncryptedEntry)
+ {
+ e2 = (PasswordEncryptedEntry) e;
+ break;
+ }
+ }
+ if (e2 != null)
+ {
+ try
+ {
+ e2.decrypt(password);
+ }
+ catch (Exception e)
+ {
+ log.throwing(this.getClass().getName(), "getPrivateKey", e);
+ throw new UnrecoverableKeyException("decryption failed");
+ }
+ for (Iterator it = e2.get(alias).iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof PrivateKeyEntry)
+ {
+ result = ((PrivateKeyEntry) e).getKey();
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getPrivateKey",
+ result == null ? "null" : result.getClass().getName());
+ return result;
+ }
+
+ public void putPrivateKey(String alias, Key key, char[] password)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putPrivateKey",
+ new Object[] { alias, key.getClass().getName() });
+ if (! containsPrivateKey(alias))
+ {
+ alias = fixAlias(alias);
+ Properties p = new Properties();
+ p.put("alias", alias);
+ PrivateKeyEntry pke = new PrivateKeyEntry(key, new Date(), p);
+ if (Configuration.DEBUG)
+ log.fine("About to encrypt the key...");
+ PasswordEncryptedEntry enc;
+ enc = new PasswordEncryptedEntry(cipher, mode, keylen, new Properties());
+ enc.add(pke);
+ try
+ {
+ enc.encode(null, password);
+ }
+ catch (IOException x)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception while encrypting the key. "
+ + "Rethrow as IllegalArgumentException", x);
+ throw new IllegalArgumentException(x.toString());
+ }
+ if (Configuration.DEBUG)
+ log.fine("About to authenticate the encrypted key...");
+ PasswordAuthenticatedEntry auth;
+ auth = new PasswordAuthenticatedEntry(mac, maclen, new Properties());
+ auth.add(enc);
+ try
+ {
+ auth.encode(null, password);
+ }
+ catch (IOException x)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception while authenticating the encrypted "
+ + "key. Rethrow as IllegalArgumentException", x);
+ throw new IllegalArgumentException(x.toString());
+ }
+ keyring.add(auth);
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putPrivateKey");
+ }
+
+ public boolean containsPublicKey(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsPublicKey", alias);
+ boolean result = false;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ if (it.next() instanceof PublicKeyEntry)
+ {
+ result = true;
+ break;
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsPublicKey",
+ Boolean.valueOf(result));
+ return result;
+ }
+
+ public PublicKey getPublicKey(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getPublicKey", alias);
+ PublicKey result = null;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof PublicKeyEntry)
+ {
+ result = ((PublicKeyEntry) e).getKey();
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getPublicKey",
+ result == null ? "null" : result.getClass().getName());
+ return result;
+ }
+
+ public void putPublicKey(String alias, PublicKey key)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putPublicKey",
+ new Object[] { alias, key.getClass().getName() });
+ if (! containsPublicKey(alias))
+ {
+ Properties p = new Properties();
+ p.put("alias", fixAlias(alias));
+ add(new PublicKeyEntry(key, new Date(), p));
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putPublicKey");
+ }
+
+ public boolean containsCertPath(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsCertPath", alias);
+ boolean result = false;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ if (it.next() instanceof CertPathEntry)
+ {
+ result = true;
+ break;
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsCertPath",
+ Boolean.valueOf(result));
+ return result;
+ }
+
+ public Certificate[] getCertPath(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getCertPath", alias);
+ Certificate[] result = null;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof CertPathEntry)
+ {
+ result = ((CertPathEntry) e).getCertPath();
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getCertPath", result);
+ return result;
+ }
+
+ public void putCertPath(String alias, Certificate[] path)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putCertPath",
+ new Object[] { alias, path });
+ if (! containsCertPath(alias))
+ {
+ Properties p = new Properties();
+ p.put("alias", fixAlias(alias));
+ add(new CertPathEntry(path, new Date(), p));
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putCertPath");
+ }
+
+ protected void load(InputStream in, char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "load");
+ if (in.read() != USAGE)
+ throw new MalformedKeyringException("incompatible keyring usage");
+ if (in.read() != PasswordAuthenticatedEntry.TYPE)
+ throw new MalformedKeyringException(
+ "expecting password-authenticated entry tag");
+ keyring = PasswordAuthenticatedEntry.decode(new DataInputStream(in), password);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "load");
+ }
+
+ protected void store(OutputStream out, char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "store");
+ out.write(USAGE);
+ keyring.encode(new DataOutputStream(out), password);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "store");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPublicKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPublicKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPublicKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/GnuPublicKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,151 @@
+/* GnuPublicKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.cert.Certificate;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+public class GnuPublicKeyring
+ extends BaseKeyring
+ implements IPublicKeyring
+{
+ private static final Logger log = Logger.getLogger(GnuPublicKeyring.class.getName());
+ public static final int USAGE = Registry.GKR_CERTIFICATES;
+
+ public GnuPublicKeyring(String mac, int macLen)
+ {
+ keyring = new PasswordAuthenticatedEntry(mac, macLen, new Properties());
+ keyring2 = new CompressedEntry(new Properties());
+ keyring.add(keyring2);
+ }
+
+ public GnuPublicKeyring()
+ {
+ }
+
+ public boolean containsCertificate(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsCertificate", alias);
+ boolean result = false;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ if (it.next() instanceof CertificateEntry)
+ {
+ result = true;
+ break;
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsCertificate",
+ Boolean.valueOf(result));
+ return result;
+ }
+
+ public Certificate getCertificate(String alias)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getCertificate", alias);
+ Certificate result = null;
+ if (containsAlias(alias))
+ for (Iterator it = get(alias).iterator(); it.hasNext();)
+ {
+ Entry e = (Entry) it.next();
+ if (e instanceof CertificateEntry)
+ {
+ result = ((CertificateEntry) e).getCertificate();
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getCertificate", result);
+ return result;
+ }
+
+ public void putCertificate(String alias, Certificate cert)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putCertificate",
+ new Object[] { alias, cert });
+ if (! containsCertificate(alias))
+ {
+ Properties p = new Properties();
+ p.put("alias", fixAlias(alias));
+ add(new CertificateEntry(cert, new Date(), p));
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putCertificate");
+ }
+
+ protected void load(InputStream in, char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "load");
+ if (in.read() != USAGE)
+ throw new MalformedKeyringException("incompatible keyring usage");
+ if (in.read() != PasswordAuthenticatedEntry.TYPE)
+ throw new MalformedKeyringException(
+ "expecting password-authenticated entry tag");
+ DataInputStream dis = new DataInputStream(in);
+ keyring = PasswordAuthenticatedEntry.decode(dis, password);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "load");
+ }
+
+ protected void store(OutputStream out, char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "store");
+ out.write(USAGE);
+ keyring.encode(new DataOutputStream(out), password);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "store");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,162 @@
+/* IKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The top-level interface to a <i>keyring:</i> a file that is used to store
+ * and protect public and private cryptographic keys.
+ * <p>
+ * A <i>keyring</i> is modelled as a mapping of one <i>alias</i> to one or
+ * more <i>entries</i> (optionally of different types).
+ * <p>
+ * See also the sub-interfaces {@link IPublicKeyring} and
+ * {@link IPrivateKeyring} for special types of <i>keyrings</i> --the
+ * difference being in the type of entries they contain.
+ */
+public interface IKeyring
+{
+ /**
+ * Property name for the source of data to load the keyring from. The value
+ * mapped must be a {@link java.io.InputStream}.
+ */
+ public static final String KEYRING_DATA_IN = "gnu.crypto.keyring.data.in";
+
+ /**
+ * Property name for the data sink to store the keyring to. The value mapped
+ * must be a {@link java.io.OutputStream}.
+ */
+ public static final String KEYRING_DATA_OUT = "gun.crypto.keyring.data.out";
+
+ /**
+ * Property name for the keyring's top-level password, used to authenticate
+ * and/or transform the store itself. The mapped value must be a char array.
+ */
+ public static final String KEYRING_PASSWORD = "gnu.crypto.keyring.password";
+
+ /**
+ * Loads a keyring into memory.
+ * <p>
+ * What happens to the current contents of this keyring? are the new ones
+ * merged with the current ones or do they simply replace them?
+ *
+ * @param attributes The attributes that designate the source where the store
+ * is to be loaded from. What happens
+ * @throws IllegalArgumentException If the attributes are inappropriate.
+ * @throws IOException If the keyring file cannot be read.
+ * @throws SecurityException If the given password is incorrect, or if the
+ * top-level authentication or decryption fails.
+ */
+ void load(Map attributes) throws IOException;
+
+ /**
+ * Stores the contents of this keyring to persistent storage as specified by
+ * the designated <code>attributes</code>.
+ *
+ * @param attributes the attributes that define where the contents of this
+ * keyring will be stored.
+ * @throws IOException if an exception occurs during the process.
+ */
+ void store(Map attributes) throws IOException;
+
+ /**
+ * Resets this keyring, clearing all sensitive data. This method always
+ * suceeds.
+ */
+ void reset();
+
+ /**
+ * Returns the number of entries in this keyring.
+ *
+ * @return The number of current entries in this keyring.
+ */
+ int size();
+
+ /**
+ * Returns an {@link Enumeration} of all aliases (instances of {@link String})
+ * in this keyring.
+ *
+ * @return The enumeration of {@link String}s each representing an <i>alias</i>
+ * found in this keyring.
+ */
+ Enumeration aliases();
+
+ /**
+ * Tests whether or not this keyring contains the given alias.
+ *
+ * @param alias The alias to check.
+ * @return true if this keyring contains the alias.
+ */
+ boolean containsAlias(String alias);
+
+ /**
+ * Returns a {@link List} of entries (instances of {@link Entry}) for the
+ * given <code>alias</code>, or <code>null</code> if there no such entry
+ * exists.
+ *
+ * @param alias The alias of the entry(ies) to return.
+ * @return A list of all entries (instances of {@link Entry} that have the
+ * given <code>alias</code>, or <code>null</code> if no one
+ * {@link Entry} can be found with the designated <code>alias</code>.
+ */
+ List get(String alias);
+
+ /**
+ * Adds a designated {@link Entry} to this keyring.
+ * <p>
+ * What happens if there is already an entry with the same alias?
+ *
+ * @param entry The entry to put in this keyring.
+ */
+ void add(Entry entry);
+
+ /**
+ * Removes an entry with the designated <code>alias</code> from this
+ * keyring. Does nothing if there was no such entry.
+ * <p>
+ * What happens if there are more than one?
+ *
+ * @param alias The alias of the entry to remove.
+ */
+ void remove(String alias);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,144 @@
+/* IPrivateKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.security.Key;
+import java.security.PublicKey;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+
+/**
+ * An interface to private, or "personal", keyrings, which contain private
+ * credentials. The contract is that each such entry is known by a unique
+ * <i>alias</i>.
+ * <p>
+ * What about public keys? and certificate-path?
+ */
+public interface IPrivateKeyring
+ extends IKeyring
+{
+ /**
+ * Tests if this keyring contains a private key entry with the given
+ * <code>alias</code>.
+ *
+ * @param alias The alias to check.
+ * @return <code>true</code> if this keyring contains a private key with the
+ * given <code>alias</code>; <code>false</code> otherwise.
+ */
+ boolean containsPrivateKey(String alias);
+
+ /**
+ * Returns the private key with the given <code>alias</code>.
+ *
+ * @param alias The alias of the private key to find.
+ * @param password The password of the private key.
+ * @return The private, or secret, key if one is found; <code>null</code> if
+ * none were found.
+ * @throws UnrecoverableKeyException If the private key could not be
+ * recovered, possibly due to a bad password.
+ */
+ Key getPrivateKey(String alias, char[] password)
+ throws UnrecoverableKeyException;
+
+ /**
+ * Adds a private key to this keyring.
+ *
+ * @param alias The alias of the private key.
+ * @param key The private key.
+ * @param password The password used to protect this private key.
+ */
+ void putPrivateKey(String alias, Key key, char[] password);
+
+ /**
+ * Checks if this keyring contains a public key with the given
+ * <code>alias</code>.
+ *
+ * @param alias The alias to test.
+ * @return <code>true</code> if this keyring contains a public key entry
+ * with the given <code>alias</code>; <code>false</code>
+ * otherwise.
+ */
+ boolean containsPublicKey(String alias);
+
+ /**
+ * Returns the public key with the given <code>alias</code>, or
+ * <code>null</code> if there is no such entry.
+ *
+ * @param alias The alias of the public key to find.
+ * @return The public key; or <code>null</code> if none were found.
+ */
+ PublicKey getPublicKey(String alias);
+
+ /**
+ * Sets a public key entry.
+ *
+ * @param alias The alias for this public key.
+ * @param key The public key.
+ */
+ void putPublicKey(String alias, PublicKey key);
+
+ /**
+ * Checks if this keyring contains a certificate path with the given
+ * <code>alias</code>.
+ *
+ * @param alias The alias to check.
+ * @return <code>true</code> if this keyring contains a certificate path
+ * with the given <code>alias</code>; <code>false</code>
+ * otherwise.
+ */
+ boolean containsCertPath(String alias);
+
+ /**
+ * Returns the certificate path with the given <code>alias</code>, or
+ * <code>null</code> if there is no such entry.
+ *
+ * @param alias The alias of the certificate path to find.
+ * @return The certificate path for the designated <code>alias</code>; or
+ * <code>null</code> if none were found.
+ */
+ Certificate[] getCertPath(String alias);
+
+ /**
+ * Sets a certificate path entry.
+ *
+ * @param alias The alias for this certificate path.
+ * @param path The certificate path.
+ */
+ void putCertPath(String alias, Certificate[] path);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPublicKeyring.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPublicKeyring.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPublicKeyring.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/IPublicKeyring.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,82 @@
+/* IPublicKeyring.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.security.cert.Certificate;
+
+/**
+ * An interface for keyrings that contain trusted (by the owner) public
+ * credentials (incl. certificates).
+ *
+ * @see IKeyring
+ */
+public interface IPublicKeyring
+ extends IKeyring
+{
+ /**
+ * Tests if this keyring contains a certificate entry with the specified
+ * <code>alias</code>.
+ *
+ * @param alias The alias of the certificate to check.
+ * @return <code>true</code> if this keyring contains a certificate entry
+ * that has the given <code>alias</code>; <code>false</code>
+ * otherwise.
+ */
+ boolean containsCertificate(String alias);
+
+ /**
+ * Returns a certificate that has the given <code>alias</code>, or
+ * <code>null</code> if this keyring has no such entry.
+ *
+ * @param alias The alias of the certificate to find.
+ * @return The certificate with the designated <code>alias</code>, or
+ * <code>null</code> if none found.
+ */
+ Certificate getCertificate(String alias);
+
+ /**
+ * Adds a certificate in this keyring, with the given <code>alias</code>.
+ * <p>
+ * What happens if there is already a certificate entry with this alias?
+ *
+ * @param alias The alias of this certificate entry.
+ * @param cert The certificate.
+ */
+ void putCertificate(String alias, Certificate cert);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,55 @@
+/* MalformedKeyringException.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.IOException;
+
+public class MalformedKeyringException
+ extends IOException
+{
+ public MalformedKeyringException()
+ {
+ super();
+ }
+
+ public MalformedKeyringException(String msg)
+ {
+ super(msg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,135 @@
+/* MaskableEnvelopeEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * An envelope entry that can be "masked" -- placed in a state where the
+ * envelope's contents cannot be accessed, due to the envelope not being fully
+ * decoded, for example.
+ */
+public abstract class MaskableEnvelopeEntry
+ extends EnvelopeEntry
+{
+ /** The masked state. */
+ protected boolean masked;
+
+ public MaskableEnvelopeEntry(int type, Properties properties)
+ {
+ super(type, properties);
+ }
+
+ protected MaskableEnvelopeEntry(int type)
+ {
+ super(type);
+ }
+
+ /**
+ * Sets the masked state to the specified value.
+ *
+ * @param masked The new masked state.
+ */
+ protected final void setMasked(boolean masked)
+ {
+ this.masked = masked;
+ }
+
+ /**
+ * Gets the masked state of this object. Certain operations on this object
+ * will fail if it is masked.
+ *
+ * @return The current masked state.
+ */
+ public boolean isMasked()
+ {
+ return masked;
+ }
+
+ public void add(Entry entry)
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ super.add(entry);
+ }
+
+ public boolean containsEntry(Entry entry)
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ return super.containsEntry(entry);
+ }
+
+ public List getEntries()
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ return new ArrayList(entries);
+ }
+
+ public List get(String alias)
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ return super.get(alias);
+ }
+
+ public boolean remove(Entry entry)
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ return super.remove(entry);
+ }
+
+ public boolean remove(String alias)
+ {
+ if (isMasked())
+ throw new IllegalStateException("masked envelope");
+ return super.remove(alias);
+ }
+
+ public String toString()
+ {
+ return new StringBuilder("MaskableEnvelope{")
+ .append(super.toString())
+ .append(", masked=").append(masked)
+ .append("}").toString();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* MeteredInputStream.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+final class MeteredInputStream
+ extends FilterInputStream
+{
+ private int count;
+ private final int limit;
+
+ MeteredInputStream(InputStream in, int limit)
+ {
+ super(in);
+ if (limit < 0)
+ throw new IllegalArgumentException("limit must be nonnegative");
+ this.limit = limit;
+ count = 0;
+ }
+
+ /**
+ * Tests if the number of bytes read has reached the limit.
+ *
+ * @return True if the limit has been reached.
+ */
+ public boolean limitReached()
+ {
+ return count == limit;
+ }
+
+ public int available() throws IOException
+ {
+ return Math.min(in.available(), limit - count);
+ }
+
+ public void close() throws IOException
+ {
+ in.close();
+ }
+
+ public void mark(int readLimit)
+ {
+ }
+
+ public boolean markSupported()
+ {
+ return false;
+ }
+
+ public int read() throws IOException
+ {
+ if (limitReached())
+ return -1;
+ int i = in.read();
+ if (i != -1)
+ count++;
+ return i;
+ }
+
+ public int read(byte[] buf) throws IOException
+ {
+ return read(buf, 0, buf.length);
+ }
+
+ public int read(byte[] buf, int off, int len) throws IOException
+ {
+ if (limitReached())
+ return -1;
+ int i = in.read(buf, off, Math.min(len, limit - count));
+ if (i != -1)
+ count += i;
+ return i;
+ }
+
+ public void reset() throws IOException
+ {
+ }
+
+ public long skip(long len) throws IOException
+ {
+ if (limitReached())
+ return 0L;
+ len = Math.min(len, limit - count);
+ len = in.skip(len);
+ count += (int) len;
+ return len;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,286 @@
+/* PasswordAuthenticatedEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+import gnu.javax.crypto.mac.MacInputStream;
+import gnu.javax.crypto.mac.MacOutputStream;
+import gnu.javax.crypto.prng.IPBE;
+import gnu.javax.crypto.prng.PRNGFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+/**
+ * An entry authenticated with a password-based MAC.
+ */
+public final class PasswordAuthenticatedEntry
+ extends MaskableEnvelopeEntry
+ implements PasswordProtectedEntry, Registry
+{
+ private static final Logger log = Logger.getLogger(PasswordAuthenticatedEntry.class.getName());
+ public static final int TYPE = 3;
+
+ public PasswordAuthenticatedEntry(String mac, int maclen,
+ Properties properties)
+ {
+ super(TYPE, properties);
+ if (mac == null || mac.length() == 0)
+ throw new IllegalArgumentException("no MAC specified");
+ this.properties.put("mac", mac);
+ this.properties.put("maclen", String.valueOf(maclen));
+ setMasked(false);
+ }
+
+ private PasswordAuthenticatedEntry()
+ {
+ super(TYPE);
+ setMasked(true);
+ }
+
+ public static PasswordAuthenticatedEntry decode(DataInputStream in,
+ char[] password)
+ throws IOException
+ {
+ PasswordAuthenticatedEntry entry = new PasswordAuthenticatedEntry();
+ entry.properties.decode(in);
+ IMac mac = entry.getMac(password);
+ int len = in.readInt() - mac.macSize();
+ MeteredInputStream min = new MeteredInputStream(in, len);
+ MacInputStream macin = new MacInputStream(min, mac);
+ DataInputStream in2 = new DataInputStream(macin);
+ entry.setMasked(false);
+ entry.decodeEnvelope(in2);
+ byte[] macValue = new byte[mac.macSize()];
+ in.readFully(macValue);
+ if (! Arrays.equals(macValue, mac.digest()))
+ throw new MalformedKeyringException("MAC verification failed");
+ return entry;
+ }
+
+ public static PasswordAuthenticatedEntry decode(DataInputStream in)
+ throws IOException
+ {
+ PasswordAuthenticatedEntry entry = new PasswordAuthenticatedEntry();
+ entry.defaultDecode(in);
+ if (! entry.properties.containsKey("mac"))
+ throw new MalformedKeyringException("no MAC");
+ if (! entry.properties.containsKey("maclen"))
+ throw new MalformedKeyringException("no MAC length");
+ if (! entry.properties.containsKey("salt"))
+ throw new MalformedKeyringException("no salt");
+ return entry;
+ }
+
+ public void verify(char[] password)
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "verify");
+ if (isMasked() && payload != null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("payload to verify: " + Util.dumpString(payload));
+ long tt = -System.currentTimeMillis();
+ IMac m = null;
+ try
+ {
+ m = getMac(password);
+ }
+ catch (Exception x)
+ {
+ throw new IllegalArgumentException(x.toString(), x);
+ }
+ int limit = payload.length - m.macSize();
+ m.update(payload, 0, limit);
+ byte[] macValue = new byte[m.macSize()];
+ System.arraycopy(payload, payload.length - macValue.length, macValue,
+ 0, macValue.length);
+ if (! Arrays.equals(macValue, m.digest()))
+ throw new IllegalArgumentException("MAC verification failed");
+ setMasked(false);
+ ByteArrayInputStream bais;
+ try
+ {
+ bais = new ByteArrayInputStream(payload, 0, limit);
+ DataInputStream in = new DataInputStream(bais);
+ decodeEnvelope(in);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalArgumentException("malformed keyring fragment");
+ }
+ tt += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ log.fine("Verified in " + tt + "ms.");
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Skip verification; "
+ + (isMasked() ? "null payload" : "unmasked"));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "verify");
+ }
+
+ public void authenticate(char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "authenticate");
+ long tt = -System.currentTimeMillis();
+ long t1 = -System.currentTimeMillis();
+ if (isMasked())
+ throw new IllegalStateException("entry is masked");
+ byte[] salt = new byte[8];
+ PRNG.getInstance().nextBytes(salt);
+ t1 += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ log.fine("-- Generated salt in " + t1 + "ms.");
+ properties.put("salt", Util.toString(salt));
+ IMac m = getMac(password);
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ MacOutputStream macout = new MacOutputStream(bout, m);
+ DataOutputStream out2 = new DataOutputStream(macout);
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry entry = (Entry) it.next();
+ if (Configuration.DEBUG)
+ log.fine("-- About to authenticate one " + entry);
+ t1 = -System.currentTimeMillis();
+ entry.encode(out2);
+ t1 += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ log.fine("-- Authenticated an Entry in " + t1 + "ms.");
+ }
+ bout.write(m.digest());
+ payload = bout.toByteArray();
+ if (Configuration.DEBUG)
+ log.fine("authenticated payload: " + Util.dumpString(payload));
+ setMasked(true);
+ tt += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ {
+ log.fine("Authenticated in " + tt + "ms.");
+ log.exiting(this.getClass().getName(), "authenticate");
+ }
+ }
+
+ public void encode(DataOutputStream out, char[] password) throws IOException
+ {
+ authenticate(password);
+ encode(out);
+ }
+
+ protected void encodePayload(DataOutputStream out) throws IOException
+ {
+ if (payload == null)
+ {
+ log.fine("Null payload: " + this);
+ throw new IllegalStateException("mac not computed");
+ }
+ }
+
+ private IMac getMac(char[] password) throws MalformedKeyringException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getMac");
+ String saltString = properties.get("salt");
+ if (saltString == null)
+ throw new MalformedKeyringException("no salt");
+ byte[] salt = Util.toBytesFromString(saltString);
+ String macAlgorithm = properties.get("mac");
+ IMac mac = MacFactory.getInstance(macAlgorithm);
+ if (mac == null)
+ throw new MalformedKeyringException("no such mac: " + macAlgorithm);
+ String macLenString = properties.get("maclen");
+ if (macLenString == null)
+ throw new MalformedKeyringException("no MAC length");
+ int maclen;
+ try
+ {
+ maclen = Integer.parseInt(macLenString);
+ }
+ catch (NumberFormatException nfe)
+ {
+ throw new MalformedKeyringException("bad MAC length");
+ }
+ HashMap pbAttr = new HashMap();
+ pbAttr.put(IPBE.PASSWORD, password);
+ pbAttr.put(IPBE.SALT, salt);
+ pbAttr.put(IPBE.ITERATION_COUNT, ITERATION_COUNT);
+ IRandom kdf = PRNGFactory.getInstance("PBKDF2-HMAC-SHA");
+ kdf.init(pbAttr);
+ int keylen = mac.macSize();
+ byte[] dk = new byte[keylen];
+ try
+ {
+ kdf.nextBytes(dk, 0, keylen);
+ }
+ catch (LimitReachedException shouldNotHappen)
+ {
+ throw new Error(shouldNotHappen.toString());
+ }
+ HashMap macAttr = new HashMap();
+ macAttr.put(IMac.MAC_KEY_MATERIAL, dk);
+ macAttr.put(IMac.TRUNCATED_SIZE, Integer.valueOf(maclen));
+ try
+ {
+ mac.init(macAttr);
+ }
+ catch (InvalidKeyException shouldNotHappen)
+ {
+ throw new Error(shouldNotHappen.toString());
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getMac");
+ return mac;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,293 @@
+/* PasswordEncryptedEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.mode.IMode;
+import gnu.javax.crypto.mode.ModeFactory;
+import gnu.javax.crypto.pad.IPad;
+import gnu.javax.crypto.pad.PadFactory;
+import gnu.javax.crypto.pad.WrongPaddingException;
+import gnu.javax.crypto.prng.IPBE;
+import gnu.javax.crypto.prng.PRNGFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+/**
+ * An envelope that is encrypted with a password-derived key.
+ */
+public class PasswordEncryptedEntry
+ extends MaskableEnvelopeEntry
+ implements PasswordProtectedEntry, Registry
+{
+ private static final Logger log = Logger.getLogger(PasswordEncryptedEntry.class.getName());
+ public static final int TYPE = 1;
+
+ public PasswordEncryptedEntry(String cipher, String mode, int keylen,
+ Properties properties)
+ {
+ super(TYPE, properties);
+ if ((cipher == null || cipher.length() == 0)
+ || (mode == null || mode.length() == 0))
+ throw new IllegalArgumentException("cipher nor mode can be empty");
+ this.properties.put("cipher", cipher);
+ this.properties.put("mode", mode);
+ this.properties.put("keylen", String.valueOf(keylen));
+ setMasked(false);
+ }
+
+ private PasswordEncryptedEntry()
+ {
+ super(TYPE);
+ setMasked(true);
+ }
+
+ public static PasswordEncryptedEntry decode(DataInputStream in,
+ char[] password)
+ throws IOException
+ {
+ PasswordEncryptedEntry entry = decode(in);
+ try
+ {
+ entry.decrypt(password);
+ }
+ catch (WrongPaddingException wpe)
+ {
+ throw new MalformedKeyringException("wrong padding in decrypted data");
+ }
+ return entry;
+ }
+
+ public static PasswordEncryptedEntry decode(DataInputStream in)
+ throws IOException
+ {
+ PasswordEncryptedEntry entry = new PasswordEncryptedEntry();
+ entry.defaultDecode(in);
+ return entry;
+ }
+
+ public void decrypt(char[] password) throws IllegalArgumentException,
+ WrongPaddingException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decrypt");
+ if (isMasked() && payload != null)
+ {
+ long tt = -System.currentTimeMillis();
+ IMode mode = getMode(password, IMode.DECRYPTION);
+ IPad padding = PadFactory.getInstance("PKCS7");
+ padding.init(mode.currentBlockSize());
+ byte[] buf = new byte[payload.length];
+ int count = 0;
+ while (count + mode.currentBlockSize() <= payload.length)
+ {
+ mode.update(payload, count, buf, count);
+ count += mode.currentBlockSize();
+ }
+ int padlen = padding.unpad(buf, 0, buf.length);
+ setMasked(false);
+ int len = buf.length - padlen;
+ ByteArrayInputStream baos = new ByteArrayInputStream(buf, 0, len);
+ DataInputStream in = new DataInputStream(baos);
+ try
+ {
+ decodeEnvelope(in);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalArgumentException("decryption failed");
+ }
+ tt += System.currentTimeMillis();
+ log.fine("Decrypted in " + tt + "ms.");
+ }
+ else if (Configuration.DEBUG)
+ log.fine("Skip decryption; " + (isMasked() ? "null payload" : "unmasked"));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decrypt");
+ }
+
+ public void encrypt(char[] password) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encrypt", String.valueOf(password));
+ long tt = -System.currentTimeMillis();
+ long t1 = -System.currentTimeMillis();
+ byte[] salt = new byte[8];
+ PRNG.getInstance().nextBytes(salt);
+ t1 += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ log.fine("-- Generated salt in " + t1 + "ms.");
+ properties.put("salt", Util.toString(salt));
+ IMode mode = getMode(password, IMode.ENCRYPTION);
+ IPad pad = PadFactory.getInstance("PKCS7");
+ pad.init(mode.currentBlockSize());
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ DataOutputStream out2 = new DataOutputStream(bout);
+ for (Iterator it = entries.iterator(); it.hasNext();)
+ {
+ Entry entry = (Entry) it.next();
+ if (Configuration.DEBUG)
+ log.fine("-- About to encode one " + entry);
+ t1 = -System.currentTimeMillis();
+ entry.encode(out2);
+ t1 += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ log.fine("-- Encoded an Entry in " + t1 + "ms.");
+ }
+ byte[] plaintext = bout.toByteArray();
+ byte[] padding = pad.pad(plaintext, 0, plaintext.length);
+ payload = new byte[plaintext.length + padding.length];
+ byte[] lastBlock = new byte[mode.currentBlockSize()];
+ int l = mode.currentBlockSize() - padding.length;
+ System.arraycopy(plaintext, plaintext.length - l, lastBlock, 0, l);
+ System.arraycopy(padding, 0, lastBlock, l, padding.length);
+ int count = 0;
+ while (count + mode.currentBlockSize() < plaintext.length)
+ {
+ mode.update(plaintext, count, payload, count);
+ count += mode.currentBlockSize();
+ }
+ mode.update(lastBlock, 0, payload, count);
+ setMasked(true);
+ tt += System.currentTimeMillis();
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encrypted in " + tt + "ms.");
+ log.exiting(this.getClass().getName(), "encrypt");
+ }
+ }
+
+ public void encode(DataOutputStream out, char[] password) throws IOException
+ {
+ encrypt(password);
+ encode(out);
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ if (payload == null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Null payload: " + this);
+ throw new IllegalStateException("not encrypted");
+ }
+ }
+
+ private IMode getMode(char[] password, int state)
+ {
+ String s = properties.get("salt");
+ if (s == null)
+ throw new IllegalArgumentException("no salt");
+ byte[] salt = Util.toBytesFromString(s);
+ IBlockCipher cipher = CipherFactory.getInstance(properties.get("cipher"));
+ if (cipher == null)
+ throw new IllegalArgumentException("no such cipher: "
+ + properties.get("cipher"));
+ int blockSize = cipher.defaultBlockSize();
+ if (properties.containsKey("block-size"))
+ try
+ {
+ blockSize = Integer.parseInt(properties.get("block-size"));
+ }
+ catch (NumberFormatException nfe)
+ {
+ throw new IllegalArgumentException("bad block size: "
+ + nfe.getMessage());
+ }
+ String modeName = properties.get("mode");
+ IMode mode = ModeFactory.getInstance(modeName, cipher, blockSize);
+ if (mode == null)
+ throw new IllegalArgumentException("no such mode: " + modeName);
+ HashMap pbAttr = new HashMap();
+ pbAttr.put(IPBE.PASSWORD, password);
+ pbAttr.put(IPBE.SALT, salt);
+ pbAttr.put(IPBE.ITERATION_COUNT, ITERATION_COUNT);
+ IRandom kdf = PRNGFactory.getInstance("PBKDF2-HMAC-SHA");
+ kdf.init(pbAttr);
+ int keylen = 0;
+ if (! properties.containsKey("keylen"))
+ throw new IllegalArgumentException("no key length");
+ try
+ {
+ keylen = Integer.parseInt(properties.get("keylen"));
+ }
+ catch (NumberFormatException nfe)
+ {
+ }
+ byte[] dk = new byte[keylen];
+ byte[] iv = new byte[blockSize];
+ try
+ {
+ kdf.nextBytes(dk, 0, keylen);
+ kdf.nextBytes(iv, 0, blockSize);
+ }
+ catch (LimitReachedException shouldNotHappen)
+ {
+ throw new Error(shouldNotHappen.toString());
+ }
+ HashMap modeAttr = new HashMap();
+ modeAttr.put(IMode.KEY_MATERIAL, dk);
+ modeAttr.put(IMode.STATE, Integer.valueOf(state));
+ modeAttr.put(IMode.IV, iv);
+ try
+ {
+ mode.init(modeAttr);
+ }
+ catch (InvalidKeyException ike)
+ {
+ throw new IllegalArgumentException(ike.toString());
+ }
+ return mode;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordProtectedEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordProtectedEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordProtectedEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PasswordProtectedEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,57 @@
+/* PasswordProtectedEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+public interface PasswordProtectedEntry
+{
+ /** The iteration count for password-based KDFs. */
+ Integer ITERATION_COUNT = Integer.valueOf(1000);
+
+ /**
+ * Encodes this entry, protected by a password.
+ *
+ * @param out The output stream to encode to.
+ * @param password The password.
+ * @throws IOException If an I/O error occurs.
+ */
+ void encode(DataOutputStream out, char[] password) throws IOException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrimitiveEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrimitiveEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrimitiveEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrimitiveEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* PrimitiveEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.util.Date;
+
+/**
+ * A primitive entry is an entry that contains a single cryptographic entity.
+ */
+public abstract class PrimitiveEntry
+ extends Entry
+{
+ /** The creation date. */
+ protected Date creationDate;
+
+ protected PrimitiveEntry(int type, Date creationDate, Properties properties)
+ {
+ super(type, properties);
+ if (creationDate == null)
+ this.creationDate = new Date();
+ else
+ this.creationDate = (Date) creationDate.clone();
+ if (! this.properties.containsKey("alias")
+ || this.properties.get("alias").length() == 0)
+ throw new IllegalArgumentException("primitive entries MUST have an alias");
+ this.properties.put("creation-date",
+ String.valueOf(this.creationDate.getTime()));
+ }
+
+ protected PrimitiveEntry(int type)
+ {
+ super(type);
+ }
+
+ /**
+ * Returns the alias of this primitive entry.
+ *
+ * @return The alias.
+ */
+ public String getAlias()
+ {
+ return properties.get("alias");
+ }
+
+ /**
+ * Returns the creation date of this primitive entry.
+ *
+ * @return The creation date.
+ */
+ public Date getCreationDate()
+ {
+ return (Date) creationDate.clone();
+ }
+
+ public boolean equals(Object object)
+ {
+ if (! getClass().equals(object.getClass()))
+ return false;
+ return getAlias().equals(((PrimitiveEntry) object).getAlias());
+ }
+
+ protected final void makeCreationDate() throws MalformedKeyringException
+ {
+ String s = properties.get("creation-date");
+ if (s == null)
+ throw new MalformedKeyringException("no creation date");
+ try
+ {
+ creationDate = new Date(Long.parseLong(s));
+ }
+ catch (NumberFormatException nfe)
+ {
+ throw new MalformedKeyringException("invalid creation date");
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrivateKeyEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrivateKeyEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrivateKeyEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PrivateKeyEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,194 @@
+/* PrivateKeyEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.key.IKeyPairCodec;
+import gnu.java.security.key.KeyPairCodecFactory;
+import gnu.java.security.key.dss.DSSPrivateKey;
+import gnu.java.security.key.rsa.GnuRSAPrivateKey;
+import gnu.javax.crypto.key.GnuSecretKey;
+import gnu.javax.crypto.key.dh.GnuDHPrivateKey;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.Key;
+import java.security.KeyFactory;
+import java.security.PrivateKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.Date;
+
+/**
+ * An immutable class representing a private or secret key entry.
+ */
+public final class PrivateKeyEntry
+ extends PrimitiveEntry
+{
+ public static final int TYPE = 7;
+ /** The key. */
+ private Key key;
+
+ /**
+ * Creates a new key entry.
+ *
+ * @param key The key.
+ * @param creationDate The entry creation date.
+ * @param properties The entry properties.
+ * @throws IllegalArgumentException If any parameter is null.
+ */
+ public PrivateKeyEntry(Key key, Date creationDate, Properties properties)
+ {
+ super(TYPE, creationDate, properties);
+ if (key == null)
+ throw new IllegalArgumentException("no private key");
+ if (! (key instanceof PrivateKey) && ! (key instanceof GnuSecretKey))
+ throw new IllegalArgumentException("not a private or secret key");
+ this.key = key;
+ }
+
+ private PrivateKeyEntry()
+ {
+ super(TYPE);
+ }
+
+ public static PrivateKeyEntry decode(DataInputStream in) throws IOException
+ {
+ PrivateKeyEntry entry = new PrivateKeyEntry();
+ entry.defaultDecode(in);
+ String type = entry.properties.get("type");
+ if (type == null)
+ throw new MalformedKeyringException("no key type");
+ if (type.equalsIgnoreCase("RAW-DSS"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
+ entry.key = coder.decodePrivateKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("RAW-RSA"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("rsa");
+ entry.key = coder.decodePrivateKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("RAW-DH"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dh");
+ entry.key = coder.decodePrivateKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("RAW"))
+ entry.key = new GnuSecretKey(entry.payload, null);
+ else if (type.equalsIgnoreCase("PKCS8"))
+ {
+ try
+ {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(entry.payload);
+ entry.key = kf.generatePrivate(ks);
+ }
+ catch (Exception ignored)
+ {
+ }
+ if (entry.key == null)
+ {
+ try
+ {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(entry.payload);
+ entry.key = kf.generatePrivate(ks);
+ }
+ catch (Exception ignored)
+ {
+ }
+ if (entry.key == null)
+ throw new MalformedKeyringException("could not decode PKCS#8 key");
+ }
+ }
+ else
+ throw new MalformedKeyringException("unsupported key type " + type);
+ return entry;
+ }
+
+ /**
+ * Returns this entry's key.
+ *
+ * @return The key.
+ */
+ public Key getKey()
+ {
+ return key;
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ String format = key.getFormat();
+ if (key instanceof DSSPrivateKey)
+ {
+ properties.put("type", "RAW-DSS");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
+ payload = coder.encodePrivateKey((PrivateKey) key);
+ }
+ else if (key instanceof GnuRSAPrivateKey)
+ {
+ properties.put("type", "RAW-RSA");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("rsa");
+ payload = coder.encodePrivateKey((PrivateKey) key);
+ }
+ else if (key instanceof GnuDHPrivateKey)
+ {
+ properties.put("type", "RAW-DH");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dh");
+ payload = coder.encodePrivateKey((PrivateKey) key);
+ }
+ else if (key instanceof GnuSecretKey)
+ {
+ properties.put("type", "RAW");
+ payload = key.getEncoded();
+ }
+ else if (format != null && format.equals("PKCS#8"))
+ {
+ properties.put("type", "PKCS8");
+ payload = key.getEncoded();
+ }
+ else
+ throw new IllegalArgumentException("unsupported private key");
+ }
+
+ public String toString()
+ {
+ return "PrivateKeyEntry{key="
+ + (key == null ? "-" : key.getClass().getName()) + "}";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Properties.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Properties.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Properties.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/Properties.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,203 @@
+/* Properties.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A set of <code>(name => value)</code> pairs used in keyring entries.
+ * Keys and values are simple strings, with the key never being empty and always
+ * treated case-insensitively.
+ */
+public class Properties
+ implements Cloneable
+{
+ private HashMap props;
+
+ /**
+ * Creates a new properties object.
+ */
+ public Properties()
+ {
+ props = new HashMap();
+ }
+
+ /**
+ * Removes all properties from this object.
+ */
+ public void clear()
+ {
+ props.clear();
+ }
+
+ /**
+ * Creates a copy of this properties object.
+ *
+ * @return The copy.
+ */
+ public Object clone()
+ {
+ Properties result = new Properties();
+ result.props.putAll(props);
+ return result;
+ }
+
+ /**
+ * Tests if this object contains a given property name.
+ *
+ * @param key The key to test.
+ * @return True if this object contains the given key.
+ */
+ public boolean containsKey(String key)
+ {
+ if (key == null || key.length() == 0)
+ return false;
+ return props.containsKey(canonicalize(key));
+ }
+
+ /**
+ * Tests if this object contains a given property value.
+ *
+ * @param value The value to test.
+ * @return True if this object contains the given value.
+ */
+ public boolean containsValue(String value)
+ {
+ if (value == null)
+ return false;
+ return props.containsValue(value);
+ }
+
+ /**
+ * Adds a new property to this object.
+ *
+ * @param key The key, which can neither be null nor empty.
+ * @param value The value, which cannot be null.
+ * @return The old value mapped by the key, if any.
+ * @throws IllegalArgumentException If either the key or value parameter is
+ * null, or if the key is empty.
+ */
+ public String put(String key, String value)
+ {
+ if (key == null || value == null || key.length() == 0)
+ throw new IllegalArgumentException("key nor value can be null");
+ return (String) props.put(canonicalize(key), value);
+ }
+
+ /**
+ * Returns the value mapped by the given key, or null if there is no such
+ * mapping.
+ *
+ * @param key
+ */
+ public String get(String key)
+ {
+ if (key == null || key.length() == 0)
+ return null;
+ return (String) props.get(canonicalize(key));
+ }
+
+ /**
+ * Removes a key and its value from this object.
+ *
+ * @param key The key of the property to remove.
+ * @return The old value mapped by the key, if any.
+ */
+ public String remove(String key)
+ {
+ if (key == null || key.length() == 0)
+ return null;
+ return (String) props.remove(canonicalize(key));
+ }
+
+ /**
+ * Decodes a set of properties from the given input stream.
+ *
+ * @param in The input stream.
+ * @throws IOException If an I/O error occurs.
+ */
+ public void decode(DataInputStream in) throws IOException
+ {
+ int len = in.readInt();
+ MeteredInputStream min = new MeteredInputStream(in, len);
+ DataInputStream in2 = new DataInputStream(min);
+ while (! min.limitReached())
+ {
+ String name = in2.readUTF();
+ String value = in2.readUTF();
+ put(name, value);
+ }
+ }
+
+ /**
+ * Encodes this set of properties to the given output stream.
+ *
+ * @param out The output stream to encode to.
+ * @throws IOException If an I/O error occurs.
+ */
+ public void encode(DataOutputStream out) throws IOException
+ {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ DataOutputStream out2 = new DataOutputStream(buf);
+ for (Iterator it = props.entrySet().iterator(); it.hasNext();)
+ {
+ Map.Entry entry = (Map.Entry) it.next();
+ out2.writeUTF((String) entry.getKey());
+ out2.writeUTF((String) entry.getValue());
+ }
+ out.writeInt(buf.size());
+ buf.writeTo(out);
+ }
+
+ public String toString()
+ {
+ return props.toString();
+ }
+
+ private String canonicalize(String key)
+ {
+ return key.toLowerCase();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,162 @@
+/* PublicKeyEntry.java --
+ Copyright (C) 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.javax.crypto.keyring;
+
+import gnu.java.security.key.IKeyPairCodec;
+import gnu.java.security.key.KeyPairCodecFactory;
+import gnu.java.security.key.dss.DSSPublicKey;
+import gnu.java.security.key.rsa.GnuRSAPublicKey;
+import gnu.javax.crypto.key.dh.GnuDHPublicKey;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.KeyFactory;
+import java.security.PublicKey;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Date;
+
+public final class PublicKeyEntry
+ extends PrimitiveEntry
+{
+ public static final int TYPE = 6;
+ private PublicKey key;
+
+ public PublicKeyEntry(PublicKey key, Date creationDate, Properties properties)
+ {
+ super(TYPE, creationDate, properties);
+ if (key == null)
+ throw new IllegalArgumentException("no key specified");
+ this.key = key;
+ }
+
+ private PublicKeyEntry()
+ {
+ super(TYPE);
+ }
+
+ public static PublicKeyEntry decode(DataInputStream in) throws IOException
+ {
+ PublicKeyEntry entry = new PublicKeyEntry();
+ entry.defaultDecode(in);
+ String type = entry.properties.get("type");
+ if (type == null)
+ throw new MalformedKeyringException("no key type");
+ if (type.equalsIgnoreCase("RAW-DSS"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
+ entry.key = coder.decodePublicKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("RAW-RSA"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("rsa");
+ entry.key = coder.decodePublicKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("RAW-DH"))
+ {
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dh");
+ entry.key = coder.decodePublicKey(entry.payload);
+ }
+ else if (type.equalsIgnoreCase("X.509"))
+ {
+ try
+ {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ entry.key = kf.generatePublic(new X509EncodedKeySpec(entry.payload));
+ }
+ catch (Exception x)
+ {
+ }
+ if (entry.key == null)
+ {
+ try
+ {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ entry.key = kf.generatePublic(new X509EncodedKeySpec(entry.payload));
+ }
+ catch (Exception x)
+ {
+ }
+ if (entry.key == null)
+ throw new MalformedKeyringException("could not decode X.509 key");
+ }
+ }
+ else
+ throw new MalformedKeyringException("unsupported public key type: " + type);
+ return entry;
+ }
+
+ /**
+ * Returns the public key.
+ *
+ * @return The public key.
+ */
+ public PublicKey getKey()
+ {
+ return key;
+ }
+
+ protected void encodePayload() throws IOException
+ {
+ if (key instanceof DSSPublicKey)
+ {
+ properties.put("type", "RAW-DSS");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
+ payload = coder.encodePublicKey(key);
+ }
+ else if (key instanceof GnuRSAPublicKey)
+ {
+ properties.put("type", "RAW-RSA");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("rsa");
+ payload = coder.encodePublicKey(key);
+ }
+ else if (key instanceof GnuDHPublicKey)
+ {
+ properties.put("type", "RAW-DH");
+ IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dh");
+ payload = coder.encodePublicKey(key);
+ }
+ else if (key.getFormat() != null && key.getFormat().equals("X.509"))
+ {
+ properties.put("type", "X.509");
+ payload = key.getEncoded();
+ }
+ else
+ throw new IllegalArgumentException("cannot encode public key");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,168 @@
+/* AESWrap.java -- An implementation of RFC-3394 AES Key Wrap Algorithm
+ 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.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.cipher.Rijndael;
+
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The GNU implementation of the AES Key Wrap Algorithm as described in [1].
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://csrc.nist.gov/encryption/kms/key-wrap.pdf"></a>.</li>
+ * <li><a href="http://www.rfc-archive.org/getrfc.php?rfc=3394">Advanced
+ * Encryption Standard (AES) Key Wrap Algorithm</a>.</li>
+ * <li><a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption Syntax and
+ * Processing</a>.</li>
+ * </ol>
+ */
+public class AESKeyWrap
+ extends BaseKeyWrappingAlgorithm
+{
+ private static final byte[] DEFAULT_IV = new byte[] {
+ (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6,
+ (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6 };
+
+ private Rijndael aes;
+ private byte[] iv;
+
+ public AESKeyWrap()
+ {
+ super(Registry.AES_KWA);
+
+ aes = new Rijndael();
+ }
+
+ protected void engineInit(Map attributes) throws InvalidKeyException
+ {
+ Map cipherAttributes = new HashMap();
+ cipherAttributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(16));
+ cipherAttributes.put(IBlockCipher.KEY_MATERIAL,
+ attributes.get(KEY_ENCRYPTION_KEY_MATERIAL));
+ aes.reset();
+ aes.init(cipherAttributes);
+ byte[] initialValue = (byte[]) attributes.get(INITIAL_VALUE);
+ iv = initialValue == null ? DEFAULT_IV : (byte[]) initialValue.clone();
+ }
+
+ protected byte[] engineWrap(byte[] in, int inOffset, int length)
+ {
+ // TODO: handle input length which is not a multiple of 8 as suggested by
+ // section 2.2.3.2 of RFC-3394
+ if (length % 8 != 0)
+ throw new IllegalArgumentException("Input length MUST be a multiple of 8");
+ int n = length / 8;
+ // output is always one block larger than input
+ byte[] result = new byte[length + 8];
+
+ // 1. init variables: we'll use out buffer for our work buffer;
+ // A will be the first block in out, while R will be the rest
+ System.arraycopy(iv, 0, result, 0, 8);
+ System.arraycopy(in, inOffset, result, 8, length);
+ byte[] B = new byte[2 * 8];
+ // 2. compute intermediate values
+ long t;
+ for (int j = 0; j < 6; j++)
+ for (int i = 1; i <= n; i++)
+ {
+ System.arraycopy(result, 0, B, 0, 8);
+ System.arraycopy(result, i * 8, B, 8, 8);
+ aes.encryptBlock(B, 0, B, 0);
+ t = (n * j) + i;
+ result[0] = (byte)(B[0] ^ (t >>> 56));
+ result[1] = (byte)(B[1] ^ (t >>> 48));
+ result[2] = (byte)(B[2] ^ (t >>> 40));
+ result[3] = (byte)(B[3] ^ (t >>> 32));
+ result[4] = (byte)(B[4] ^ (t >>> 24));
+ result[5] = (byte)(B[5] ^ (t >>> 16));
+ result[6] = (byte)(B[6] ^ (t >>> 8));
+ result[7] = (byte)(B[7] ^ t );
+ System.arraycopy(B, 8, result, i * 8, 8);
+ }
+ return result;
+ }
+
+ protected byte[] engineUnwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException
+ {
+ // TODO: handle input length which is not a multiple of 8 as suggested by
+ // section 2.2.3.2 of RFC-3394
+ if (length % 8 != 0)
+ throw new IllegalArgumentException("Input length MUST be a multiple of 8");
+ // output is always one block shorter than input
+ byte[] result = new byte[length - 8];
+
+ // 1. init variables: we'll use out buffer for our R work buffer
+ byte[] A = new byte[8];
+ System.arraycopy(in, inOffset, A, 0, 8);
+ System.arraycopy(in, inOffset + 8, result, 0, result.length);
+ byte[] B = new byte[2 * 8];
+ // 2. compute intermediate values
+ int n = length / 8 - 1;
+ long t;
+ for (int j = 5; j >= 0; j--)
+ for (int i = n; i >= 1; i--)
+ {
+ t = (n * j) + i;
+ B[0] = (byte)(A[0] ^ (t >>> 56));
+ B[1] = (byte)(A[1] ^ (t >>> 48));
+ B[2] = (byte)(A[2] ^ (t >>> 40));
+ B[3] = (byte)(A[3] ^ (t >>> 32));
+ B[4] = (byte)(A[4] ^ (t >>> 24));
+ B[5] = (byte)(A[5] ^ (t >>> 16));
+ B[6] = (byte)(A[6] ^ (t >>> 8));
+ B[7] = (byte)(A[7] ^ t );
+ System.arraycopy(result, (i - 1) * 8, B, 8, 8);
+ aes.decryptBlock(B, 0, B, 0);
+ System.arraycopy(B, 0, A, 0, 8);
+ System.arraycopy(B, 8, result, (i - 1) * 8, 8);
+ }
+ if (! Arrays.equals(A, iv))
+ throw new KeyUnwrappingException();
+
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,145 @@
+/* BaseKeyWrappingAlgorithm.java -- FIXME: briefly describe file purpose
+ 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.javax.crypto.kwa;
+
+import gnu.java.security.util.PRNG;
+
+import java.security.InvalidKeyException;
+import java.util.Collections;
+import java.util.Map;
+
+import javax.crypto.ShortBufferException;
+
+/**
+ * A base class to facilitate implementation of concrete Key Wrapping
+ * Algorithms.
+ */
+public abstract class BaseKeyWrappingAlgorithm
+ implements IKeyWrappingAlgorithm
+{
+ /** The canonical name of the key wrapping algorithm. */
+ protected String name;
+ /** A source of randomness if/when needed by concrete implementations. */
+ private PRNG prng;
+
+ /**
+ * Protected constructor.
+ *
+ * @param name the key wrapping algorithm canonical name.
+ */
+ protected BaseKeyWrappingAlgorithm(String name)
+ {
+ super();
+ }
+
+ public String name()
+ {
+ return this.name;
+ }
+
+ public void init(Map attributes) throws InvalidKeyException
+ {
+ if (attributes == null)
+ attributes = Collections.EMPTY_MAP;
+
+ engineInit(attributes);
+ }
+
+ public int wrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException
+ {
+ if (outOffset < 0)
+ throw new IllegalArgumentException("Output offset MUST NOT be negative");
+ byte[] result = wrap(in, inOffset, length);
+ if (outOffset + result.length > out.length)
+ throw new ShortBufferException();
+ System.arraycopy(result, 0, out, outOffset, result.length);
+ return result.length;
+ }
+
+ public byte[] wrap(byte[] in, int inOffset, int length)
+ {
+ if (inOffset < 0)
+ throw new IllegalArgumentException("Input offset MUST NOT be negative");
+ if (length < 0)
+ throw new IllegalArgumentException("Input length MUST NOT be negative");
+
+ return engineWrap(in, inOffset, length);
+ }
+
+ public int unwrap(byte[] in, int inOffset, int length,
+ byte[] out, int outOffset)
+ throws ShortBufferException, KeyUnwrappingException
+ {
+ if (outOffset < 0)
+ throw new IllegalArgumentException("Output offset MUST NOT be negative");
+ byte[] result = engineUnwrap(in, inOffset, length);
+ if (outOffset + result.length > out.length)
+ throw new ShortBufferException();
+ System.arraycopy(result, 0, out, outOffset, result.length);
+ return result.length;
+ }
+
+ public byte[] unwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException
+ {
+ if (inOffset < 0)
+ throw new IllegalArgumentException("Input offset MUST NOT be negative");
+ if (length < 0)
+ throw new IllegalArgumentException("Input length MUST NOT be negative");
+
+ return engineUnwrap(in, inOffset, length);
+ }
+
+ protected abstract void engineInit(Map attributes) throws InvalidKeyException;
+
+ protected abstract byte[] engineWrap(byte[] in, int inOffset, int length);
+
+ protected abstract byte[] engineUnwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException;
+
+ /** @return a strong pseudo-random number generator if/when needed. */
+ protected PRNG getDefaultPRNG()
+ {
+ if (prng == null)
+ prng = PRNG.getInstance();
+
+ return prng;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,160 @@
+/* IKeyWrappingAlgorithm.java -- FIXME: briefly describe file purpose
+ 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.javax.crypto.kwa;
+
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.util.Map;
+
+import javax.crypto.ShortBufferException;
+
+/**
+ * Constants and visible methods available to all GNU Key Wrapping Algorithm
+ * implementations.
+ */
+public interface IKeyWrappingAlgorithm
+{
+ /**
+ * Name of the property, in the attributes map, that references the Key
+ * Wrapping Algorithm KEK (Key Encryption Key) material. The object referenced
+ * by this property is a byte array containing the keying material for the
+ * underlying block cipher.
+ */
+ String KEY_ENCRYPTION_KEY_MATERIAL = "gnu.crypto.kwa.kek";
+ /**
+ * Name of the property, in the attributes map, that references the Initial
+ * Value (IV) material. The object referenced by this property is a byte array
+ * containing the initial integrity check register value.
+ */
+ String INITIAL_VALUE = "gnu.crypto.kwa.iv";
+ /**
+ * Property name of an optional {@link SecureRandom} instance to use. The
+ * default is to use a {@link gnu.java.security.util.PRNG} instance.
+ */
+ String SOURCE_OF_RANDOMNESS = "gnu.crypto.kwa.prng";
+
+ /**
+ * Returns the canonical name of this Key Wrapping Algorithm.
+ *
+ * @return the canonical name of this Key Wrapping Algorithm.
+ */
+ String name();
+
+ /**
+ * Initializes this instance with the designated algorithm specific
+ * attributes.
+ *
+ * @param attributes a map of name-to-value pairs the Key Wrapping Algorithm
+ * must use for its setup.
+ * @throws InvalidKeyException if an exception is encountered while seting up
+ * the Key Wrapping Algorithm keying material (KEK).
+ */
+ void init(Map attributes) throws InvalidKeyException;
+
+ /**
+ * Wraps the designated plain text bytes.
+ *
+ * @param in the input byte array containing the plain text.
+ * @param inOffset the offset into <code>in</code> where the first byte of
+ * the plain text (key material) to wrap is located.
+ * @param length the number of bytes to wrap.
+ * @param out the output byte array where the wrapped key material will be
+ * stored.
+ * @param outOffset the offset into <code>out</code> of the first wrapped
+ * byte.
+ * @return the number of bytes of the wrapped key material; i.e. the length,
+ * in <code>out</code>, starting from <code>outOffset</code>
+ * where the cipher text (wrapped key material) are stored.
+ * @throws ShortBufferException if the output buffer is not long enough to
+ * accomodate the number of bytes resulting from wrapping the plain
+ * text.
+ */
+ int wrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException;
+
+ /**
+ * Wraps the designated plain text bytes.
+ *
+ * @param in the input byte array containing the plain text.
+ * @param inOffset the offset into <code>in</code> where the first byte of
+ * the plain text (key material) to wrap is located.
+ * @param length the number of bytes to wrap.
+ * @return a newly allocated byte array containing the cipher text.
+ */
+ byte[] wrap(byte[] in, int inOffset, int length);
+
+ /**
+ * Unwraps the designated cipher text bytes.
+ *
+ * @param in the input byte array containing the cipher text.
+ * @param inOffset the offset into <code>in</code> where the first byte of
+ * the cipher text (already wrapped key material) to unwrap is
+ * located.
+ * @param length the number of bytes to unwrap.
+ * @param out the output byte array where the unwrapped key material will be
+ * stored.
+ * @param outOffset the offset into <code>out</code> of the first unwrapped
+ * byte.
+ * @return the number of bytes of the unwrapped key material; i.e. the length,
+ * in <code>out</code>, starting from <code>outOffset</code>
+ * where the plain text (unwrapped key material) are stored.
+ * @throws ShortBufferException if the output buffer is not long enough to
+ * accomodate the number of bytes resulting from unwrapping the
+ * cipher text.
+ * @throws KeyUnwrappingException if after unwrapping the cipher text, the
+ * bytes at the begining did not match the initial value.
+ */
+ int unwrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException, KeyUnwrappingException;
+
+ /**
+ * Unwraps the designated cipher text bytes.
+ *
+ * @param in the input byte array containing the cipher text.
+ * @param inOffset the offset into <code>in</code> where the first byte of
+ * the cipher text (already wrapped key material) to unwrap is
+ * located.
+ * @param length the number of bytes to unwrap.
+ * @return a newly allocated byte array containing the plain text.
+ * @throws KeyUnwrappingException if after unwrapping the cipher text, the
+ * bytes at the begining did not match the initial value.
+ */
+ byte[] unwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,67 @@
+/* KeyUnwrappingException.java -- FIXME: briefly describe file purpose
+ 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.javax.crypto.kwa;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * A checked security exception to denote an unexpected problem while unwrapping
+ * key material with a Key Wrapping Algorithm.
+ */
+public class KeyUnwrappingException
+ extends GeneralSecurityException
+{
+ /**
+ * Create a new instance with no descriptive error message.
+ */
+ public KeyUnwrappingException()
+ {
+ super();
+ }
+
+ /**
+ * Create a new instance with a descriptive error message.
+ *
+ * @param msg the descriptive error message
+ */
+ public KeyUnwrappingException(String msg)
+ {
+ super(msg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,110 @@
+/* KeyWrappingAlgorithmFactory.java -- FIXME: briefly describe file purpose
+ 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.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A Factory class for the Key Wrapping Algorithm implementations.
+ */
+public class KeyWrappingAlgorithmFactory
+{
+ /** Names of Key Wrapping Algorihms cached for speed. */
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private KeyWrappingAlgorithmFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a key-wrapping algorithm given its name.
+ *
+ * @param name the case-insensitive name of the key-wrapping algorithm.
+ * @return an instance of the designated key-wrapping algorithm, or
+ * <code>null</code> if none was found.
+ * @exception InternalError if the implementation does not pass its self-test.
+ */
+ public static final IKeyWrappingAlgorithm getInstance(String name)
+ {
+ if (name == null)
+ return null;
+ name = name.trim();
+ IKeyWrappingAlgorithm result = null;
+ if (name.equalsIgnoreCase(Registry.AES_KWA)
+ || name.equalsIgnoreCase(Registry.AES128_KWA)
+ || name.equalsIgnoreCase(Registry.AES192_KWA)
+ || name.equalsIgnoreCase(Registry.AES256_KWA)
+ || name.equalsIgnoreCase(Registry.RIJNDAEL_KWA))
+ result = new AESKeyWrap();
+ else if (name.equalsIgnoreCase(Registry.TRIPLEDES_KWA)
+ || name.equalsIgnoreCase(Registry.DESEDE_KWA))
+ result = new TripleDESKeyWrap();
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of key wrapping algorithm names supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of key wrapping algorithm names (Strings).
+ */
+ public static synchronized final Set getNames()
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(Registry.AES_KWA);
+ hs.add(Registry.AES128_KWA);
+ hs.add(Registry.AES192_KWA);
+ hs.add(Registry.AES256_KWA);
+ hs.add(Registry.RIJNDAEL_KWA);
+ hs.add(Registry.TRIPLEDES_KWA);
+ hs.add(Registry.DESEDE_KWA);
+ names = Collections.unmodifiableSet(hs);
+ }
+ return names;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,292 @@
+/* TripleDESKeyWrap.java -- FIXME: briefly describe file purpose
+ 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.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.Sha160;
+import gnu.javax.crypto.assembly.Assembly;
+import gnu.javax.crypto.assembly.Cascade;
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.assembly.Stage;
+import gnu.javax.crypto.assembly.Transformer;
+import gnu.javax.crypto.assembly.TransformerException;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.cipher.TripleDES;
+import gnu.javax.crypto.mode.IMode;
+import gnu.javax.crypto.mode.ModeFactory;
+
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The GNU implementation of the Triple DES Key Wrap Algorithm as described in
+ * [1].
+ * <p>
+ * <b>IMPORTANT</b>: This class is NOT thread safe.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.rfc-archive.org/getrfc.php?rfc=3217">Triple-DES and
+ * RC2 Key Wrapping</a>.</li>
+ * <li><a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption Syntax and
+ * Processing</a>.</li>
+ * </ol>
+ */
+public class TripleDESKeyWrap
+ extends BaseKeyWrappingAlgorithm
+{
+ private static final byte[] DEFAULT_IV = new byte[] {
+ (byte) 0x4A, (byte) 0xDD, (byte) 0xA2, (byte) 0x2C,
+ (byte) 0x79, (byte) 0xE8, (byte) 0x21, (byte) 0x05 };
+
+ private Assembly asm;
+ private HashMap asmAttributes = new HashMap();
+ private HashMap modeAttributes = new HashMap();
+ private Sha160 sha = new Sha160();
+ private SecureRandom rnd;
+
+ public TripleDESKeyWrap()
+ {
+ super(Registry.TRIPLEDES_KWA);
+ }
+
+ protected void engineInit(Map attributes) throws InvalidKeyException
+ {
+ rnd = (SecureRandom) attributes.get(IKeyWrappingAlgorithm.SOURCE_OF_RANDOMNESS);
+ IMode des3CBC = ModeFactory.getInstance(Registry.CBC_MODE, new TripleDES(), 8);
+ Stage des3CBCStage = Stage.getInstance(des3CBC, Direction.FORWARD);
+ Cascade cascade = new Cascade();
+ Object modeNdx = cascade.append(des3CBCStage);
+
+ asmAttributes.put(modeNdx, modeAttributes);
+
+ asm = new Assembly();
+ asm.addPreTransformer(Transformer.getCascadeTransformer(cascade));
+
+ modeAttributes.put(IBlockCipher.KEY_MATERIAL,
+ attributes.get(KEY_ENCRYPTION_KEY_MATERIAL));
+ asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
+ }
+
+ protected byte[] engineWrap(byte[] in, int inOffset, int length)
+ {
+ // The same key wrap algorithm is used for both Two-key Triple-DES and
+ // Three-key Triple-DES keys. When a Two-key Triple-DES key is to be
+ // wrapped, a third DES key with the same value as the first DES key is
+ // created. Thus, all wrapped Triple-DES keys include three DES keys.
+ if (length != 16 && length != 24)
+ throw new IllegalArgumentException("Only 2- and 3-key Triple DES keys are alowed");
+
+ byte[] CEK = new byte[24];
+ if (length == 16)
+ {
+ System.arraycopy(in, inOffset, CEK, 0, 16);
+ System.arraycopy(in, inOffset, CEK, 16, 8);
+ }
+ else
+ System.arraycopy(in, inOffset, CEK, 0, 24);
+
+ // TODO: check for the following:
+ // However, a Two-key Triple-DES key MUST NOT be used to wrap a Three-
+ // key Triple-DES key that is comprised of three unique DES keys.
+
+ // 1. Set odd parity for each of the DES key octets comprising the
+ // Three-Key Triple-DES key that is to be wrapped, call the result
+ // CEK.
+ TripleDES.adjustParity(CEK, 0);
+
+ // 2. Compute an 8 octet key checksum value on CEK as described above in
+ // Section 2, call the result ICV.
+ sha.update(CEK);
+ byte[] hash = sha.digest();
+ byte[] ICV = new byte[8];
+ System.arraycopy(hash, 0, ICV, 0, 8);
+
+ // 3. Let CEKICV = CEK || ICV.
+ byte[] CEKICV = new byte[CEK.length + ICV.length];
+ System.arraycopy(CEK, 0, CEKICV, 0, CEK.length);
+ System.arraycopy(ICV, 0, CEKICV, CEK.length, ICV.length);
+
+ // 4. Generate 8 octets at random, call the result IV.
+ byte[] IV = new byte[8];
+ nextRandomBytes(IV);
+
+ // 5. Encrypt CEKICV in CBC mode using the key-encryption key. Use the
+ // random value generated in the previous step as the initialization
+ // vector (IV). Call the ciphertext TEMP1.
+ modeAttributes.put(IMode.IV, IV);
+ asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
+ byte[] TEMP1;
+ try
+ {
+ asm.init(asmAttributes);
+ TEMP1 = asm.lastUpdate(CEKICV);
+ }
+ catch (TransformerException x)
+ {
+ throw new RuntimeException(x);
+ }
+
+ // 6. Let TEMP2 = IV || TEMP1.
+ byte[] TEMP2 = new byte[IV.length + TEMP1.length];
+ System.arraycopy(IV, 0, TEMP2, 0, IV.length);
+ System.arraycopy(TEMP1, 0, TEMP2, IV.length, TEMP1.length);
+
+ // 7. Reverse the order of the octets in TEMP2. That is, the most
+ // significant (first) octet is swapped with the least significant
+ // (last) octet, and so on. Call the result TEMP3.
+ byte[] TEMP3 = new byte[TEMP2.length];
+ for (int i = 0, j = TEMP2.length - 1; i < TEMP2.length; i++, j--)
+ TEMP3[j] = TEMP2[i];
+
+ // 8. Encrypt TEMP3 in CBC mode using the key-encryption key. Use an
+ // initialization vector (IV) of 0x4adda22c79e82105. The ciphertext
+ // is 40 octets long.
+ modeAttributes.put(IMode.IV, DEFAULT_IV);
+ asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
+ byte[] result;
+ try
+ {
+ asm.init(asmAttributes);
+ result = asm.lastUpdate(TEMP3);
+ }
+ catch (TransformerException x)
+ {
+ throw new RuntimeException(x);
+ }
+ return result;
+ }
+
+ protected byte[] engineUnwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException
+ {
+ // 1. If the wrapped key is not 40 octets, then error.
+ if (length != 40)
+ throw new IllegalArgumentException("length MUST be 40");
+
+ // 2. Decrypt the wrapped key in CBC mode using the key-encryption key.
+ // Use an initialization vector (IV) of 0x4adda22c79e82105. Call the
+ // output TEMP3.
+ modeAttributes.put(IMode.IV, DEFAULT_IV);
+ asmAttributes.put(Assembly.DIRECTION, Direction.REVERSED);
+ byte[] TEMP3;
+ try
+ {
+ asm.init(asmAttributes);
+ TEMP3 = asm.lastUpdate(in, inOffset, 40);
+ }
+ catch (TransformerException x)
+ {
+ throw new RuntimeException(x);
+ }
+
+ // 3. Reverse the order of the octets in TEMP3. That is, the most
+ // significant (first) octet is swapped with the least significant
+ // (last) octet, and so on. Call the result TEMP2.
+ byte[] TEMP2 = new byte[40];
+ for (int i = 0, j = 40 - 1; i < 40; i++, j--)
+ TEMP2[j] = TEMP3[i];
+
+ // 4. Decompose TEMP2 into IV and TEMP1. IV is the most significant
+ // (first) 8 octets, and TEMP1 is the least significant (last) 32
+ // octets.
+ byte[] IV = new byte[8];
+ byte[] TEMP1 = new byte[32];
+ System.arraycopy(TEMP2, 0, IV, 0, 8);
+ System.arraycopy(TEMP2, 8, TEMP1, 0, 32);
+
+ // 5. Decrypt TEMP1 in CBC mode using the key-encryption key. Use the
+ // IV value from the previous step as the initialization vector.
+ // Call the ciphertext CEKICV.
+ modeAttributes.put(IMode.IV, IV);
+ asmAttributes.put(Assembly.DIRECTION, Direction.REVERSED);
+ byte[] CEKICV;
+ try
+ {
+ asm.init(asmAttributes);
+ CEKICV = asm.lastUpdate(TEMP1, 0, 32);
+ }
+ catch (TransformerException x)
+ {
+ throw new RuntimeException(x);
+ }
+
+ // 6. Decompose CEKICV into CEK and ICV. CEK is the most significant
+ // (first) 24 octets, and ICV is the least significant (last) 8
+ // octets.
+ byte[] CEK = new byte[24];
+ byte[] ICV = new byte[8];
+ System.arraycopy(CEKICV, 0, CEK, 0, 24);
+ System.arraycopy(CEKICV, 24, ICV, 0, 8);
+
+ // 7. Compute an 8 octet key checksum value on CEK as described above in
+ // Section 2. If the computed key checksum value does not match the
+ // decrypted key checksum value, ICV, then error.
+ sha.update(CEK);
+ byte[] hash = sha.digest();
+ byte[] computedICV = new byte[8];
+ System.arraycopy(hash, 0, computedICV, 0, 8);
+ if (! Arrays.equals(ICV, computedICV))
+ throw new KeyUnwrappingException("ICV and computed ICV MUST match");
+
+ // 8. Check for odd parity each of the DES key octets comprising CEK.
+ // If parity is incorrect, then error.
+ if (! TripleDES.isParityAdjusted(CEK, 0))
+ throw new KeyUnwrappingException("Triple-DES key parity MUST be adjusted");
+
+ // 9. Use CEK as a Triple-DES key.
+ return CEK;
+ }
+
+ /**
+ * Fills the designated byte array with random data.
+ *
+ * @param buffer the byte array to fill with random data.
+ */
+ private void nextRandomBytes(byte[] buffer)
+ {
+ if (rnd != null)
+ rnd.nextBytes(buffer);
+ else
+ getDefaultPRNG().nextBytes(buffer);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/BaseMac.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/BaseMac.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/BaseMac.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/BaseMac.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* BaseMac.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mac;
+
+import gnu.java.security.hash.IMessageDigest;
+
+import java.security.InvalidKeyException;
+import java.util.Map;
+
+/**
+ * A base abstract class to facilitate <i>MAC</i> (Message Authentication Code)
+ * implementations.
+ */
+public abstract class BaseMac
+ implements IMac
+{
+ /** The canonical name prefix of the <i>MAC</i>. */
+ protected String name;
+ /** Reference to the underlying hash algorithm instance. */
+ protected IMessageDigest underlyingHash;
+ /** The length of the truncated output in bytes. */
+ protected int truncatedSize;
+
+ /**
+ * Trivial constructor for use by concrete subclasses.
+ *
+ * @param name the canonical name of this instance.
+ */
+ protected BaseMac(String name)
+ {
+ super();
+
+ this.name = name;
+ }
+
+ /**
+ * Trivial constructor for use by concrete subclasses.
+ *
+ * @param name the canonical name of this instance.
+ * @param underlyingHash the underlying message digest algorithm instance.
+ */
+ protected BaseMac(String name, IMessageDigest underlyingHash)
+ {
+ this(name);
+
+ if (underlyingHash != null)
+ truncatedSize = underlyingHash.hashSize();
+ this.underlyingHash = underlyingHash;
+ }
+
+ public String name()
+ {
+ return name;
+ }
+
+ public int macSize()
+ {
+ return truncatedSize;
+ }
+
+ public void update(byte b)
+ {
+ underlyingHash.update(b);
+ }
+
+ public void update(byte[] b, int offset, int len)
+ {
+ underlyingHash.update(b, offset, len);
+ }
+
+ public void reset()
+ {
+ underlyingHash.reset();
+ }
+
+ public Object clone() throws CloneNotSupportedException
+ {
+ BaseMac result = (BaseMac) super.clone();
+ if (this.underlyingHash != null)
+ result.underlyingHash = (IMessageDigest) this.underlyingHash.clone();
+
+ return result;
+ }
+
+ public abstract void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException;
+
+ public abstract byte[] digest();
+
+ public abstract boolean selfTest();
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMac.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMac.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMac.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMac.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,263 @@
+/* HMac.java --
+ 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.javax.crypto.mac;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.hash.MD5;
+import gnu.java.security.util.Util;
+
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The implementation of the <i>HMAC</i> (Keyed-Hash Message Authentication
+ * Code).
+ * <p>
+ * <i>HMAC</i> can be used in combination with any iterated cryptographic hash
+ * function. <i>HMAC</i> also uses a <i>secret key</i> for calculation and
+ * verification of the message authentication values. The main goals behind this
+ * construction are:
+ * <ul>
+ * <li>To use, without modifications, available hash functions. In particular,
+ * hash functions that perform well in software, and for which code is freely
+ * and widely available.</li>
+ * <li>To preserve the original performance of the hash function without
+ * incurring a significant degradation.</li>
+ * <li>To use and handle keys in a simple way.</li>
+ * <li>To have a well understood cryptographic analysis of the strength of the
+ * authentication mechanism based on reasonable assumptions on the underlying
+ * hash function.</li>
+ * <li>To allow for easy replaceability of the underlying hash function in case
+ * that faster or more secure hash functions are found or required.</li>
+ * </ul>
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc-2104.txt">RFC 2104</a>HMAC:
+ * Keyed-Hashing for Message Authentication.<br>
+ * H. Krawczyk, M. Bellare, and R. Canetti.</li>
+ * </ol>
+ */
+public class HMac
+ extends BaseMac
+ implements Cloneable
+{
+ public static final String USE_WITH_PKCS5_V2 = "gnu.crypto.hmac.pkcs5";
+ private static final byte IPAD_BYTE = 0x36;
+ private static final byte OPAD_BYTE = 0x5C;
+ /** caches the result of the correctness test, once executed. */
+ private static Boolean valid;
+ protected int macSize;
+ protected int blockSize;
+ protected IMessageDigest ipadHash;
+ protected IMessageDigest opadHash;
+ protected byte[] ipad;
+
+ /**
+ * Trivial constructor for use by concrete subclasses.
+ *
+ * @param underlyingHash the underlying hash algorithm instance.
+ */
+ protected HMac(IMessageDigest underlyingHash)
+ {
+ super(Registry.HMAC_NAME_PREFIX + underlyingHash.name(), underlyingHash);
+
+ this.blockSize = underlyingHash.blockSize();
+ this.macSize = underlyingHash.hashSize();
+ ipadHash = opadHash = null;
+ }
+
+ public Object clone() throws CloneNotSupportedException
+ {
+ HMac result = (HMac) super.clone();
+ if (this.ipadHash != null)
+ result.ipadHash = (IMessageDigest) this.ipadHash.clone();
+ if (this.opadHash != null)
+ result.opadHash = (IMessageDigest) this.opadHash.clone();
+ if (this.ipad != null)
+ result.ipad = (byte[]) this.ipad.clone();
+
+ return result;
+ }
+
+ public void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException
+ {
+ Integer ts = (Integer) attributes.get(TRUNCATED_SIZE);
+ truncatedSize = (ts == null ? macSize : ts.intValue());
+ if (truncatedSize < (macSize / 2))
+ throw new IllegalArgumentException("Truncated size too small");
+ else if (truncatedSize < 10)
+ throw new IllegalArgumentException("Truncated size less than 80 bits");
+
+ // we dont use/save the key outside this method
+ byte[] K = (byte[]) attributes.get(MAC_KEY_MATERIAL);
+ if (K == null)
+ { // take it as an indication to re-use previous key if set
+ if (ipadHash == null)
+ throw new InvalidKeyException("Null key");
+ // we already went through the motions; ie. up to step #4. re-use
+ underlyingHash = (IMessageDigest) ipadHash.clone();
+ return;
+ }
+
+ // for HMACs used in key-derivation functions (e.g. PBKDF2) the key material
+ // need not be >= the (output) block size of the underlying algorithm
+ Boolean pkcs5 = (Boolean) attributes.get(USE_WITH_PKCS5_V2);
+ if (pkcs5 == null)
+ pkcs5 = Boolean.FALSE;
+ if (K.length < macSize && ! pkcs5.booleanValue())
+ throw new InvalidKeyException("Key too short");
+
+ if (K.length > blockSize)
+ {
+ // (0) replace K with HASH(K) if K is larger than the hash's block size.
+ // Then pad with zeros until it is the correct size (the next `if').
+ underlyingHash.update(K, 0, K.length);
+ K = underlyingHash.digest();
+ }
+ if (K.length < blockSize)
+ {
+ // (1) append zeros to the end of K to create a B byte string (e.g., if
+ // K is of length 20 bytes and B=64, then K will be appended with 44
+ // zero bytes 0x00)
+ int limit = (K.length > blockSize) ? blockSize : K.length;
+ byte[] newK = new byte[blockSize];
+ System.arraycopy(K, 0, newK, 0, limit);
+ K = newK;
+ }
+ underlyingHash.reset();
+ opadHash = (IMessageDigest) underlyingHash.clone();
+ if (ipad == null)
+ ipad = new byte[blockSize];
+ // (2) XOR (bitwise exclusive-OR) the B byte string computed in step (1)
+ // with ipad
+ // (3) append the stream of data 'text' to the B byte string resulting from
+ // step (2)
+ // (4) apply H to the stream generated in step (3)
+ for (int i = 0; i < blockSize; i++)
+ ipad[i] = (byte)(K[i] ^ IPAD_BYTE);
+ for (int i = 0; i < blockSize; i++)
+ opadHash.update((byte)(K[i] ^ OPAD_BYTE));
+ underlyingHash.update(ipad, 0, blockSize);
+ ipadHash = (IMessageDigest) underlyingHash.clone();
+ K = null;
+ }
+
+ public void reset()
+ {
+ super.reset();
+ if (ipad != null)
+ {
+ underlyingHash.update(ipad, 0, blockSize);
+ ipadHash = (IMessageDigest) underlyingHash.clone();
+ }
+ }
+
+ public byte[] digest()
+ {
+ if (ipadHash == null)
+ throw new IllegalStateException("HMAC not initialised");
+ byte[] out = underlyingHash.digest();
+ // (5) XOR (bitwise exclusive-OR) the B byte string computed in step (1)
+ // with opad
+ underlyingHash = (IMessageDigest) opadHash.clone();
+ // (6) append the H result from step (4) to the B byte string resulting from
+ // step (5)
+ underlyingHash.update(out, 0, macSize);
+ // (7) apply H to the stream generated in step (6) and output the result
+ out = underlyingHash.digest(); // which also resets the underlying hash
+ // truncate and return
+ if (truncatedSize == macSize)
+ return out;
+ byte[] result = new byte[truncatedSize];
+ System.arraycopy(out, 0, result, 0, truncatedSize);
+ return result;
+ }
+
+ public boolean selfTest()
+ {
+ if (valid == null)
+ {
+ try
+ {
+ IMac mac = new HMac(new MD5()); // use rfc-2104 test vectors
+ String tv1 = "9294727A3638BB1C13F48EF8158BFC9D";
+ String tv3 = "56BE34521D144C88DBB8C733F0E8B3F6";
+ byte[] k1 = new byte[] {
+ 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B,
+ 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B };
+ byte[] k3 = new byte[] {
+ (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,
+ (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,
+ (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,
+ (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA };
+ byte[] data = new byte[50];
+ for (int i = 0; i < 50;)
+ data[i++] = (byte) 0xDD;
+
+ HashMap map = new HashMap();
+ // test vector #1
+ map.put(MAC_KEY_MATERIAL, k1);
+ mac.init(map);
+ mac.update("Hi There".getBytes("ASCII"), 0, 8);
+ if (! tv1.equals(Util.toString(mac.digest())))
+ valid = Boolean.FALSE;
+
+ // test #2 is not used since it causes a "Key too short" exception
+
+ // test vector #3
+ map.put(MAC_KEY_MATERIAL, k3);
+ mac.init(map);
+ mac.update(data, 0, 50);
+ if (! tv3.equals(Util.toString(mac.digest())))
+ valid = Boolean.FALSE;
+ valid = Boolean.TRUE;
+ }
+ catch (Exception x)
+ {
+ x.printStackTrace(System.err);
+ valid = Boolean.FALSE;
+ }
+ }
+ return valid.booleanValue();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMacFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMacFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMacFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/HMacFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* HMacFactory.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mac;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * A <i>Factory</i> to instantiate Keyed-Hash Message Authentication Code
+ * (HMAC) algorithm instances.
+ */
+public class HMacFactory
+ implements Registry
+{
+ /** Trivial constructor to enforce <i>Singleton</i> pattern. */
+ private HMacFactory()
+ {
+ super();
+ }
+
+ /**
+ * Return an instance of a <i>HMAC</i> algorithm given the name of its
+ * underlying hash function, prefixed with the literal defined in
+ * {@link Registry#HMAC_NAME_PREFIX}.
+ *
+ * @param name the fully qualified name of the underlying algorithm: composed
+ * as the concatenation of a literal prefix (see
+ * {@link Registry#HMAC_NAME_PREFIX}) and the name of the underlying
+ * hash algorithm.
+ * @return an instance of the <i>HMAC</i> algorithm, or <code>null</code>
+ * if none can be constructed.
+ * @exception InternalError if the implementation does not pass its self-test.
+ */
+ public static IMac getInstance(String name)
+ {
+ if (name == null)
+ return null;
+
+ name = name.trim();
+ name = name.toLowerCase();
+ if (! name.startsWith(HMAC_NAME_PREFIX))
+ return null;
+
+ // strip the prefix
+ name = name.substring(HMAC_NAME_PREFIX.length()).trim();
+ IMac result = new HMac(HashFactory.getInstance(name));
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
+
+ return result;
+ }
+
+ /**
+ * <p>
+ * Returns a {@link java.util.Set} of names of <i>HMAC</i> algorithms
+ * supported by this <i>Factory</i>.
+ * </p>
+ *
+ * @return a {@link java.util.Set} of HMAC algorithm names (Strings).
+ */
+ public static final Set getNames()
+ {
+ Set hashNames = HashFactory.getNames();
+ HashSet hs = new HashSet();
+ for (Iterator it = hashNames.iterator(); it.hasNext();)
+ hs.add(HMAC_NAME_PREFIX + ((String) it.next()));
+
+ return Collections.unmodifiableSet(hs);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/IMac.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/IMac.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/IMac.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/IMac.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,181 @@
+/* IMac.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mac;
+
+import java.security.InvalidKeyException;
+import java.util.Map;
+
+/**
+ * The basic visible methods of any MAC (Message Authentication Code) algorithm.
+ * <p>
+ * A <i>MAC</i> provides a way to check the integrity of information
+ * transmitted over, or stored in, an unreliable medium, based on a secret key.
+ * Typically, <i>MAC</i>s are used between two parties, that share a common
+ * secret key, in order to validate information transmitted between them.
+ * <p>
+ * When a <i>MAC</i> algorithm is based on a cryptographic hash function, it is
+ * then called to a <i>HMAC</i> (Hashed Message Authentication Code) --see <a
+ * href="http://www.ietf.org/rfc/rfc-2104.txt">RFC-2104</a>.
+ * <p>
+ * Another type of <i>MAC</i> algorithms exist: UMAC or <i>Universal Message
+ * Authentication Code</i>, described in <a
+ * href="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">
+ * draft-krovetz-umac-01.txt</a>.
+ * <p>
+ * With <i>UMAC</i>s, the sender and receiver share a common secret key (the
+ * <i>MAC</i> key) which determines:
+ * <ul>
+ * <li>The key for a <i>universal hash function</i>. This hash function is
+ * <i>non-cryptographic</i>, in the sense that it does not need to have any
+ * cryptographic <i>hardness</i> property. Rather, it needs to satisfy some
+ * combinatorial property, which can be proven to hold without relying on
+ * unproven hardness assumptions.</li>
+ * <li>The key for a <i>pseudorandom function</i>. This is where one needs a
+ * cryptographic hardness assumption. The pseudorandom function may be obtained
+ * from a <i>block cipher</i> or a <i>cryptographic hash function</i>. </li>
+ * </ul>
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc-2104.txt">RFC 2104</a>HMAC:
+ * Keyed-Hashing for Message Authentication.<br>
+ * H. Krawczyk, M. Bellare, and R. Canetti.</li>
+ * <li><a href="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">
+ * UMAC</a>: Message Authentication Code using Universal Hashing.<br>
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.</li>
+ * </ol>
+ */
+public interface IMac
+{
+ /**
+ * Property name of the user-supplied key material. The value associated to
+ * this property name is taken to be a byte array.
+ */
+ String MAC_KEY_MATERIAL = "gnu.crypto.mac.key.material";
+ /**
+ * Property name of the desired truncated output size in bytes. The value
+ * associated to this property name is taken to be an integer. If no value is
+ * specified in the attributes map at initialisation time, then all bytes of
+ * the underlying hash algorithm's output are emitted.
+ * <p>
+ * This implementation, follows the recommendation of the <i>RFC 2104</i>
+ * authors; specifically:
+ * <pre>
+ * We recommend that the output length t be not less than half the
+ * length of the hash output (to match the birthday attack bound)
+ * and not less than 80 bits (a suitable lower bound on the number
+ * of bits that need to be predicted by an attacker).
+ * </pre>
+ */
+ String TRUNCATED_SIZE = "gnu.crypto.mac.truncated.size";
+
+ /**
+ * Returns the canonical name of this algorithm.
+ *
+ * @return the canonical name of this algorithm.
+ */
+ String name();
+
+ /**
+ * Returns the output length in bytes of this <i>MAC</i> algorithm.
+ *
+ * @return the output length in bytes of this <i>MAC</i> algorithm.
+ */
+ int macSize();
+
+ /**
+ * Initialises the algorithm with designated attributes. Permissible names and
+ * values are described in the class documentation above.
+ *
+ * @param attributes a set of name-value pairs that describe the desired
+ * future instance behaviour.
+ * @exception InvalidKeyException if the key data is invalid.
+ * @exception IllegalStateException if the instance is already initialised.
+ * @see #MAC_KEY_MATERIAL
+ */
+ void init(Map attributes) throws InvalidKeyException, IllegalStateException;
+
+ /**
+ * Continues a <i>MAC</i> operation using the input byte.
+ *
+ * @param b the input byte to digest.
+ */
+ void update(byte b);
+
+ /**
+ * Continues a <i>MAC</i> operation, by filling the buffer, processing data
+ * in the algorithm's MAC_SIZE-bit block(s), updating the context and count,
+ * and buffering the remaining bytes in buffer for the next operation.
+ *
+ * @param in the input block.
+ * @param offset start of meaningful bytes in input block.
+ * @param length number of bytes, in input block, to consider.
+ */
+ void update(byte[] in, int offset, int length);
+
+ /**
+ * Completes the <i>MAC</i> by performing final operations such as padding
+ * and resetting the instance.
+ *
+ * @return the array of bytes representing the <i>MAC</i> value.
+ */
+ byte[] digest();
+
+ /**
+ * Resets the algorithm instance for re-initialisation and use with other
+ * characteristics. This method always succeeds.
+ */
+ void reset();
+
+ /**
+ * A basic test. Ensures that the MAC of a pre-determined message is equal to
+ * a known pre-computed value.
+ *
+ * @return <code>true</code> if the implementation passes a basic self-test.
+ * Returns <code>false</code> otherwise.
+ */
+ boolean selfTest();
+
+ /**
+ * Returns a clone copy of this instance.
+ *
+ * @return a clone copy of this instance.
+ */
+ Object clone() throws CloneNotSupportedException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,130 @@
+/* MacFactory.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mac;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * A <i>Factory</i> that instantiates instances of every supported Message
+ * Authentication Code algorithms, including all <i>HMAC</i> algorithms.
+ */
+public class MacFactory
+ implements Registry
+{
+ private static Set names;
+
+ /** Trivial constructor to enforce <i>Singleton</i> pattern. */
+ private MacFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a <i>MAC</i> algorithm given its name.
+ *
+ * @param name the name of the MAC algorithm.
+ * @return an instance of the <i>MAC</i> algorithm, or <code>null</code> if
+ * none can be constructed.
+ * @exception InternalError if the implementation does not pass its self-test.
+ */
+ public static IMac getInstance(String name)
+ {
+ if (name == null)
+ return null;
+
+ name = name.trim();
+ name = name.toLowerCase();
+ if (name.startsWith(HMAC_NAME_PREFIX))
+ return HMacFactory.getInstance(name);
+
+ if (name.startsWith(OMAC_PREFIX))
+ {
+ name = name.substring(OMAC_PREFIX.length());
+ IBlockCipher cipher = CipherFactory.getInstance(name);
+ if (cipher == null)
+ return null;
+ return new OMAC(cipher);
+ }
+ IMac result = null;
+ if (name.equalsIgnoreCase(UHASH32))
+ result = new UHash32();
+ else if (name.equalsIgnoreCase(UMAC32))
+ result = new UMac32();
+ else if (name.equalsIgnoreCase(TMMH16))
+ result = new TMMH16();
+
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of names of <i>MAC</i> algorithms supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of MAC names (Strings).
+ */
+ public static final Set getNames()
+ {
+ synchronized (MacFactory.class)
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.addAll(HMacFactory.getNames());
+ hs.add(UHASH32);
+ hs.add(UMAC32);
+ hs.add(TMMH16);
+ for (Iterator it = CipherFactory.getNames().iterator(); it.hasNext();)
+ hs.add(OMAC_PREFIX + it.next());
+
+ names = Collections.unmodifiableSet(hs);
+ }
+ }
+ return names;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,124 @@
+/* MacInputStream.java --
+ Copyright (C) 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.javax.crypto.mac;
+
+import java.io.FilterInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+
+/**
+ * A filtering input stream that computes a MAC (message authentication code)
+ * over all data read from the stream.
+ */
+public class MacInputStream
+ extends FilterInputStream
+{
+ /** The digesting state. The MAC is updated only if this flag is true. */
+ private boolean digesting;
+ /** The MAC being updated. */
+ private IMac mac;
+
+ /**
+ * Creates a new MacInputStream. The stream is initially set to digest data
+ * written, the <i>mac</i> argument must have already been initialized, and
+ * the <i>mac</i> argument is <b>not</b> cloned.
+ *
+ * @param in The underlying input stream.
+ * @param mac The mac instance to use.
+ */
+ public MacInputStream(InputStream in, IMac mac)
+ {
+ super(in);
+ if (mac == null)
+ throw new NullPointerException();
+ this.mac = mac;
+ digesting = true;
+ }
+
+ /**
+ * Returns the MAC this stream is updating.
+ *
+ * @return The MAC.
+ */
+ public IMac getMac()
+ {
+ return mac;
+ }
+
+ /**
+ * Sets the MAC this stream is updating, which must have already been
+ * initialized. The argument is not cloned by this method.
+ *
+ * @param mac The new MAC.
+ * @throws NullPointerException If the argument is null.
+ */
+ public void setMac(IMac mac)
+ {
+ if (mac == null)
+ throw new NullPointerException();
+ this.mac = mac;
+ }
+
+ /**
+ * Turns the digesting state on or off. When off, the MAC will not be updated
+ * when data is written to the stream.
+ *
+ * @param flag The new digesting state.
+ */
+ public void on(boolean flag)
+ {
+ digesting = flag;
+ }
+
+ public int read() throws IOException
+ {
+ int i = in.read();
+ if (digesting && i != -1)
+ mac.update((byte) i);
+ return i;
+ }
+
+ public int read(byte[] buf, int off, int len) throws IOException
+ {
+ int i = in.read(buf, off, len);
+ if (digesting && i != -1)
+ mac.update(buf, off, i);
+ return i;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacOutputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacOutputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacOutputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/MacOutputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,123 @@
+/* MacOutputStream.java --
+ Copyright (C) 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.javax.crypto.mac;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * A filtering output stream that computes a MAC (message authentication code)
+ * over all data written to the stream.
+ */
+public class MacOutputStream
+ extends FilterOutputStream
+{
+ /** The digesting state. The MAC is updated only if this flag is true. */
+ private boolean digesting;
+ /** The MAC being updated. */
+ private IMac mac;
+
+ /**
+ * Creates a new <code>MacOutputStream</code>. The stream is initially set
+ * to digest data written, the <code>mac</code> argument must have already
+ * been initialized, and the <code>mac</code> argument is <b>not</b>
+ * cloned.
+ *
+ * @param out The underlying output stream.
+ * @param mac The mac instance to use.
+ */
+ public MacOutputStream(OutputStream out, IMac mac)
+ {
+ super(out);
+ if (mac == null)
+ throw new NullPointerException();
+ this.mac = mac;
+ digesting = true;
+ }
+
+ /**
+ * Returns the MAC this stream is updating.
+ *
+ * @return The MAC.
+ */
+ public IMac getMac()
+ {
+ return mac;
+ }
+
+ /**
+ * Sets the MAC this stream is updating, which must have already been
+ * initialized. The argument is not cloned by this method.
+ *
+ * @param mac The non-null new MAC.
+ * @throws NullPointerException If the argument is null.
+ */
+ public void setMac(IMac mac)
+ {
+ if (mac == null)
+ throw new NullPointerException();
+ this.mac = mac;
+ }
+
+ /**
+ * Turns the digesting state on or off. When off, the MAC will not be updated
+ * when data is written to the stream.
+ *
+ * @param flag The new digesting state.
+ */
+ public void on(boolean flag)
+ {
+ digesting = flag;
+ }
+
+ public void write(int b) throws IOException
+ {
+ if (digesting)
+ mac.update((byte) b);
+ out.write(b);
+ }
+
+ public void write(byte[] buf, int off, int len) throws IOException
+ {
+ if (digesting)
+ mac.update(buf, off, len);
+ out.write(buf, off, len);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/OMAC.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/OMAC.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/OMAC.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/OMAC.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,303 @@
+/* OMAC.java --
+ 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.javax.crypto.mac;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.mode.IMode;
+
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * The One-Key CBC MAC, OMAC. This message authentication code is based on a
+ * block cipher in CBC mode.
+ * <p>
+ * References:
+ * <ol>
+ * <li>Tetsu Iwata and Kaoru Kurosawa, <i><a
+ * href="http://crypt.cis.ibaraki.ac.jp/omac/docs/omac.pdf">OMAC: One-Key CBC
+ * MAC</a></i>.</li>
+ * </ol>
+ */
+public class OMAC
+ implements IMac
+{
+ private static final Logger log = Logger.getLogger(OMAC.class.getName());
+ private static final byte C1 = (byte) 0x87;
+ private static final byte C2 = 0x1b;
+ // Test key for OMAC-AES-128
+ private static final byte[] KEY0 =
+ Util.toBytesFromString("2b7e151628aed2a6abf7158809cf4f3c");
+ // Test MAC for zero-length input.
+ private static final byte[] DIGEST0 =
+ Util.toBytesFromString("bb1d6929e95937287fa37d129b756746");
+ private static Boolean valid;
+ private final IBlockCipher cipher;
+ private final String name;
+ private IMode mode;
+ private int blockSize;
+ private int outputSize;
+ private byte[] Lu, Lu2;
+ private byte[] M;
+ private byte[] Y;
+ private boolean init;
+ private int index;
+
+ public OMAC(IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.name = "OMAC-" + cipher.name();
+ }
+
+ public Object clone()
+ {
+ return new OMAC(cipher);
+ }
+
+ public String name()
+ {
+ return name;
+ }
+
+ public int macSize()
+ {
+ return outputSize;
+ }
+
+ public void init(Map attrib) throws InvalidKeyException
+ {
+ HashMap attrib2 = new HashMap();
+ attrib2.put(IBlockCipher.KEY_MATERIAL, attrib.get(MAC_KEY_MATERIAL));
+ cipher.reset();
+ cipher.init(attrib2);
+ blockSize = cipher.currentBlockSize();
+ Integer os = (Integer) attrib.get(TRUNCATED_SIZE);
+ if (os != null)
+ {
+ outputSize = os.intValue();
+ if (outputSize < 0 || outputSize > blockSize)
+ throw new IllegalArgumentException("truncated size out of range");
+ }
+ else
+ outputSize = blockSize;
+
+ byte[] L = new byte[blockSize];
+ cipher.encryptBlock(L, 0, L, 0);
+ if (Configuration.DEBUG)
+ log.fine("L = " + Util.toString(L).toLowerCase());
+ if (Lu != null)
+ {
+ Arrays.fill(Lu, (byte) 0);
+ if (Lu.length != blockSize)
+ Lu = new byte[blockSize];
+ }
+ else
+ Lu = new byte[blockSize];
+ if (Lu2 != null)
+ {
+ Arrays.fill(Lu2, (byte) 0);
+ if (Lu2.length != blockSize)
+ Lu2 = new byte[blockSize];
+ }
+ else
+ Lu2 = new byte[blockSize];
+
+ boolean msb = (L[0] & 0x80) != 0;
+ for (int i = 0; i < blockSize; i++)
+ {
+ Lu[i] = (byte)(L[i] << 1 & 0xFF);
+ if (i + 1 < blockSize)
+ Lu[i] |= (byte)((L[i + 1] & 0x80) >> 7);
+ }
+ if (msb)
+ {
+ if (blockSize == 16)
+ Lu[Lu.length - 1] ^= C1;
+ else if (blockSize == 8)
+ Lu[Lu.length - 1] ^= C2;
+ else
+ throw new IllegalArgumentException("unsupported cipher block size: "
+ + blockSize);
+ }
+ if (Configuration.DEBUG)
+ log.fine("Lu = " + Util.toString(Lu).toLowerCase());
+ msb = (Lu[0] & 0x80) != 0;
+ for (int i = 0; i < blockSize; i++)
+ {
+ Lu2[i] = (byte)(Lu[i] << 1 & 0xFF);
+ if (i + 1 < blockSize)
+ Lu2[i] |= (byte)((Lu[i + 1] & 0x80) >> 7);
+ }
+ if (msb)
+ {
+ if (blockSize == 16)
+ Lu2[Lu2.length - 1] ^= C1;
+ else
+ Lu2[Lu2.length - 1] ^= C2;
+ }
+ if (Configuration.DEBUG)
+ log.fine("Lu2 = " + Util.toString(Lu2).toLowerCase());
+ if (M != null)
+ {
+ Arrays.fill(M, (byte) 0);
+ if (M.length != blockSize)
+ M = new byte[blockSize];
+ }
+ else
+ M = new byte[blockSize];
+ if (Y != null)
+ {
+ Arrays.fill(Y, (byte) 0);
+ if (Y.length != blockSize)
+ Y = new byte[blockSize];
+ }
+ else
+ Y = new byte[blockSize];
+
+ index = 0;
+ init = true;
+ }
+
+ public void update(byte b)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ if (index == M.length)
+ {
+ process();
+ index = 0;
+ }
+ M[index++] = b;
+ }
+
+ public void update(byte[] buf, int off, int len)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ if (off < 0 || len < 0 || off + len > buf.length)
+ throw new IndexOutOfBoundsException("size=" + buf.length + "; off=" + off
+ + "; len=" + len);
+ for (int i = 0; i < len;)
+ {
+ if (index == blockSize)
+ {
+ process();
+ index = 0;
+ }
+ int count = Math.min(blockSize - index, len - i);
+ System.arraycopy(buf, off + i, M, index, count);
+ index += count;
+ i += count;
+ }
+ }
+
+ public byte[] digest()
+ {
+ byte[] b = new byte[outputSize];
+ digest(b, 0);
+ return b;
+ }
+
+ public void digest(byte[] out, int off)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ if (off < 0 || off + outputSize > out.length)
+ throw new IndexOutOfBoundsException("size=" + out.length + "; off=" + off
+ + "; len=" + outputSize);
+ byte[] T = new byte[blockSize];
+ byte[] L = Lu;
+ if (index < blockSize)
+ {
+ M[index++] = (byte) 0x80;
+ while (index < blockSize)
+ M[index++] = 0;
+ L = Lu2;
+ }
+ for (int i = 0; i < blockSize; i++)
+ T[i] = (byte)(M[i] ^ Y[i] ^ L[i]);
+ cipher.encryptBlock(T, 0, T, 0);
+ System.arraycopy(T, 0, out, off, outputSize);
+ reset();
+ }
+
+ public void reset()
+ {
+ index = 0;
+ if (Y != null)
+ Arrays.fill(Y, (byte) 0);
+ if (M != null)
+ Arrays.fill(M, (byte) 0);
+ }
+
+ public boolean selfTest()
+ {
+ OMAC mac = new OMAC(CipherFactory.getInstance(Registry.AES_CIPHER));
+ mac.reset();
+ Map attr = new HashMap();
+ attr.put(MAC_KEY_MATERIAL, KEY0);
+ byte[] digest = null;
+ try
+ {
+ mac.init(attr);
+ digest = mac.digest();
+ }
+ catch (Exception x)
+ {
+ return false;
+ }
+ if (digest == null)
+ return false;
+ return Arrays.equals(DIGEST0, digest);
+ }
+
+ private void process()
+ {
+ for (int i = 0; i < blockSize; i++)
+ M[i] = (byte)(M[i] ^ Y[i]);
+ cipher.encryptBlock(M, 0, Y, 0);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,339 @@
+/* TMMH16.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mac;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+
+import java.security.InvalidKeyException;
+import java.util.Map;
+
+/**
+ * <i>TMMH</i> is a <i>universal</i> hash function suitable for message
+ * authentication in the Wegman-Carter paradigm, as in the Stream Cipher
+ * Security Transform. It is simple, quick, and especially appropriate for
+ * Digital Signal Processors and other processors with a fast multiply
+ * operation, though a straightforward implementation requires storage equal in
+ * length to the largest message to be hashed.
+ * <p>
+ * <i>TMMH</i> is a simple hash function which maps a key and a message to a
+ * hash value. There are two versions of TMMH: TMMH/16 and TMMH/32. <i>TMMH</i>
+ * can be used as a message authentication code, as described in Section 5 (see
+ * References).
+ * <p>
+ * The key, message, and hash value are all octet strings, and the lengths of
+ * these quantities are denoted as <code>KEY_LENGTH</code>,
+ * <code>MESSAGE_LENGTH</code>, and <code>TAG_LENGTH</code>, respectively.
+ * The values of <code>KEY_LENGTH</code> and <code>TAG_LENGTH</code>
+ * <bold>MUST</bold> be fixed for any particular fixed value of the key, and
+ * must obey the alignment restrictions described below.
+ * <p>
+ * The parameter <code>MAX_HASH_LENGTH</code>, which denotes the maximum
+ * value which <code>MESSAGE_LENGTH</code> may take, is equal to
+ * <code>KEY_LENGTH - TAG_LENGTH</code>.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.ietf.org/internet-drafts/draft-mcgrew-saag-tmmh-01.txt"> The
+ * Truncated Multi-Modular Hash Function (TMMH)</a>, David A. McGrew.</li>
+ * </ol>
+ */
+public class TMMH16
+ extends BaseMac
+ implements Cloneable
+{
+ public static final String TAG_LENGTH = "gnu.crypto.mac.tmmh.tag.length";
+ public static final String KEYSTREAM = "gnu.crypto.mac.tmmh.keystream";
+ public static final String PREFIX = "gnu.crypto.mac.tmmh.prefix";
+ private static final int P = (1 << 16) + 1; // the TMMH/16 prime
+ /** caches the result of the correctness test, once executed. */
+ private static Boolean valid;
+ private int tagWords = 0; // the tagLength expressed in words
+ private IRandom keystream = null; // the keystream generator
+ private byte[] prefix; // mask to use when operating as an authentication f.
+ private long keyWords; // key words counter
+ private long msgLength; // in bytes
+ private long msgWords; // should be = msgLength * WORD_LENGTH
+ private int[] context; // the tmmh running context; length == TAG_WORDS
+ private int[] K0; // the first TAG_WORDS words of the keystream
+ private int[] Ki; // the sliding TAG_WORDS words of the keystream
+ private int Mi; // current message word being constructed
+
+ /** Trivial 0-arguments constructor. */
+ public TMMH16()
+ {
+ super(Registry.TMMH16);
+ }
+
+ public int macSize()
+ {
+ return tagWords * 2;
+ }
+
+ public void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException
+ {
+ int wantTagLength = 0;
+ Integer tagLength = (Integer) attributes.get(TAG_LENGTH); // get tag length
+ if (tagLength == null)
+ {
+ if (tagWords == 0) // was never set
+ throw new IllegalArgumentException(TAG_LENGTH);
+ // else re-use
+ }
+ else // check if positive and is divisible by WORD_LENGTH
+ {
+ wantTagLength = tagLength.intValue();
+ if (wantTagLength < 2 || (wantTagLength % 2 != 0))
+ throw new IllegalArgumentException(TAG_LENGTH);
+ else if (wantTagLength > (512 / 8)) // 512-bits is our maximum
+ throw new IllegalArgumentException(TAG_LENGTH);
+
+ tagWords = wantTagLength / 2; // init local vars
+ K0 = new int[tagWords];
+ Ki = new int[tagWords];
+ context = new int[tagWords];
+ }
+
+ prefix = (byte[]) attributes.get(PREFIX);
+ if (prefix == null) // default to all-zeroes
+ prefix = new byte[tagWords * 2];
+ else // ensure it's as long as it should
+ {
+ if (prefix.length != tagWords * 2)
+ throw new IllegalArgumentException(PREFIX);
+ }
+
+ IRandom prng = (IRandom) attributes.get(KEYSTREAM); // get keystream
+ if (prng == null)
+ {
+ if (keystream == null)
+ throw new IllegalArgumentException(KEYSTREAM);
+ // else reuse
+ }
+ else
+ keystream = prng;
+
+ reset(); // reset context variables
+ for (int i = 0; i < tagWords; i++) // init starting key words
+ Ki[i] = K0[i] = getNextKeyWord(keystream);
+ }
+
+ // The words of the key are denoted as K[1], K[2], ..., K[KEY_WORDS], and the
+ // words of the message (after zero padding, if needed) are denoted as M[1],
+ // M[2], ..., M[MSG_WORDS], where MSG_WORDS is the smallest number such that
+ // 2 * MSG_WORDS is at least MESSAGE_LENGTH, and KEY_WORDS is KEY_LENGTH / 2.
+ //
+ // If MESSAGE_LENGTH is greater than MAX_HASH_LENGTH, then the value of
+ // TMMH/16 is undefined. Implementations MUST indicate an error if asked to
+ // hash a message with such a length. Otherwise, the hash value is defined
+ // to be the length TAG_WORDS sequence of words in which the j-th word in the
+ // sequence is defined as
+ //
+ // [ [ K[j] * MESSAGE_LENGTH +32 K[j+1] * M[1] +32 K[j+2] * M[2]
+ // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
+ //
+ // where j ranges from 1 to TAG_WORDS.
+ public void update(byte b)
+ {
+ this.update(b, keystream);
+ }
+
+ public void update(byte[] b, int offset, int len)
+ {
+ for (int i = 0; i < len; i++)
+ this.update(b[offset + i], keystream);
+ }
+
+ // For TMMH/16, KEY_LENGTH and TAG_LENGTH MUST be a multiple of two. The key,
+ // message, and hash value are treated as a sequence of unsigned sixteen bit
+ // integers in network byte order. (In this section, we call such an integer
+ // a word.) If MESSAGE_LENGTH is odd, then a zero byte is appended to the
+ // message to align it on a word boundary, though this process does not
+ // change the value of MESSAGE_LENGTH.
+ //
+ // ... Otherwise, the hash value is defined to be the length TAG_WORDS
+ // sequence of words in which the j-th word in the sequence is defined as
+ //
+ // [ [ K[j] * MESSAGE_LENGTH +32 K[j+1] * M[1] +32 K[j+2] * M[2]
+ // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
+ //
+ // where j ranges from 1 to TAG_WORDS.
+ //
+ // Here, TAG_WORDS is equal to TAG_LENGTH / 2, and p is equal to 2^16 + 1.
+ // The symbol * denotes multiplication and the symbol +32 denotes addition
+ // modulo 2^32.
+ public byte[] digest()
+ {
+ return this.digest(keystream);
+ }
+
+ public void reset()
+ {
+ msgLength = msgWords = keyWords = 0L;
+ Mi = 0;
+ for (int i = 0; i < tagWords; i++)
+ context[i] = 0;
+ }
+
+ public boolean selfTest()
+ {
+ if (valid == null)
+ {
+ // TODO: compute and test equality with one known vector
+ valid = Boolean.TRUE;
+ }
+ return valid.booleanValue();
+ }
+
+ public Object clone() throws CloneNotSupportedException
+ {
+ TMMH16 result = (TMMH16) super.clone();
+ if (this.keystream != null)
+ result.keystream = (IRandom) this.keystream.clone();
+ if (this.prefix != null)
+ result.prefix = (byte[]) this.prefix.clone();
+ if (this.context != null)
+ result.context = (int[]) this.context.clone();
+ if (this.K0 != null)
+ result.K0 = (int[]) this.K0.clone();
+ if (this.Ki != null)
+ result.Ki = (int[]) this.Ki.clone();
+ return result;
+ }
+
+ /**
+ * Similar to the same method with one argument, but uses the designated
+ * random number generator to compute needed keying material.
+ *
+ * @param b the byte to process.
+ * @param prng the source of randomness to use.
+ */
+ public void update(byte b, IRandom prng)
+ {
+ Mi <<= 8; // update message buffer
+ Mi |= b & 0xFF;
+ msgLength++; // update message length (bytes)
+ if (msgLength % 2 == 0) // got a full word
+ {
+ msgWords++; // update message words counter
+ System.arraycopy(Ki, 1, Ki, 0, tagWords - 1); // 1. shift Ki up by 1
+ Ki[tagWords - 1] = getNextKeyWord(prng); // 2. fill last box of Ki
+ long t; // temp var to allow working in modulo 2^32
+ for (int i = 0; i < tagWords; i++) // 3. update context
+ {
+ t = context[i] & 0xFFFFFFFFL;
+ t += Ki[i] * Mi;
+ context[i] = (int) t;
+ }
+ Mi = 0; // reset message buffer
+ }
+ }
+
+ /**
+ * Similar to the same method with three arguments, but uses the designated
+ * random number generator to compute needed keying material.
+ *
+ * @param b the byte array to process.
+ * @param offset the starting offset in <code>b</code> to start considering
+ * the bytes to process.
+ * @param len the number of bytes in <code>b</code> starting from
+ * <code>offset</code> to process.
+ * @param prng the source of randomness to use.
+ */
+ public void update(byte[] b, int offset, int len, IRandom prng)
+ {
+ for (int i = 0; i < len; i++)
+ this.update(b[offset + i], prng);
+ }
+
+ /**
+ * Similar to the same method with no arguments, but uses the designated
+ * random number generator to compute needed keying material.
+ *
+ * @param prng the source of randomness to use.
+ * @return the final result of the algorithm.
+ */
+ public byte[] digest(IRandom prng)
+ {
+ doFinalRound(prng);
+ byte[] result = new byte[tagWords * 2];
+ for (int i = 0, j = 0; i < tagWords; i++)
+ {
+ result[j] = (byte)((context[i] >>> 8) ^ prefix[j]);
+ j++;
+ result[j] = (byte)(context[i] ^ prefix[j]);
+ j++;
+ }
+ reset();
+ return result;
+ }
+
+ private int getNextKeyWord(IRandom prng)
+ {
+ int result = 0;
+ try
+ {
+ result = (prng.nextByte() & 0xFF) << 8 | (prng.nextByte() & 0xFF);
+ }
+ catch (LimitReachedException x)
+ {
+ throw new RuntimeException(String.valueOf(x));
+ }
+ keyWords++; // update key words counter
+ return result;
+ }
+
+ private void doFinalRound(IRandom prng)
+ {
+ long limit = msgLength; // formula works on real message length
+ while (msgLength % 2 != 0)
+ update((byte) 0x00, prng);
+ long t;
+ for (int i = 0; i < tagWords; i++)
+ {
+ t = context[i] & 0xFFFFFFFFL;
+ t += K0[i] * limit;
+ t %= P;
+ context[i] = (int) t;
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UHash32.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UHash32.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UHash32.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UHash32.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,758 @@
+/* UHash32.java --
+ 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.javax.crypto.mac;
+
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.prng.UMacGenerator;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <i>UHASH</i> is a keyed hash function, which takes as input a string of
+ * arbitrary length, and produces as output a string of fixed length (such as 8
+ * bytes). The actual output length depends on the parameter UMAC-OUTPUT-LEN.
+ * <p>
+ * <i>UHASH</i> has been shown to be <i>epsilon-ASU</i> ("Almost Strongly
+ * Universal"), where epsilon is a small (parameter-dependent) real number.
+ * Informally, saying that a keyed hash function is <i>epsilon-ASU</i> means
+ * that for any two distinct fixed input strings, the two outputs of the hash
+ * function with a random key "look almost like a pair of random strings". The
+ * number epsilon measures how non-random the output strings may be.
+ * <p>
+ * <i>UHASH</i> has been designed to be fast by exploiting several
+ * architectural features of modern commodity processors. It was specifically
+ * designed for use in <i>UMAC</i>. But <i>UHASH</i> is useful beyond that
+ * domain, and can be easily adopted for other purposes.
+ * <p>
+ * <i>UHASH</i> does its work in three layers. First, a hash function called
+ * <code>NH</code> is used to compress input messages into strings which are
+ * typically many times smaller than the input message. Second, the compressed
+ * message is hashed with an optimized <i>polynomial hash function</i> into a
+ * fixed-length 16-byte string. Finally, the 16-byte string is hashed using an
+ * <i>inner-product hash</i> into a string of length WORD-LEN bytes. These
+ * three layers are repeated (with a modified key) until the outputs total
+ * UMAC-OUTPUT-LEN bytes.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">
+ * UMAC</a>: Message Authentication Code using Universal Hashing.<br>
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.</li>
+ * </ol>
+ */
+public class UHash32
+ extends BaseMac
+{
+ // UMAC prime values
+ private static final BigInteger PRIME_19 = BigInteger.valueOf(0x7FFFFL);
+ private static final BigInteger PRIME_32 = BigInteger.valueOf(0xFFFFFFFBL);
+ private static final BigInteger PRIME_36 = BigInteger.valueOf(0xFFFFFFFFBL);
+ private static final BigInteger PRIME_64 = new BigInteger(1, new byte[] {
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC5 });
+ private static final BigInteger PRIME_128 = new BigInteger(1, new byte[] {
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x61 });
+ static final BigInteger TWO = BigInteger.valueOf(2L);
+ static final long BOUNDARY = TWO.shiftLeft(17).longValue();
+ // 2**64 - 2**32
+ static final BigInteger LOWER_RANGE = TWO.pow(64).subtract(TWO.pow(32));
+ // 2**128 - 2**96
+ static final BigInteger UPPER_RANGE = TWO.pow(128).subtract(TWO.pow(96));
+ static final byte[] ALL_ZEROES = new byte[32];
+ int streams;
+ L1Hash32[] l1hash;
+
+ /** Trivial 0-arguments constructor. */
+ public UHash32()
+ {
+ super("uhash32");
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the instance to clone.
+ */
+ private UHash32(UHash32 that)
+ {
+ this();
+
+ this.streams = that.streams;
+ if (that.l1hash != null)
+ {
+ this.l1hash = new L1Hash32[that.streams];
+ for (int i = 0; i < that.streams; i++)
+ if (that.l1hash[i] != null)
+ this.l1hash[i] = (L1Hash32) that.l1hash[i].clone();
+ }
+ }
+
+ /**
+ * The prime numbers used in UMAC are:
+ * <pre>
+ * +-----+--------------------+---------------------------------------+
+ * | x | prime(x) [Decimal] | prime(x) [Hexadecimal] |
+ * +-----+--------------------+---------------------------------------+
+ * | 19 | 2^19 - 1 | 0x0007FFFF |
+ * | 32 | 2^32 - 5 | 0xFFFFFFFB |
+ * | 36 | 2^36 - 5 | 0x0000000F FFFFFFFB |
+ * | 64 | 2^64 - 59 | 0xFFFFFFFF FFFFFFC5 |
+ * | 128 | 2^128 - 159 | 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFF61 |
+ * +-----+--------------------+---------------------------------------+
+ *</pre>
+ *
+ * @param n a number of bits.
+ * @return the largest prime number less than 2**n.
+ */
+ static final BigInteger prime(int n)
+ {
+ switch (n)
+ {
+ case 19:
+ return PRIME_19;
+ case 32:
+ return PRIME_32;
+ case 36:
+ return PRIME_36;
+ case 64:
+ return PRIME_64;
+ case 128:
+ return PRIME_128;
+ default:
+ throw new IllegalArgumentException("Undefined prime("
+ + String.valueOf(n) + ")");
+ }
+ }
+
+ public Object clone()
+ {
+ return new UHash32(this);
+ }
+
+ public int macSize()
+ {
+ return UMac32.OUTPUT_LEN;
+ }
+
+ public void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException
+ {
+ byte[] K = (byte[]) attributes.get(MAC_KEY_MATERIAL);
+ if (K == null)
+ throw new InvalidKeyException("Null Key");
+ if (K.length != UMac32.KEY_LEN)
+ throw new InvalidKeyException("Invalid Key length: "
+ + String.valueOf(K.length));
+ // Calculate iterations needed to make UMAC-OUTPUT-LEN bytes
+ streams = (UMac32.OUTPUT_LEN + 3) / 4;
+ // Define total key needed for all iterations using UMacGenerator.
+ // L1Key and L3Key1 both reuse most key between iterations.
+ IRandom kdf1 = new UMacGenerator();
+ IRandom kdf2 = new UMacGenerator();
+ IRandom kdf3 = new UMacGenerator();
+ IRandom kdf4 = new UMacGenerator();
+ Map map = new HashMap();
+ map.put(IBlockCipher.KEY_MATERIAL, K);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(0));
+ kdf1.init(map);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(1));
+ kdf2.init(map);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(2));
+ kdf3.init(map);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(3));
+ kdf4.init(map);
+ // need to generate all bytes for use later in a Toepliz construction
+ byte[] L1Key = new byte[UMac32.L1_KEY_LEN + (streams - 1) * 16];
+ try
+ {
+ kdf1.nextBytes(L1Key, 0, L1Key.length);
+ }
+ catch (LimitReachedException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException("KDF for L1Key reached limit");
+ }
+
+ l1hash = new L1Hash32[streams];
+ for (int i = 0; i < streams; i++)
+ {
+ byte[] k1 = new byte[UMac32.L1_KEY_LEN];
+ System.arraycopy(L1Key, i * 16, k1, 0, UMac32.L1_KEY_LEN);
+ byte[] k2 = new byte[24];
+ try
+ {
+ kdf2.nextBytes(k2, 0, 24);
+ }
+ catch (LimitReachedException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException("KDF for L2Key reached limit");
+ }
+ byte[] k31 = new byte[64];
+ try
+ {
+ kdf3.nextBytes(k31, 0, 64);
+ }
+ catch (LimitReachedException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException("KDF for L3Key1 reached limit");
+ }
+ byte[] k32 = new byte[4];
+ try
+ {
+ kdf4.nextBytes(k32, 0, 4);
+ }
+ catch (LimitReachedException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException("KDF for L3Key2 reached limit");
+ }
+ L1Hash32 mac = new L1Hash32();
+ mac.init(k1, k2, k31, k32);
+ l1hash[i] = mac;
+ }
+ }
+
+ public void update(byte b)
+ {
+ for (int i = 0; i < streams; i++)
+ l1hash[i].update(b);
+ }
+
+ public void update(byte[] b, int offset, int len)
+ {
+ for (int i = 0; i < len; i++)
+ this.update(b[offset + i]);
+ }
+
+ public byte[] digest()
+ {
+ byte[] result = new byte[UMac32.OUTPUT_LEN];
+ for (int i = 0; i < streams; i++)
+ {
+ byte[] partialResult = l1hash[i].digest();
+ System.arraycopy(partialResult, 0, result, 4 * i, 4);
+ }
+ reset();
+ return result;
+ }
+
+ public void reset()
+ {
+ for (int i = 0; i < streams; i++)
+ l1hash[i].reset();
+ }
+
+ public boolean selfTest()
+ {
+ return true;
+ }
+
+ /**
+ * First hash stage of the UHash32 algorithm.
+ */
+ class L1Hash32
+ implements Cloneable
+ {
+ private int[] key; // key material as an array of 32-bit ints
+ private byte[] buffer; // work buffer L1_KEY_LEN long
+ private int count; // meaningful bytes in buffer
+ private ByteArrayOutputStream Y;
+ private long totalCount;
+ private L2Hash32 l2hash;
+ private L3Hash32 l3hash;
+
+ /** Trivial 0-arguments constructor. */
+ L1Hash32()
+ {
+ super();
+
+ key = new int[UMac32.L1_KEY_LEN / 4];
+ buffer = new byte[UMac32.L1_KEY_LEN];
+ count = 0;
+ Y = new ByteArrayOutputStream();
+ totalCount = 0L;
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the instance to clone.
+ */
+ private L1Hash32(L1Hash32 that)
+ {
+ this();
+
+ System.arraycopy(that.key, 0, this.key, 0, that.key.length);
+ System.arraycopy(that.buffer, 0, this.buffer, 0, that.count);
+ this.count = that.count;
+ byte[] otherY = that.Y.toByteArray();
+ this.Y.write(otherY, 0, otherY.length);
+ this.totalCount = that.totalCount;
+ if (that.l2hash != null)
+ this.l2hash = (L2Hash32) that.l2hash.clone();
+ if (that.l3hash != null)
+ this.l3hash = (L3Hash32) that.l3hash.clone();
+ }
+
+ public Object clone()
+ {
+ return new L1Hash32(this);
+ }
+
+ public void init(byte[] k1, byte[] k2, byte[] k31, byte[] k32)
+ {
+ for (int i = 0, j = 0; i < (UMac32.L1_KEY_LEN / 4); i++)
+ key[i] = k1[j++] << 24
+ | (k1[j++] & 0xFF) << 16
+ | (k1[j++] & 0xFF) << 8
+ | (k1[j++] & 0xFF);
+ l2hash = new L2Hash32(k2);
+ l3hash = new L3Hash32(k31, k32);
+ }
+
+ public void update(byte b)
+ {
+ // Break M into L1_KEY_LEN byte chunks (final chunk may be shorter)
+
+ // Let M_1, M_2, ..., M_t be strings so that M = M_1 || M_2 || .. ||
+ // M_t, and length(M_i) = L1_KEY_LEN for all 0 < i < t.
+
+ // For each chunk, except the last: endian-adjust, NH hash
+ // and add bit-length. Use results to build Y.
+ buffer[count] = b;
+ count++;
+ totalCount++;
+ if (count >= UMac32.L1_KEY_LEN)
+ {
+ byte[] y = nh32(UMac32.L1_KEY_LEN);
+ Y.write(y, 0, 8);
+
+ count = 0;
+
+ // For each iteration, extract key and three-layer hash.
+ // If length(M) <= L1_KEY_LEN, then skip L2-HASH.
+ if (Y.size() == 16) // we already hashed twice L1_KEY_LEN
+ {
+ byte[] A = Y.toByteArray();
+ Y.reset();
+ l2hash.update(A, 0, 16);
+ }
+ }
+ }
+
+ public byte[] digest()
+ {
+ // For the last chunk: pad to 32-byte boundary, endian-adjust,
+ // NH hash and add bit-length. Concatenate the result to Y.
+ if (count != 0)
+ {
+ if (count % 32 != 0)
+ {
+ int limit = 32 * ((count + 31) / 32);
+ System.arraycopy(ALL_ZEROES, 0, buffer, count, limit - count);
+ count += limit - count;
+ }
+ byte[] y = nh32(count);
+ Y.write(y, 0, 8);
+ }
+ byte[] A = Y.toByteArray();
+ Y.reset();
+ byte[] B;
+ if (totalCount <= UMac32.L1_KEY_LEN)
+ {
+ // we might have 'update'd the bytes already. check
+ if (A.length == 0) // we did
+ B = l2hash.digest();
+ else // did not
+ {
+ B = new byte[16];
+ System.arraycopy(A, 0, B, 8, 8);
+ }
+ }
+ else
+ {
+ if (A.length != 0)
+ l2hash.update(A, 0, A.length);
+ B = l2hash.digest();
+ }
+ byte[] result = l3hash.digest(B);
+ reset();
+ return result;
+ }
+
+ public void reset()
+ {
+ count = 0;
+ Y.reset();
+ totalCount = 0L;
+ if (l2hash != null)
+ l2hash.reset();
+ }
+
+ /**
+ * 5.1 NH-32: NH hashing with a 32-bit word size.
+ *
+ * @param len count of bytes, divisible by 32, in buffer to process
+ * @return Y, string of length 8 bytes.
+ */
+ private byte[] nh32(int len)
+ {
+ // Break M and K into 4-byte chunks
+ int t = len / 4;
+ // Let M_1, M_2, ..., M_t be 4-byte strings
+ // so that M = M_1 || M_2 || .. || M_t.
+ // Let K_1, K_2, ..., K_t be 4-byte strings
+ // so that K_1 || K_2 || .. || K_t is a prefix of K.
+ int[] m = new int[t];
+ int i;
+ int j = 0;
+ for (i = 0, j = 0; i < t; i++)
+ m[i] = buffer[j++] << 24
+ | (buffer[j++] & 0xFF) << 16
+ | (buffer[j++] & 0xFF) << 8
+ | (buffer[j++] & 0xFF);
+ // Perform NH hash on the chunks, pairing words for multiplication
+ // which are 4 apart to accommodate vector-parallelism.
+ long result = len * 8L;
+ for (i = 0; i < t; i += 8)
+ {
+ result += ((m[i + 0] + key[i + 0]) & 0xFFFFFFFFL)
+ * ((m[i + 4] + key[i + 4]) & 0xFFFFFFFFL);
+ result += ((m[i + 1] + key[i + 1]) & 0xFFFFFFFFL)
+ * ((m[i + 5] + key[i + 5]) & 0xFFFFFFFFL);
+ result += ((m[i + 2] + key[i + 2]) & 0xFFFFFFFFL)
+ * ((m[i + 6] + key[i + 6]) & 0xFFFFFFFFL);
+ result += ((m[i + 3] + key[i + 3]) & 0xFFFFFFFFL)
+ * ((m[i + 7] + key[i + 7]) & 0xFFFFFFFFL);
+ }
+ return new byte[] {
+ (byte)(result >>> 56), (byte)(result >>> 48),
+ (byte)(result >>> 40), (byte)(result >>> 32),
+ (byte)(result >>> 24), (byte)(result >>> 16),
+ (byte)(result >>> 8), (byte) result };
+ }
+ }
+
+ /**
+ * Second hash stage of the UHash32 algorithm.
+ * <p>
+ * 5.4 L2-HASH-32: Second-layer hash.
+ * <ul>
+ * <li>Input:<br>
+ * K string of length 24 bytes.<br>
+ * M string of length less than 2^64 bytes.</li>
+ * <li>Returns:<br>
+ * Y, string of length 16 bytes.</li>
+ * </ul>
+ */
+ class L2Hash32
+ implements Cloneable
+ {
+ private BigInteger k64, k128;
+ private BigInteger y;
+ private boolean highBound;
+ private long bytesSoFar;
+ private ByteArrayOutputStream buffer;
+
+ L2Hash32(byte[] K)
+ {
+ super();
+
+ if (K.length != 24)
+ throw new ExceptionInInitializerError("K length is not 24");
+ // Extract keys and restrict to special key-sets
+ // Mask64 = uint2str(0x01FFFFFF01FFFFFF, 8);
+ // Mask128 = uint2str(0x01FFFFFF01FFFFFF01FFFFFF01FFFFFF, 16);
+ // k64 = str2uint(K[1..8] and Mask64);
+ // k128 = str2uint(K[9..24] and Mask128);
+ int i = 0;
+ k64 = new BigInteger(1, new byte[] {
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF) });
+ k128 = new BigInteger(1, new byte[] {
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF) });
+ y = BigInteger.ONE;
+ highBound = false;
+ bytesSoFar = 0L;
+ }
+
+ private L2Hash32(L2Hash32 that)
+ {
+ super();
+
+ this.k64 = that.k64;
+ this.k128 = that.k128;
+ this.y = that.y;
+ this.highBound = that.highBound;
+ this.bytesSoFar = that.bytesSoFar;
+ if (that.buffer != null)
+ {
+ byte[] thatbuffer = that.buffer.toByteArray();
+ this.buffer = new ByteArrayOutputStream();
+ this.buffer.write(thatbuffer, 0, thatbuffer.length);
+ }
+ }
+
+ public Object clone()
+ {
+ return new L2Hash32(this);
+ }
+
+ // this is called with either 8-bytes or 16-bytes
+ void update(byte[] b, int offset, int len)
+ {
+ if (len == 0)
+ return;
+
+ if (! highBound) // do the first (only?) 8-bytes
+ {
+ poly(64, LOWER_RANGE, k64, b, offset, 8);
+ bytesSoFar += 8L;
+ highBound = (bytesSoFar > BOUNDARY);
+ if (highBound) // if we just crossed the limit then process y
+ {
+ poly(128, UPPER_RANGE, k128, yTo16bytes(), 0, 16);
+ buffer = new ByteArrayOutputStream();
+ }
+ // do the rest if any
+ update(b, offset + 8, len - 8);
+ }
+ else
+ { // we're already beyond the 2**17 bytes size limit
+ // process in chuncks of 16
+ buffer.write(b, offset, len);
+ if (buffer.size() > 16)
+ {
+ byte[] bb = buffer.toByteArray();
+ poly(128, UPPER_RANGE, k128, bb, 0, 16);
+ if (bb.length > 16)
+ buffer.write(bb, 16, bb.length - 16);
+ }
+ }
+ }
+
+ byte[] digest()
+ {
+ // If M no more than 2^17 bytes, hash under 64-bit prime,
+ // otherwise, hash first 2^17 bytes under 64-bit prime and
+ // remainder under 128-bit prime.
+ if (! highBound) // y is up-to-date
+ {
+ // do nothing
+ }
+ else // we may have some bytes in buffer
+ {
+ byte[] bb = buffer.toByteArray();
+ byte[] lastBlock = new byte[16];
+ System.arraycopy(bb, 0, lastBlock, 0, bb.length);
+ lastBlock[bb.length] = (byte) 0x80;
+ poly(128, UPPER_RANGE, k128, lastBlock, 0, 16);
+ }
+ byte[] result = yTo16bytes();
+ reset();
+ return result;
+ }
+
+ void reset()
+ {
+ y = BigInteger.ONE;
+ highBound = false;
+ bytesSoFar = 0L;
+ if (buffer != null)
+ buffer.reset();
+ }
+
+ private byte[] yTo16bytes()
+ {
+ byte[] yy = y.toByteArray();
+ byte[] result = new byte[16];
+ if (yy.length > 16)
+ System.arraycopy(yy, yy.length - 16, result, 0, 16);
+ else
+ System.arraycopy(yy, 0, result, 16 - yy.length, yy.length);
+
+ return result;
+ }
+
+ /**
+ * 5.3 POLY: Polynomial hash Function Name: POLY
+ *
+ * @param wordbits positive integer divisible by 8: called with 64 or 128.
+ * @param maxwordrange positive integer less than 2**wordbits.
+ * @param k integer in the range 0 .. prime(wordbits) - 1.
+ * @param M string with length divisible by (wordbits / 8) bytes. return y,
+ * integer in the range 0 .. prime(wordbits) - 1.
+ */
+ private void poly(int wordbits, BigInteger maxwordrange, BigInteger k,
+ byte[] M, int off, int len)
+ {
+ byte[] mag = new byte[len];
+ System.arraycopy(M, off, mag, 0, len);
+ // Define constants used for fixing out-of-range words
+ BigInteger p = prime(wordbits);
+ BigInteger offset = TWO.pow(wordbits).subtract(p); // 2^wordbits - p;
+ BigInteger marker = p.subtract(BigInteger.ONE);
+ // Break M into chunks of length wordbytes bytes
+ // long n = M.length / wordbytes;
+ // Let M_1, M_2, ..., M_n be strings of length wordbytes bytes
+ // so that M = M_1 || M_2 || .. || M_n
+
+ // For each input word, compare it with maxwordrange. If larger
+ // then hash the words 'marker' and (m - offset), both in range.
+ // for (int i = 0; i < n; i++) {
+ BigInteger m = new BigInteger(1, mag);
+ if (m.compareTo(maxwordrange) >= 0) // m >= maxwordrange
+ {
+ y = y.multiply(k).add(marker).mod(p); // (k * y + marker) % p;
+ y = y.multiply(k).add(m.subtract(offset)).mod(p); // (k * y + (m - offset)) % p;
+ }
+ else
+ y = y.multiply(k).add(m).mod(p); // (k * y + m) % p;
+ }
+ }
+
+ /**
+ * Third hash stage of the UHash32 algorithm.
+ * <ul>
+ * <li>Input:<br/>
+ * K1 string of length 64 bytes.<br/>
+ * K2 string of length 4 bytes.<br/>
+ * M string of length 16 bytes.</li>
+ * <li>Returns:<br/>
+ * Y, string of length 4 bytes.</li>
+ * </ul>
+ */
+ class L3Hash32
+ implements Cloneable
+ {
+ private static final long PRIME_36 = 0x0000000FFFFFFFFBL;
+ private int[] k = new int[9];
+
+ /**
+ * @param K1 string of length 64 bytes.
+ * @param K2 string of length 4 bytes.
+ */
+ L3Hash32(byte[] K1, byte[] K2)
+ {
+ super();
+
+ // pre-conditions
+ if (K1.length != 64)
+ throw new ExceptionInInitializerError("K1 length is not 64");
+ if (K2.length != 4)
+ throw new ExceptionInInitializerError("K2 length is not 4");
+ // Break K1 into 8 chunks and convert to integers
+ for (int i = 0, j = 0; i < 8; i++)
+ {
+ long kk = (K1[j++] & 0xFFL) << 56
+ | (K1[j++] & 0xFFL) << 48
+ | (K1[j++] & 0xFFL) << 40
+ | (K1[j++] & 0xFFL) << 32
+ | (K1[j++] & 0xFFL) << 24
+ | (K1[j++] & 0xFFL) << 16
+ | (K1[j++] & 0xFFL) << 8
+ | (K1[j++] & 0xFFL);
+ k[i] = (int)(kk % PRIME_36);
+ }
+ k[8] = K2[0] << 24
+ | (K2[1] & 0xFF) << 16
+ | (K2[2] & 0xFF) << 8
+ | (K2[3] & 0xFF);
+ }
+
+ private L3Hash32(int[] k)
+ {
+ super();
+
+ this.k = k;
+ }
+
+ public Object clone()
+ {
+ return new L3Hash32((int[]) k.clone());
+ }
+
+ /**
+ * @param M string of length 16 bytes.
+ * @return Y, string of length 4 bytes.
+ */
+ byte[] digest(byte[] M)
+ {
+ if (M.length != 16)
+ throw new IllegalArgumentException("M length is not 16");
+
+ long m, y = 0L;
+ for (int i = 0, j = 0; i < 8; i++)
+ {
+ // Break M into 8 chunks and convert to integers
+ m = (M[j++] & 0xFFL) << 8 | (M[j++] & 0xFFL);
+ // Inner-product hash, extract last 32 bits and affine-translate
+ // y = (m_1 * k_1 + ... + m_8 * k_8) mod prime(36);
+ // y = y mod 2^32;
+ y += (m * (k[i] & 0xFFFFFFFFL)) % PRIME_36;
+ }
+ int Y = ((int) y) ^ k[8];
+ return new byte[] {
+ (byte)(Y >>> 24),
+ (byte)(Y >>> 16),
+ (byte)(Y >>> 8),
+ (byte) Y };
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UMac32.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UMac32.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UMac32.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mac/UMac32.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,418 @@
+/* UMac32.java --
+ 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.javax.crypto.mac;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.prng.UMacGenerator;
+
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The implementation of the <i>UMAC</i> (Universal Message Authentication
+ * Code).
+ * <p>
+ * The <i>UMAC</i> algorithms described are <i>parameterized</i>. This means
+ * that various low-level choices, like the endian convention and the underlying
+ * cryptographic primitive, have not been fixed. One must choose values for
+ * these parameters before the authentication tag generated by <i>UMAC</i> (for
+ * a given message, key, and nonce) becomes fully-defined. In this document we
+ * provide two collections of parameter settings, and have named the sets
+ * <i>UMAC16</i> and <i>UMAC32</i>. The parameter sets have been chosen based
+ * on experimentation and provide good performance on a wide variety of
+ * processors. <i>UMAC16</i> is designed to excel on processors which provide
+ * small-scale SIMD parallelism of the type found in Intel's MMX and Motorola's
+ * AltiVec instruction sets, while <i>UMAC32</i> is designed to do well on
+ * processors with good 32- and 64- bit support. <i>UMAC32</i> may take
+ * advantage of SIMD parallelism in future processors.
+ * <p>
+ * <i>UMAC</i> has been designed to allow implementations which accommodate
+ * <i>on-line</i> authentication. This means that pieces of the message may be
+ * presented to <i>UMAC</i> at different times (but in correct order) and an
+ * on-line implementation will be able to process the message correctly without
+ * the need to buffer more than a few dozen bytes of the message. For
+ * simplicity, the algorithms in this specification are presented as if the
+ * entire message being authenticated were available at once.
+ * <p>
+ * To authenticate a message, <code>Msg</code>, one first applies the
+ * universal hash function, resulting in a string which is typically much
+ * shorter than the original message. The pseudorandom function is applied to a
+ * nonce, and the result is used in the manner of a Vernam cipher: the
+ * authentication tag is the xor of the output from the hash function and the
+ * output from the pseudorandom function. Thus, an authentication tag is
+ * generated as
+ * <pre>
+ * AuthTag = f(Nonce) xor h(Msg)
+ * </pre>
+ * <p>
+ * Here <code>f</code> is the pseudorandom function shared between the sender
+ * and the receiver, and h is a universal hash function shared by the sender and
+ * the receiver. In <i>UMAC</i>, a shared key is used to key the pseudorandom
+ * function <code>f</code>, and then <code>f</code> is used for both tag
+ * generation and internally to generate all of the bits needed by the universal
+ * hash function.
+ * <p>
+ * The universal hash function that we use is called <code>UHASH</code>. It
+ * combines several software-optimized algorithms into a multi-layered
+ * structure. The algorithm is moderately complex. Some of this complexity comes
+ * from extensive speed optimizations.
+ * <p>
+ * For the pseudorandom function we use the block cipher of the <i>Advanced
+ * Encryption Standard</i> (AES).
+ * <p>
+ * The UMAC32 parameters, considered in this implementation are:
+ * <pre>
+ * UMAC32
+ * ------
+ * WORD-LEN 4
+ * UMAC-OUTPUT-LEN 8
+ * L1-KEY-LEN 1024
+ * UMAC-KEY-LEN 16
+ * ENDIAN-FAVORITE BIG *
+ * L1-OPERATIONS-SIGN UNSIGNED
+ * </pre>
+ * <p>
+ * Please note that this UMAC32 differs from the one described in the paper by
+ * the <i>ENDIAN-FAVORITE</i> value.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">
+ * UMAC</a>: Message Authentication Code using Universal Hashing.<br>
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.</li>
+ * </ol>
+ */
+public class UMac32
+ extends BaseMac
+{
+ /**
+ * Property name of the user-supplied <i>Nonce</i>. The value associated to
+ * this property name is taken to be a byte array.
+ */
+ public static final String NONCE_MATERIAL = "gnu.crypto.umac.nonce.material";
+ /** Known test vector. */
+ // private static final String TV1 = "3E5A0E09198B0F94";
+ // private static final String TV1 = "5FD764A6D3A9FD9D";
+ // private static final String TV1 = "48658DE1D9A70304";
+ private static final String TV1 = "455ED214A6909F20";
+ private static final BigInteger MAX_NONCE_ITERATIONS = BigInteger.ONE.shiftLeft(16 * 8);
+ // UMAC32 parameters
+ static final int OUTPUT_LEN = 8;
+ static final int L1_KEY_LEN = 1024;
+ static final int KEY_LEN = 16;
+ /** caches the result of the correctness test, once executed. */
+ private static Boolean valid;
+ private byte[] nonce;
+ private UHash32 uhash32;
+ private BigInteger nonceReuseCount;
+ /** The authentication key for this instance. */
+ private transient byte[] K;
+
+ /** Trivial 0-arguments constructor. */
+ public UMac32()
+ {
+ super("umac32");
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the instance to clone.
+ */
+ private UMac32(UMac32 that)
+ {
+ this();
+
+ if (that.K != null)
+ this.K = (byte[]) that.K.clone();
+ if (that.nonce != null)
+ this.nonce = (byte[]) that.nonce.clone();
+ if (that.uhash32 != null)
+ this.uhash32 = (UHash32) that.uhash32.clone();
+ this.nonceReuseCount = that.nonceReuseCount;
+ }
+
+ public Object clone()
+ {
+ return new UMac32(this);
+ }
+
+ public int macSize()
+ {
+ return OUTPUT_LEN;
+ }
+
+ /**
+ * Initialising a <i>UMAC</i> instance consists of defining values for the
+ * following parameters:
+ * <ol>
+ * <li>Key Material: as the value of the attribute entry keyed by
+ * {@link #MAC_KEY_MATERIAL}. The value is taken to be a byte array
+ * containing the user-specified key material. The length of this array,
+ * if/when defined SHOULD be exactly equal to {@link #KEY_LEN}.</li>
+ * <li>Nonce Material: as the value of the attribute entry keyed by
+ * {@link #NONCE_MATERIAL}. The value is taken to be a byte array containing
+ * the user-specified nonce material. The length of this array, if/when
+ * defined SHOULD be (a) greater than zero, and (b) less or equal to 16 (the
+ * size of the AES block).</li>
+ * </ol>
+ * <p>
+ * For convenience, this implementation accepts that not both parameters be
+ * always specified.
+ * <ul>
+ * <li>If the <i>Key Material</i> is specified, but the <i>Nonce Material</i>
+ * is not, then this implementation, re-uses the previously set <i>Nonce
+ * Material</i> after (a) converting the bytes to an unsigned integer, (b)
+ * incrementing the number by one, and (c) converting it back to 16 bytes.</li>
+ * <li>If the <i>Nonce Material</i> is specified, but the <i>Key Material</i>
+ * is not, then this implementation re-uses the previously set <i>Key Material</i>.
+ * </li>
+ * </ul>
+ * <p>
+ * This method throws an exception if no <i>Key Material</i> is specified in
+ * the input map, and there is no previously set/defined <i>Key Material</i>
+ * (from an earlier invocation of this method). If a <i>Key Material</i> can
+ * be used, but no <i>Nonce Material</i> is defined or previously
+ * set/defined, then a default value of all-zeroes shall be used.
+ *
+ * @param attributes one or both of required parameters.
+ * @throws InvalidKeyException the key material specified is not of the
+ * correct length.
+ */
+ public void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException
+ {
+ byte[] key = (byte[]) attributes.get(MAC_KEY_MATERIAL);
+ byte[] n = (byte[]) attributes.get(NONCE_MATERIAL);
+ boolean newKey = (key != null);
+ boolean newNonce = (n != null);
+ if (newKey)
+ {
+ if (key.length != KEY_LEN)
+ throw new InvalidKeyException("Key length: "
+ + String.valueOf(key.length));
+ K = key;
+ }
+ else
+ {
+ if (K == null)
+ throw new InvalidKeyException("Null Key");
+ }
+ if (newNonce)
+ {
+ if (n.length < 1 || n.length > 16)
+ throw new IllegalArgumentException("Invalid Nonce length: "
+ + String.valueOf(n.length));
+ if (n.length < 16) // pad with zeroes
+ {
+ byte[] newN = new byte[16];
+ System.arraycopy(n, 0, newN, 0, n.length);
+ nonce = newN;
+ }
+ else
+ nonce = n;
+
+ nonceReuseCount = BigInteger.ZERO;
+ }
+ else if (nonce == null) // use all-0 nonce if 1st time
+ {
+ nonce = new byte[16];
+ nonceReuseCount = BigInteger.ZERO;
+ }
+ else if (! newKey) // increment nonce if still below max count
+ {
+ nonceReuseCount = nonceReuseCount.add(BigInteger.ONE);
+ if (nonceReuseCount.compareTo(MAX_NONCE_ITERATIONS) >= 0)
+ {
+ // limit reached. we SHOULD have a key
+ throw new InvalidKeyException("Null Key and unusable old Nonce");
+ }
+ BigInteger N = new BigInteger(1, nonce);
+ N = N.add(BigInteger.ONE).mod(MAX_NONCE_ITERATIONS);
+ n = N.toByteArray();
+ if (n.length == 16)
+ nonce = n;
+ else if (n.length < 16)
+ {
+ nonce = new byte[16];
+ System.arraycopy(n, 0, nonce, 16 - n.length, n.length);
+ }
+ else
+ {
+ nonce = new byte[16];
+ System.arraycopy(n, n.length - 16, nonce, 0, 16);
+ }
+ }
+ else // do nothing, re-use old nonce value
+ nonceReuseCount = BigInteger.ZERO;
+
+ if (uhash32 == null)
+ uhash32 = new UHash32();
+
+ Map map = new HashMap();
+ map.put(MAC_KEY_MATERIAL, K);
+ uhash32.init(map);
+ }
+
+ public void update(byte b)
+ {
+ uhash32.update(b);
+ }
+
+ public void update(byte[] b, int offset, int len)
+ {
+ uhash32.update(b, offset, len);
+ }
+
+ public byte[] digest()
+ {
+ byte[] result = uhash32.digest();
+ byte[] pad = pdf(); // pdf(K, nonce);
+ for (int i = 0; i < OUTPUT_LEN; i++)
+ result[i] = (byte)(result[i] ^ pad[i]);
+
+ return result;
+ }
+
+ public void reset()
+ {
+ if (uhash32 != null)
+ uhash32.reset();
+ }
+
+ public boolean selfTest()
+ {
+ if (valid == null)
+ {
+ byte[] key;
+ try
+ {
+ key = "abcdefghijklmnop".getBytes("ASCII");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new RuntimeException("ASCII not supported");
+ }
+ byte[] nonce = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
+ UMac32 mac = new UMac32();
+ Map attributes = new HashMap();
+ attributes.put(MAC_KEY_MATERIAL, key);
+ attributes.put(NONCE_MATERIAL, nonce);
+ try
+ {
+ mac.init(attributes);
+ }
+ catch (InvalidKeyException x)
+ {
+ x.printStackTrace(System.err);
+ return false;
+ }
+ byte[] data = new byte[128];
+ data[0] = (byte) 0x80;
+ mac.update(data, 0, 128);
+ byte[] result = mac.digest();
+ valid = Boolean.valueOf(TV1.equals(Util.toString(result)));
+ }
+ return valid.booleanValue();
+ }
+
+ /**
+ * @return byte array of length 8 (or OUTPUT_LEN) bytes.
+ */
+ private byte[] pdf()
+ {
+ // Make Nonce 16 bytes by prepending zeroes. done (see init())
+ // one AES invocation is enough for more than one PDF invocation
+ // number of index bits needed = 1
+ // Extract index bits and zero low bits of Nonce
+ BigInteger Nonce = new BigInteger(1, nonce);
+ int nlowbitsnum = Nonce.testBit(0) ? 1 : 0;
+ Nonce = Nonce.clearBit(0);
+ // Generate subkey, AES and extract indexed substring
+ IRandom kdf = new UMacGenerator();
+ Map map = new HashMap();
+ map.put(IBlockCipher.KEY_MATERIAL, K);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(128));
+ kdf.init(map);
+ byte[] Kp = new byte[KEY_LEN];
+ try
+ {
+ kdf.nextBytes(Kp, 0, KEY_LEN);
+ }
+ catch (IllegalStateException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException(String.valueOf(x));
+ }
+ catch (LimitReachedException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException(String.valueOf(x));
+ }
+ IBlockCipher aes = CipherFactory.getInstance(Registry.AES_CIPHER);
+ map.put(IBlockCipher.KEY_MATERIAL, Kp);
+ try
+ {
+ aes.init(map);
+ }
+ catch (InvalidKeyException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException(String.valueOf(x));
+ }
+ catch (IllegalStateException x)
+ {
+ x.printStackTrace(System.err);
+ throw new RuntimeException(String.valueOf(x));
+ }
+ byte[] T = new byte[16];
+ aes.encryptBlock(nonce, 0, T, 0);
+ byte[] result = new byte[OUTPUT_LEN];
+ System.arraycopy(T, nlowbitsnum, result, 0, OUTPUT_LEN);
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/BaseMode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/BaseMode.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/BaseMode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/BaseMode.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,293 @@
+/* BaseMode.java --
+ 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.javax.crypto.mode;
+
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.security.InvalidKeyException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A basic abstract class to facilitate implementing block cipher modes of
+ * operations.
+ */
+public abstract class BaseMode
+ implements IMode
+{
+ /** The canonical name prefix of this mode. */
+ protected String name;
+ /** The state indicator of this instance. */
+ protected int state;
+ /** The underlying block cipher implementation. */
+ protected IBlockCipher cipher;
+ /** The block size, in bytes, to operate the underlying block cipher in. */
+ protected int cipherBlockSize;
+ /** The block size, in bytes, in which to operate the mode instance. */
+ protected int modeBlockSize;
+ /** The initialisation vector value. */
+ protected byte[] iv;
+ /** The instance lock. */
+ protected Object lock = new Object();
+
+ /**
+ * Trivial constructor for use by concrete subclasses.
+ *
+ * @param name the canonical name prefix of this mode.
+ * @param underlyingCipher the implementation of the underlying cipher.
+ * @param cipherBlockSize the block size, in bytes, in which to operate the
+ * underlying cipher.
+ */
+ protected BaseMode(String name, IBlockCipher underlyingCipher,
+ int cipherBlockSize)
+ {
+ super();
+
+ this.name = name;
+ this.cipher = underlyingCipher;
+ this.cipherBlockSize = cipherBlockSize;
+ state = -1;
+ }
+
+ public void update(byte[] in, int inOffset, byte[] out, int outOffset)
+ throws IllegalStateException
+ {
+ synchronized (lock)
+ {
+ switch (state)
+ {
+ case ENCRYPTION:
+ encryptBlock(in, inOffset, out, outOffset);
+ break;
+ case DECRYPTION:
+ decryptBlock(in, inOffset, out, outOffset);
+ break;
+ default:
+ throw new IllegalStateException();
+ }
+ }
+ }
+
+ public String name()
+ {
+ return new StringBuffer(name).append('(').append(cipher.name()).append(')')
+ .toString();
+ }
+
+ /**
+ * Returns the default value, in bytes, of the mode's block size. This value
+ * is part of the construction arguments passed to the Factory methods in
+ * {@link ModeFactory}. Unless changed by an invocation of any of the
+ * <code>init()</code> methods, a <i>Mode</i> instance would operate with
+ * the same block size as its underlying block cipher. As mentioned earlier,
+ * the block size of the underlying block cipher itself is specified in one of
+ * the method(s) available in the factory class.
+ *
+ * @return the default value, in bytes, of the mode's block size.
+ * @see ModeFactory
+ */
+ public int defaultBlockSize()
+ {
+ return cipherBlockSize;
+ }
+
+ /**
+ * Returns the default value, in bytes, of the underlying block cipher key
+ * size.
+ *
+ * @return the default value, in bytes, of the underlying cipher's key size.
+ */
+ public int defaultKeySize()
+ {
+ return cipher.defaultKeySize();
+ }
+
+ /**
+ * Returns an {@link Iterator} over the supported block sizes. Each element
+ * returned by this object is an {@link Integer}.
+ * <p>
+ * The default behaviour is to return an iterator with just one value, which
+ * is that currently configured for the underlying block cipher. Concrete
+ * implementations may override this behaviour to signal their ability to
+ * support other values.
+ *
+ * @return an {@link Iterator} over the supported block sizes.
+ */
+ public Iterator blockSizes()
+ {
+ ArrayList al = new ArrayList();
+ al.add(Integer.valueOf(cipherBlockSize));
+ return Collections.unmodifiableList(al).iterator();
+ }
+
+ /**
+ * Returns an {@link Iterator} over the supported underlying block cipher key
+ * sizes. Each element returned by this object is an instance of
+ * {@link Integer}.
+ *
+ * @return an {@link Iterator} over the supported key sizes.
+ */
+ public Iterator keySizes()
+ {
+ return cipher.keySizes();
+ }
+
+ public void init(Map attributes) throws InvalidKeyException,
+ IllegalStateException
+ {
+ synchronized (lock)
+ {
+ if (state != -1)
+ throw new IllegalStateException();
+ Integer want = (Integer) attributes.get(STATE);
+ if (want != null)
+ {
+ switch (want.intValue())
+ {
+ case ENCRYPTION:
+ state = ENCRYPTION;
+ break;
+ case DECRYPTION:
+ state = DECRYPTION;
+ break;
+ default:
+ throw new IllegalArgumentException();
+ }
+ }
+ Integer bs = (Integer) attributes.get(MODE_BLOCK_SIZE);
+ modeBlockSize = (bs == null ? cipherBlockSize : bs.intValue());
+ byte[] iv = (byte[]) attributes.get(IV);
+ if (iv != null)
+ this.iv = (byte[]) iv.clone();
+ else
+ this.iv = new byte[modeBlockSize];
+ cipher.init(attributes);
+ setup();
+ }
+ }
+
+ public int currentBlockSize()
+ {
+ if (state == -1)
+ throw new IllegalStateException();
+ return modeBlockSize;
+ }
+
+ public void reset()
+ {
+ synchronized (lock)
+ {
+ state = -1;
+ iv = null;
+ cipher.reset();
+ teardown();
+ }
+ }
+
+ public boolean selfTest()
+ {
+ int ks;
+ Iterator bit;
+ for (Iterator kit = keySizes(); kit.hasNext();)
+ {
+ ks = ((Integer) kit.next()).intValue();
+ for (bit = blockSizes(); bit.hasNext();)
+ if (! testSymmetry(ks, ((Integer) bit.next()).intValue()))
+ return false;
+ }
+ return true;
+ }
+
+ public abstract Object clone();
+
+ /** The initialisation phase of the concrete mode implementation. */
+ public abstract void setup();
+
+ /** The termination phase of the concrete mode implementation. */
+ public abstract void teardown();
+
+ public abstract void encryptBlock(byte[] in, int i, byte[] out, int o);
+
+ public abstract void decryptBlock(byte[] in, int i, byte[] out, int o);
+
+ private boolean testSymmetry(int ks, int bs)
+ {
+ try
+ {
+ IMode mode = (IMode) this.clone();
+ byte[] iv = new byte[cipherBlockSize]; // all zeroes
+ byte[] k = new byte[ks];
+ int i;
+ for (i = 0; i < ks; i++)
+ k[i] = (byte) i;
+ int blockCount = 5;
+ int limit = blockCount * bs;
+ byte[] pt = new byte[limit];
+ for (i = 0; i < limit; i++)
+ pt[i] = (byte) i;
+ byte[] ct = new byte[limit];
+ byte[] cpt = new byte[limit];
+ Map map = new HashMap();
+ map.put(KEY_MATERIAL, k);
+ map.put(CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
+ map.put(STATE, Integer.valueOf(ENCRYPTION));
+ map.put(IV, iv);
+ map.put(MODE_BLOCK_SIZE, Integer.valueOf(bs));
+ mode.reset();
+ mode.init(map);
+ for (i = 0; i < blockCount; i++)
+ mode.update(pt, i * bs, ct, i * bs);
+ mode.reset();
+ map.put(STATE, Integer.valueOf(DECRYPTION));
+ mode.init(map);
+ for (i = 0; i < blockCount; i++)
+ mode.update(ct, i * bs, cpt, i * bs);
+ return Arrays.equals(pt, cpt);
+ }
+ catch (Exception x)
+ {
+ x.printStackTrace(System.err);
+ return false;
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CBC.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CBC.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CBC.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CBC.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,123 @@
+/* CBC.java --
+ Copyright (C) 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+/**
+ * The Cipher Block Chaining mode. This mode introduces feedback into the cipher
+ * by XORing the previous ciphertext block with the plaintext block before
+ * encipherment. That is, encrypting looks like this:
+ *
+ * <pre>
+ * C<sub>i</sub> = E<sub>K</sub>(P<sub>i</sub>ˆ C<sub>i-1</sub>)
+ * </pre>
+ * <p>
+ * Similarly, decrypting is:
+ * <pre>
+ * P<sub>i</sub> = C<sub>i-1</sub> ˆ D<sub>K</sub>(C<sub>i</sub>)
+ * </pre>
+ */
+public class CBC
+ extends BaseMode
+ implements Cloneable
+{
+ /** The last (de|en)crypted block */
+ private byte[] lastBlock;
+ /** An intermediate buffer. */
+ private byte[] scratch;
+
+ /**
+ * Package-private constructor for the factory class.
+ *
+ * @param underlyingCipher The cipher implementation.
+ * @param cipherBlockSize The cipher's block size.
+ */
+ CBC(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.CBC_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /** Our constructor for cloning. */
+ private CBC(CBC that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new CBC(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize != cipherBlockSize)
+ throw new IllegalArgumentException();
+ scratch = new byte[cipherBlockSize];
+ lastBlock = new byte[cipherBlockSize];
+ // lastBlock gets initialized to the initialization vector.
+ for (int i = 0; i < lastBlock.length && i < iv.length; i++)
+ lastBlock[i] = iv[i];
+ }
+
+ public void teardown()
+ {
+ lastBlock = null;
+ scratch = null;
+ }
+
+ public void encryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ for (int k = 0; k < scratch.length; k++)
+ scratch[k] = (byte)(lastBlock[k] ^ in[k + i]);
+ cipher.encryptBlock(scratch, 0, out, o);
+ System.arraycopy(out, o, lastBlock, 0, cipherBlockSize);
+ }
+
+ public void decryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ byte[] buf = new byte[cipherBlockSize];
+ System.arraycopy(in, i, buf, 0, cipherBlockSize);
+ cipher.decryptBlock(in, i, scratch, 0);
+ for (int k = 0; k < scratch.length; k++)
+ out[o + k] = (byte)(lastBlock[k] ^ scratch[k]);
+ System.arraycopy(buf, 0, lastBlock, 0, cipherBlockSize);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CFB.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CFB.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CFB.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CFB.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,155 @@
+/* CFB.java --
+ Copyright (C) 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+/**
+ * The cipher feedback mode. CFB mode is a stream mode that operates on <i>s</i>
+ * bit blocks, where 1 <= <i>s</i> <= <i>b</i>, if <i>b</i> is the
+ * underlying cipher's block size. Encryption is:
+ * <pre>
+ * I[1] = IV
+ * I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n
+ * O[j] = CIPH(K, I[j]) for j = 1,2...n
+ * C[j] = P[j] ˆ MSB(s, O[j]) for j = 1,2...n
+ * </pre>
+ * <p>
+ * And decryption is:
+ * <pre>
+ * I[1] = IV
+ * I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n
+ * O[j] = CIPH(K, I[j]) for j = 1,2...n
+ * P[j] = C[j] ˆ MSB(s, O[j]) for j = 1,2...n
+ * </pre>
+ * <p>
+ * CFB mode requires an initialization vector, which need not be kept secret.
+ * <p>
+ * References:
+ * <ol>
+ * <li>Bruce Schneier, <i>Applied Cryptography: Protocols, Algorithms, and
+ * Source Code in C, Second Edition</i>. (1996 John Wiley and Sons) ISBN
+ * 0-471-11709-9.</li>
+ * <li><a
+ * href="http://csrc.nist.gov/encryption/modes/Recommendation/Modes01.pdf">
+ * Recommendation for Block Cipher Modes of Operation Methods and Techniques</a>,
+ * Morris Dworkin.</li>
+ * </ol>
+ */
+public class CFB
+ extends BaseMode
+{
+ /** The shift register, the input block to the block cipher. */
+ private byte[] shiftRegister;
+ /** The output block from the block cipher. */
+ private byte[] scratch;
+
+ /**
+ * Package-private constructor for the factory class.
+ *
+ * @param underlyingCipher The cipher implementation.
+ * @param cipherBlockSize The cipher's block size.
+ */
+ CFB(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.CFB_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /**
+ * Cloneing constructor.
+ *
+ * @param that The instance being cloned.
+ */
+ private CFB(CFB that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new CFB(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize > cipherBlockSize)
+ throw new IllegalArgumentException(
+ "CFB block size cannot be larger than the cipher block size");
+ shiftRegister = new byte[cipherBlockSize];
+ scratch = new byte[cipherBlockSize];
+ System.arraycopy(iv, 0,
+ shiftRegister, 0,
+ Math.min(iv.length, cipherBlockSize));
+ }
+
+ public void teardown()
+ {
+ if (shiftRegister != null)
+ for (int i = 0; i < shiftRegister.length; i++)
+ shiftRegister[i] = 0;
+ shiftRegister = null;
+ }
+
+ public void encryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ cipher.encryptBlock(shiftRegister, 0, scratch, 0);
+ for (int i = 0; i < modeBlockSize; i++)
+ out[outOffset + i] = (byte)(in[inOffset + i] ^ scratch[i]);
+ System.arraycopy(shiftRegister, modeBlockSize,
+ shiftRegister, 0,
+ cipherBlockSize - modeBlockSize);
+ System.arraycopy(out, outOffset,
+ shiftRegister, cipherBlockSize - modeBlockSize,
+ modeBlockSize);
+ }
+
+ public void decryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ cipher.encryptBlock(shiftRegister, 0, scratch, 0);
+ for (int i = 0; i < modeBlockSize; i++)
+ out[outOffset + i] = (byte)(in[inOffset + i] ^ scratch[i]);
+ System.arraycopy(shiftRegister, modeBlockSize,
+ shiftRegister, 0,
+ cipherBlockSize - modeBlockSize);
+ System.arraycopy(in, inOffset,
+ shiftRegister, cipherBlockSize - modeBlockSize,
+ modeBlockSize);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CTR.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CTR.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CTR.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/CTR.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,168 @@
+/* CTR.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Sequence;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+/**
+ * The implementation of the Counter Mode.
+ * <p>
+ * The algorithm steps are formally described as follows:
+ *
+ * <pre>
+ * CTR Encryption: O[j] = E(K)(T[j]); for j = 1, 2...n;
+ * C[j] = P[j] ˆ O[j]; for j = 1, 2...n.
+ * CTR Decryption: O[j] = E(K)(T[j]); for j = 1, 2...n;
+ * P[j] = C[j] ˆ O[j]; for j = 1, 2...n.
+ * </pre>
+ *
+ * <p>
+ * where <code>P</code> is the plaintext, <code>C</code> is the ciphertext,
+ * <code>E(K)</code> is the underlying block cipher encryption function
+ * parametrised with the session key <code>K</code>, and <code>T</code> is
+ * the <i>Counter</i>.
+ * <p>
+ * This implementation, uses a standard incrementing function with a step of 1,
+ * and an initial value similar to that described in the NIST document.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://csrc.nist.gov/encryption/modes/Recommendation/Modes01.pdf">
+ * Recommendation for Block Cipher Modes of Operation Methods and Techniques</a>,
+ * Morris Dworkin.</li>
+ * </ol>
+ */
+public class CTR
+ extends BaseMode
+ implements Cloneable
+{
+ private int off;
+ private byte[] counter, enc;
+
+ /**
+ * Trivial package-private constructor for use by the Factory class.
+ *
+ * @param underlyingCipher the underlying cipher implementation.
+ * @param cipherBlockSize the underlying cipher block size to use.
+ */
+ CTR(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.CTR_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the instance to clone.
+ */
+ private CTR(CTR that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new CTR(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize > cipherBlockSize)
+ throw new IllegalArgumentException("mode size exceeds cipher block size");
+ off = 0;
+ counter = new byte[cipherBlockSize];
+ int i = cipherBlockSize - 1;
+ int j = iv.length - 1;
+ while (i >= 0 && j >= 0)
+ counter[i--] = iv[j--];
+ enc = new byte[cipherBlockSize];
+ cipher.encryptBlock(counter, 0, enc, 0);
+ }
+
+ public void teardown()
+ {
+ if (counter != null)
+ Arrays.fill(counter, (byte) 0);
+ if (enc != null)
+ Arrays.fill(enc, (byte) 0);
+ }
+
+ public void encryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ ctr(in, i, out, o);
+ }
+
+ public void decryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ ctr(in, i, out, o);
+ }
+
+ public Iterator blockSizes()
+ {
+ return new Sequence(1, cipherBlockSize).iterator();
+ }
+
+ private void ctr(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ for (int i = 0; i < modeBlockSize; i++)
+ {
+ out[outOffset++] = (byte)(in[inOffset++] ^ enc[off++]);
+ if (off == cipherBlockSize)
+ {
+ int j;
+ for (j = cipherBlockSize - 1; j >= 0; j--)
+ {
+ counter[j]++;
+ if ((counter[j] & 0xFF) != 0)
+ break;
+ }
+ if (j == 0)
+ counter[cipherBlockSize - 1]++;
+ off = 0;
+ cipher.encryptBlock(counter, 0, enc, 0);
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/EAX.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/EAX.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/EAX.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/EAX.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,289 @@
+/* EAX.java --
+ 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A conventional two-pass authenticated-encrypted mode, EAX. EAX is a
+ * <i>Authenticated Encryption with Additional Data</i> (<b>AEAD</b>) scheme,
+ * which provides protection and authentication for the message, and provides
+ * authentication of an (optional) header. EAX is composed of the counter mode
+ * (CTR) and the one-key CBC MAC (OMAC).
+ * <p>
+ * This class makes full use of the {@link IAuthenticatedMode} interface, that
+ * is, all methods of both {@link IMode} and {@link IMac} can be used as
+ * specified in the {@link IAuthenticatedMode} interface.
+ * <p>
+ * References:
+ * <ol>
+ * <li>M. Bellare, P. Rogaway, and D. Wagner; <a
+ * href="http://www.cs.berkeley.edu/~daw/papers/eprint-short-ae.pdf">A
+ * Conventional Authenticated-Encryption Mode</a>.</li>
+ * </ol>
+ */
+public class EAX
+ implements IAuthenticatedMode
+{
+ /** The tag size, in bytes. */
+ private int tagSize;
+ /** The nonce OMAC instance. */
+ private IMac nonceOmac;
+ /** The header OMAC instance. */
+ private IMac headerOmac;
+ /** The message OMAC instance. */
+ private IMac msgOmac;
+ /** The CTR instance. */
+ private IMode ctr;
+ /** The direction state (encrypting or decrypting). */
+ private int state;
+ /** Whether we're initialized or not. */
+ private boolean init;
+ /** The cipher block size. */
+ private int cipherBlockSize;
+ /** The cipher. */
+ private IBlockCipher cipher;
+ /** The [t]_n array. */
+ private byte[] t_n;
+ private static boolean valid = false;
+
+ public EAX(IBlockCipher cipher, int cipherBlockSize)
+ {
+ this.cipher = cipher;
+ this.cipherBlockSize = cipherBlockSize;
+ String name = cipher.name();
+ int i = name.indexOf('-');
+ if (i >= 0)
+ name = name.substring(0, i);
+ String omacname = Registry.OMAC_PREFIX + name;
+ nonceOmac = MacFactory.getInstance(omacname);
+ headerOmac = MacFactory.getInstance(omacname);
+ msgOmac = MacFactory.getInstance(omacname);
+ ctr = ModeFactory.getInstance(Registry.CTR_MODE, cipher, cipherBlockSize);
+ t_n = new byte[cipherBlockSize];
+ init = false;
+ }
+
+ public Object clone()
+ {
+ return new EAX((IBlockCipher) cipher.clone(), cipherBlockSize);
+ }
+
+ public String name()
+ {
+ return Registry.EAX_MODE + "(" + cipher.name() + ")";
+ }
+
+ public int defaultBlockSize()
+ {
+ return ctr.defaultBlockSize();
+ }
+
+ public int defaultKeySize()
+ {
+ return ctr.defaultKeySize();
+ }
+
+ public Iterator blockSizes()
+ {
+ return ctr.blockSizes();
+ }
+
+ public Iterator keySizes()
+ {
+ return ctr.keySizes();
+ }
+
+ public void init(Map attrib) throws InvalidKeyException
+ {
+ byte[] nonce = (byte[]) attrib.get(IV);
+ if (nonce == null)
+ throw new IllegalArgumentException("no nonce provided");
+ byte[] key = (byte[]) attrib.get(KEY_MATERIAL);
+ if (key == null)
+ throw new IllegalArgumentException("no key provided");
+
+ Arrays.fill(t_n, (byte) 0);
+ nonceOmac.reset();
+ nonceOmac.init(Collections.singletonMap(MAC_KEY_MATERIAL, key));
+ nonceOmac.update(t_n, 0, t_n.length);
+ nonceOmac.update(nonce, 0, nonce.length);
+ byte[] N = nonceOmac.digest();
+ nonceOmac.reset();
+ nonceOmac.update(t_n, 0, t_n.length);
+ nonceOmac.update(nonce, 0, nonce.length);
+ t_n[t_n.length - 1] = 1;
+ headerOmac.reset();
+ headerOmac.init(Collections.singletonMap(MAC_KEY_MATERIAL, key));
+ headerOmac.update(t_n, 0, t_n.length);
+ t_n[t_n.length - 1] = 2;
+ msgOmac.reset();
+ msgOmac.init(Collections.singletonMap(MAC_KEY_MATERIAL, key));
+ msgOmac.update(t_n, 0, t_n.length);
+ Integer modeSize = (Integer) attrib.get(MODE_BLOCK_SIZE);
+ if (modeSize == null)
+ modeSize = Integer.valueOf(cipherBlockSize);
+ HashMap ctrAttr = new HashMap();
+ ctrAttr.put(KEY_MATERIAL, key);
+ ctrAttr.put(IV, N);
+ ctrAttr.put(STATE, Integer.valueOf(ENCRYPTION));
+ ctrAttr.put(MODE_BLOCK_SIZE, modeSize);
+ ctr.reset();
+ ctr.init(ctrAttr);
+ Integer st = (Integer) attrib.get(STATE);
+ if (st != null)
+ {
+ state = st.intValue();
+ if (state != ENCRYPTION && state != DECRYPTION)
+ throw new IllegalArgumentException("invalid state");
+ }
+ else
+ state = ENCRYPTION;
+
+ Integer ts = (Integer) attrib.get(TRUNCATED_SIZE);
+ if (ts != null)
+ tagSize = ts.intValue();
+ else
+ tagSize = cipherBlockSize;
+ if (tagSize < 0 || tagSize > cipherBlockSize)
+ throw new IllegalArgumentException("tag size out of range");
+ init = true;
+ }
+
+ public int currentBlockSize()
+ {
+ return ctr.currentBlockSize();
+ }
+
+ public void encryptBlock(byte[] in, int inOff, byte[] out, int outOff)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ if (state != ENCRYPTION)
+ throw new IllegalStateException("not encrypting");
+ ctr.update(in, inOff, out, outOff);
+ msgOmac.update(out, outOff, ctr.currentBlockSize());
+ }
+
+ public void decryptBlock(byte[] in, int inOff, byte[] out, int outOff)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ if (state != DECRYPTION)
+ throw new IllegalStateException("not decrypting");
+ msgOmac.update(in, inOff, ctr.currentBlockSize());
+ ctr.update(in, inOff, out, outOff);
+ }
+
+ public void update(byte[] in, int inOff, byte[] out, int outOff)
+ {
+ switch (state)
+ {
+ case ENCRYPTION:
+ encryptBlock(in, inOff, out, outOff);
+ break;
+ case DECRYPTION:
+ decryptBlock(in, inOff, out, outOff);
+ break;
+ default:
+ throw new IllegalStateException("impossible state " + state);
+ }
+ }
+
+ public void reset()
+ {
+ nonceOmac.reset();
+ headerOmac.reset();
+ msgOmac.reset();
+ ctr.reset();
+ }
+
+ public boolean selfTest()
+ {
+ return true; // XXX
+ }
+
+ public int macSize()
+ {
+ return tagSize;
+ }
+
+ public byte[] digest()
+ {
+ byte[] tag = new byte[tagSize];
+ digest(tag, 0);
+ return tag;
+ }
+
+ public void digest(byte[] out, int outOffset)
+ {
+ if (outOffset < 0 || outOffset + tagSize > out.length)
+ throw new IndexOutOfBoundsException();
+ byte[] N = nonceOmac.digest();
+ byte[] H = headerOmac.digest();
+ byte[] M = msgOmac.digest();
+ for (int i = 0; i < tagSize; i++)
+ out[outOffset + i] = (byte)(N[i] ^ H[i] ^ M[i]);
+ reset();
+ }
+
+ public void update(byte b)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ headerOmac.update(b);
+ }
+
+ public void update(byte[] buf, int off, int len)
+ {
+ if (! init)
+ throw new IllegalStateException("not initialized");
+ headerOmac.update(buf, off, len);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ECB.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ECB.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ECB.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ECB.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,121 @@
+/* ECB.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+/**
+ * The implementation of the Electronic Codebook mode.
+ * <p>
+ * The Electronic Codebook (ECB) mode is a confidentiality mode that is defined
+ * as follows:
+ * <ul>
+ * <li>ECB Encryption: C<sub>j</sub> = CIPH<sub>K</sub>(P<sub>j</sub>)
+ * for j = 1...n</li>
+ * <li>ECB Decryption: P<sub>j</sub> = CIPH<sup>-1</sup><sub>K</sub>(C<sub>j</sub>)
+ * for j = 1...n</li>
+ * </ul>
+ * <p>
+ * In ECB encryption, the forward cipher function is applied directly, and
+ * independently, to each block of the plaintext. The resulting sequence of
+ * output blocks is the ciphertext.
+ * <p>
+ * In ECB decryption, the inverse cipher function is applied directly, and
+ * independently, to each block of the ciphertext. The resulting sequence of
+ * output blocks is the plaintext.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://csrc.nist.gov/encryption/modes/Recommendation/Modes01.pdf">
+ * Recommendation for Block Cipher Modes of Operation Methods and Techniques</a>,
+ * Morris Dworkin.</li>
+ * </ol>
+ */
+public class ECB
+ extends BaseMode
+ implements Cloneable
+{
+ /**
+ * Trivial package-private constructor for use by the Factory class.
+ *
+ * @param underlyingCipher the underlying cipher implementation.
+ * @param cipherBlockSize the underlying cipher block size to use.
+ */
+ ECB(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.ECB_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the mode to clone.
+ */
+ private ECB(ECB that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new ECB(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize != cipherBlockSize)
+ throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE);
+ }
+
+ public void teardown()
+ {
+ }
+
+ public void encryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ cipher.encryptBlock(in, i, out, o);
+ }
+
+ public void decryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ cipher.decryptBlock(in, i, out, o);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,56 @@
+/* IAuthenticatedMode.java --
+ 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.javax.crypto.mode;
+
+import gnu.javax.crypto.mac.IMac;
+
+/**
+ * The interface for encryption modes that also produce a message authentication
+ * tag.
+ * <p>
+ * This interface is merely the conjuction of the {@link IMode} and {@link IMac}
+ * interfaces. Encryption and decryption is done via the
+ * {@link IMode#update(byte[],int,byte[],int)} method, tag generation is done
+ * via the {@link IMac#digest()} method, and header updating (if supported by
+ * the mode) is done via the {@link IMac#update(byte[],int,int)} method.
+ */
+public interface IAuthenticatedMode
+ extends IMode, IMac
+{
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ICM.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ICM.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ICM.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ICM.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,181 @@
+/* ICM.java --
+ 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.math.BigInteger;
+
+/**
+ * An implementation of <i>David McGrew</i> Integer Counter Mode (ICM) as an
+ * {@link IMode}.
+ * <p>
+ * ICM is a way to define a pseudorandom keystream generator using a block
+ * cipher. The keystream can be used for additive encryption, key derivation, or
+ * any other application requiring pseudorandom data. In the case of this class,
+ * it is used as additive encryption, XOR-ing the keystream with the input text
+ * --for both encryption and decryption.
+ * <p>
+ * In ICM, the keystream is logically broken into segments. Each segment is
+ * identified with a segment index, and the segments have equal lengths. This
+ * segmentation makes ICM especially appropriate for securing packet-based
+ * protocols. ICM also allows a variety of configurations based, among other
+ * things, on two parameters: the <i>block index length</i> and the <i>segment
+ * index length</i>. A constraint on those two values exists: The sum of
+ * <i>segment index length</i> and <i>block index length</i> <b>must not</b>
+ * half the <i>block size</i> of the underlying cipher. This requirement
+ * protects the ICM keystream generator from potentially failing to be
+ * pseudorandom.
+ * <p>
+ * For simplicity, this implementation, fixes these two values to the following:
+ * <ul>
+ * <li>block index length: is half the underlying cipher block size, and</li>
+ * <li>segment index length: is zero.</li>
+ * </ul>
+ * <p>
+ * For a 128-bit block cipher, the above values imply a maximum keystream length
+ * of 295,147,905,179,352,825,856 octets, since in ICM, each segment must not
+ * exceed the value
+ * <code>(256 ^ <i>block index length</i>) * <i>block length</i></code>
+ * octets.
+ * <p>
+ * Finally, for this implementation of the ICM, the IV placeholder will be used
+ * to pass the value of the <i>Offset</i> in the keystream segment.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.ietf.org/internet-drafts/draft-mcgrew-saag-icm-00.txt">
+ * Integer Counter Mode</a>, David A. McGrew.</li>
+ * </ol>
+ */
+public class ICM
+ extends BaseMode
+ implements Cloneable
+{
+ /** The integer value 256 as a BigInteger. */
+ private static final BigInteger TWO_FIFTY_SIX = new BigInteger("256");
+ /** Maximum number of blocks per segment. */
+ private BigInteger maxBlocksPerSegment;
+ /** A work constant. */
+ private BigInteger counterRange;
+ /** The initial counter for a given keystream segment. */
+ private BigInteger C0;
+ /** The index of the next block for a given keystream segment. */
+ private BigInteger blockNdx;
+
+ /**
+ * Trivial package-private constructor for use by the Factory class.
+ *
+ * @param underlyingCipher the underlying cipher implementation.
+ * @param cipherBlockSize the underlying cipher block size to use.
+ */
+ ICM(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.ICM_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the instance to clone.
+ */
+ private ICM(ICM that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new ICM(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize != cipherBlockSize)
+ throw new IllegalArgumentException();
+ counterRange = TWO_FIFTY_SIX.pow(cipherBlockSize);
+ maxBlocksPerSegment = TWO_FIFTY_SIX.pow(cipherBlockSize / 2);
+ BigInteger r = new BigInteger(1, iv);
+ C0 = maxBlocksPerSegment.add(r).modPow(BigInteger.ONE, counterRange);
+ blockNdx = BigInteger.ZERO;
+ }
+
+ public void teardown()
+ {
+ counterRange = null;
+ maxBlocksPerSegment = null;
+ C0 = null;
+ blockNdx = null;
+ }
+
+ public void encryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ icm(in, i, out, o);
+ }
+
+ public void decryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ icm(in, i, out, o);
+ }
+
+ private void icm(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ if (blockNdx.compareTo(maxBlocksPerSegment) >= 0)
+ throw new RuntimeException("Maximum blocks for segment reached");
+ BigInteger Ci = C0.add(blockNdx).modPow(BigInteger.ONE, counterRange);
+ byte[] result = Ci.toByteArray();
+ int limit = result.length;
+ int ndx = 0;
+ if (limit < cipherBlockSize)
+ {
+ byte[] data = new byte[cipherBlockSize];
+ System.arraycopy(result, 0, data, cipherBlockSize - limit, limit);
+ result = data;
+ }
+ else if (limit > cipherBlockSize)
+ ndx = limit - cipherBlockSize;
+
+ cipher.encryptBlock(result, ndx, result, ndx);
+ blockNdx = blockNdx.add(BigInteger.ONE); // increment blockNdx
+ for (int i = 0; i < modeBlockSize; i++) // xor result with input block
+ out[outOffset++] = (byte)(in[inOffset++] ^ result[ndx++]);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IMode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IMode.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IMode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/IMode.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,123 @@
+/* IMode.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mode;
+
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+/**
+ * The basic visible methods of any block cipher mode.
+ * <p>
+ * Block ciphers encrypt plaintext in fixed size n-bit blocks. For messages
+ * larger than n bits, the simplest approach is to segment the message into
+ * n-bit blocks and process (encrypt and/or decrypt) each one separately
+ * (Electronic Codebook or ECB mode). But this approach has disadvantages in
+ * most applications. The block cipher modes of operations are one way of
+ * working around those disadvantages.
+ * <p>
+ * A <i>Mode</i> always employs an underlying block cipher for processing its
+ * input. For all intents and purposes, a <i>Mode</i> appears to behave as any
+ * other block cipher with the following differences:
+ * <ul>
+ * <li>Depending on the specifications of the mode, the block size may be
+ * different that that of the underlying cipher.</li>
+ * <li>While some modes of operations allow operations on block sizes that can
+ * be 1-bit long, this library will only deal with sizes that are multiple of 8
+ * bits. This is because the <tt>byte</tt> is the smallest, easy to handle,
+ * primitive type in Java.</li>
+ * <li>Some modes need an <i>Initialisation Vector</i> (IV) to be properly
+ * initialised.</li>
+ * </ul>
+ * <p>
+ * Possible additional initialisation values for an instance of that type are:
+ * <ul>
+ * <li>The block size in which to operate this mode instance. This value is
+ * <b>optional</b>, if unspecified, the underlying block cipher's configured
+ * block size shall be used.</li>
+ * <li>Whether this mode will be used for encryption or decryption. This value
+ * is <b>mandatory</b> and should be included in the initialisation parameters.
+ * If it isn't, a {@link java.lang.IllegalStateException} will be thrown if any
+ * method, other than <code>reset()</code> is invoked on the instance.</li>
+ * <li>The byte array containing the <i>initialisation vector</i>, if required
+ * by this type of mode.</li>
+ * </ul>
+ */
+public interface IMode
+ extends IBlockCipher
+{
+ /**
+ * Property name of the state in which to operate this mode. The value
+ * associated to this property name is taken to be an {@link Integer} which
+ * value is either <code>ENCRYPTION</code> or <code>DECRYPTION</code>.
+ */
+ String STATE = "gnu.crypto.mode.state";
+ /**
+ * Property name of the block size in which to operate this mode. The value
+ * associated with this property name is taken to be an {@link Integer}. If
+ * it is not specified, the value of the block size of the underlying block
+ * cipher, used to construct the mode instance, shall be used.
+ */
+ String MODE_BLOCK_SIZE = "gnu.crypto.mode.block.size";
+ /**
+ * Property name of the initialisation vector to use, if required, with this
+ * instance. The value associated with this property name is taken to be a
+ * byte array. If the concrete instance needs such a parameter, and it has not
+ * been specified as part of the initialissation parameters, an all-zero byte
+ * array of the appropriate size shall be used.
+ */
+ String IV = "gnu.crypto.mode.iv";
+ /** Constant indicating the instance is being used for <i>encryption</i>. */
+ int ENCRYPTION = 1;
+ /** Constant indicating the instance is being used for <i>decryption</i>. */
+ int DECRYPTION = 2;
+
+ /**
+ * A convenience method. Effectively invokes the <code>encryptBlock()</code>
+ * or <code>decryptBlock()</code> method depending on the operational state
+ * of the instance.
+ *
+ * @param in the plaintext.
+ * @param inOffset index of <code>in</code> from which to start considering
+ * data.
+ * @param out the ciphertext.
+ * @param outOffset index of <code>out</code> from which to store result.
+ * @exception IllegalStateException if the instance is not initialised.
+ */
+ void update(byte[] in, int inOffset, byte[] out, int outOffset)
+ throws IllegalStateException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,151 @@
+/* ModeFactory.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * A <i>Factory</i> to instantiate block cipher modes of operations.
+ */
+public class ModeFactory
+ implements Registry
+{
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private ModeFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a block cipher mode of operations given its name and
+ * characteristics of the underlying block cipher.
+ *
+ * @param mode the case-insensitive name of the mode of operations.
+ * @param cipher the case-insensitive name of the block cipher.
+ * @param cipherBlockSize the block size, in bytes, of the underlying cipher.
+ * @return an instance of the block cipher algorithm, operating in a given
+ * mode of operations, or <code>null</code> if none found.
+ * @exception InternalError if either the mode or the underlying block cipher
+ * implementation does not pass its self-test.
+ */
+ public static IMode getInstance(String mode, String cipher,
+ int cipherBlockSize)
+ {
+ if (mode == null || cipher == null)
+ return null;
+
+ mode = mode.trim();
+ cipher = cipher.trim();
+ IBlockCipher cipherImpl = CipherFactory.getInstance(cipher);
+ if (cipherImpl == null)
+ return null;
+
+ return getInstance(mode, cipherImpl, cipherBlockSize);
+ }
+
+ public static IMode getInstance(String mode, IBlockCipher cipher,
+ int cipherBlockSize)
+ {
+ // ensure that cipherBlockSize is valid for the chosen underlying cipher
+ boolean ok = false;
+ for (Iterator it = cipher.blockSizes(); it.hasNext();)
+ {
+ ok = (cipherBlockSize == ((Integer) it.next()).intValue());
+ if (ok)
+ break;
+ }
+ if (! ok)
+ throw new IllegalArgumentException("cipherBlockSize");
+ IMode result = null;
+ if (mode.equalsIgnoreCase(ECB_MODE))
+ result = new ECB(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(CTR_MODE))
+ result = new CTR(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(ICM_MODE))
+ result = new ICM(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(OFB_MODE))
+ result = new OFB(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(CBC_MODE))
+ result = new CBC(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(CFB_MODE))
+ result = new CFB(cipher, cipherBlockSize);
+ else if (mode.equalsIgnoreCase(EAX_MODE))
+ result = new EAX(cipher, cipherBlockSize);
+
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of names of mode supported by this <i>Factory</i>.
+ *
+ * @return a {@link Set} of mode names (Strings).
+ */
+ public static final Set getNames()
+ {
+ synchronized (ModeFactory.class)
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(ECB_MODE);
+ hs.add(CTR_MODE);
+ hs.add(ICM_MODE);
+ hs.add(OFB_MODE);
+ hs.add(CBC_MODE);
+ hs.add(CFB_MODE);
+ hs.add(EAX_MODE);
+ names = Collections.unmodifiableSet(hs);
+ }
+ }
+ return names;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/OFB.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/OFB.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/OFB.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/mode/OFB.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,174 @@
+/* OFB.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.mode;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+/**
+ * The Output Feedback (OFB) mode is a confidentiality mode that requires a
+ * unique <code>IV</code> for every message that is ever encrypted under the
+ * given key. The OFB mode is defined as follows:
+ * <ul>
+ * <li>OFB Encryption:
+ * <ul>
+ * <li>I<sub>1</sub> = IV;</li>
+ * <li>I<sub>j</sub> = O<sub>j -1</sub> for j = 2...n;</li>
+ * <li>O<sub>j</sub> = CIPH<sub>K</sub>(I<sub>j</sub>) for j = 1, 2...n;</li>
+ * <li>C<sub>j</sub> = P<sub>j</sub> XOR O<sub>j</sub> for j = 1, 2...n.</li>
+ * </ul>
+ * </li>
+ * <li>OFB Decryption:
+ * <ul>
+ * <li>I<sub>1</sub> = IV;</li>
+ * <li>I<sub>j</sub> = O<sub>j -1</sub> for j = 2...n;</li>
+ * <li>O<sub>j</sub> = CIPH<sub>K</sub>(I<sub>j</sub>) for j = 1, 2...n;</li>
+ * <li>P<sub>j</sub> = C<sub>j</sub> XOR O<sub>j</sub> for j = 1, 2...n.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * <p>
+ * In OFB encryption, the <code>IV</code> is transformed by the forward cipher
+ * function to produce the first output block. The first output block is
+ * exclusive-ORed with the first plaintext block to produce the first ciphertext
+ * block. The first output block is then transformed by the forward cipher
+ * function to produce the second output block. The second output block is
+ * exclusive-ORed with the second plaintext block to produce the second
+ * ciphertext block, and the second output block is transformed by the forward
+ * cipher function to produce the third output block. Thus, the successive
+ * output blocks are produced from enciphering the previous output blocks, and
+ * the output blocks are exclusive-ORed with the corresponding plaintext blocks
+ * to produce the ciphertext blocks.
+ * <p>
+ * In OFB decryption, the <code>IV</code> is transformed by the forward cipher
+ * function to produce the first output block. The first output block is
+ * exclusive-ORed with the first ciphertext block to recover the first plaintext
+ * block. The first output block is then transformed by the forward cipher
+ * function to produce the second output block. The second output block is
+ * exclusive-ORed with the second ciphertext block to produce the second
+ * plaintext block, and the second output block is also transformed by the
+ * forward cipher function to produce the third output block. Thus, the
+ * successive output blocks are produced from enciphering the previous output
+ * blocks, and the output blocks are exclusive-ORed with the corresponding
+ * ciphertext blocks to recover the plaintext blocks.
+ * <p>
+ * In both OFB encryption and OFB decryption, each forward cipher function
+ * (except the first) depends on the results of the previous forward cipher
+ * function; therefore, multiple forward cipher functions cannot be performed in
+ * parallel. However, if the <code>IV</code> is known, the output blocks can
+ * be generated prior to the availability of the plaintext or ciphertext data.
+ * <p>
+ * The OFB mode requires a unique <code>IV</code> for every message that is
+ * ever encrypted under the given key. If, contrary to this requirement, the
+ * same <code>IV</code> is used for the encryption of more than one message,
+ * then the confidentiality of those messages may be compromised. In particular,
+ * if a plaintext block of any of these messages is known, say, the j<sup>th</sup>
+ * plaintext block, then the j<sup>th</sup> output of the forward cipher
+ * function can be determined easily from the j<sup>th</sup> ciphertext block
+ * of the message. This information allows the j<sup>th</sup> plaintext block
+ * of any other message that is encrypted using the same <code>IV</code> to be
+ * easily recovered from the jth ciphertext block of that message.
+ * <p>
+ * Confidentiality may similarly be compromised if any of the input blocks to
+ * the forward cipher function for the encryption of a message is used as the
+ * <code>IV</code> for the encryption of another message under the given key.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://csrc.nist.gov/encryption/modes/Recommendation/Modes01.pdf">
+ * Recommendation for Block Cipher Modes of Operation Methods and Techniques</a>,
+ * Morris Dworkin.</li>
+ * </ol>
+ */
+public class OFB
+ extends BaseMode
+ implements Cloneable
+{
+ private byte[] outputBlock;
+
+ /**
+ * Trivial package-private constructor for use by the Factory class.
+ *
+ * @param underlyingCipher the underlying cipher implementation.
+ * @param cipherBlockSize the underlying cipher block size to use.
+ */
+ OFB(IBlockCipher underlyingCipher, int cipherBlockSize)
+ {
+ super(Registry.OFB_MODE, underlyingCipher, cipherBlockSize);
+ }
+
+ /**
+ * Private constructor for cloning purposes.
+ *
+ * @param that the mode to clone.
+ */
+ private OFB(OFB that)
+ {
+ this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
+ }
+
+ public Object clone()
+ {
+ return new OFB(this);
+ }
+
+ public void setup()
+ {
+ if (modeBlockSize != cipherBlockSize)
+ throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE);
+ outputBlock = (byte[]) iv.clone();
+ }
+
+ public void teardown()
+ {
+ }
+
+ public void encryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ cipher.encryptBlock(outputBlock, 0, outputBlock, 0);
+ for (int j = 0; j < cipherBlockSize;)
+ out[o++] = (byte)(in[i++] ^ outputBlock[j++]);
+ }
+
+ public void decryptBlock(byte[] in, int i, byte[] out, int o)
+ {
+ this.encryptBlock(in, i, out, o);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/BasePad.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/BasePad.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/BasePad.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/BasePad.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,191 @@
+/* BasePad.java --
+ 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.javax.crypto.pad;
+
+import gnu.java.security.Configuration;
+
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * An abstract class to facilitate implementing padding algorithms.
+ */
+public abstract class BasePad
+ implements IPad
+{
+ private static final Logger log = Logger.getLogger(BasePad.class.getName());
+ /** The canonical name prefix of the padding algorithm. */
+ protected String name;
+ /** The block size, in bytes, for this instance. */
+ protected int blockSize;
+
+ /** Trivial constructor for use by concrete subclasses. */
+ protected BasePad(final String name)
+ {
+ super();
+
+ this.name = name;
+ blockSize = -1;
+ }
+
+ public String name()
+ {
+ final StringBuffer sb = new StringBuffer(name);
+ if (blockSize != -1)
+ sb.append('-').append(String.valueOf(8 * blockSize));
+ return sb.toString();
+ }
+
+ public void init(final int bs) throws IllegalStateException
+ {
+ if (blockSize != -1)
+ throw new IllegalStateException();
+ blockSize = bs;
+ setup();
+ }
+
+ /**
+ * Initialises the algorithm with designated attributes. Names, valid and/or
+ * recognisable by all concrete implementations are described in {@link IPad}
+ * class documentation. Other algorithm-specific attributes MUST be documented
+ * in the implementation class of that padding algorithm.
+ * <p>
+ * For compatibility reasons, this method is not declared <i>abstract</i>.
+ * Furthermore, and unless overridden, the default implementation will throw
+ * an {@link UnsupportedOperationException}. Concrete padding algorithms MUST
+ * override this method if they wish to offer an initialisation method that
+ * allows for other than the padding block size parameter to be specified.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @exception IllegalStateException if the instance is already initialised.
+ * @exception IllegalArgumentException if the block size value is invalid.
+ */
+ public void init(Map attributes) throws IllegalStateException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void reset()
+ {
+ blockSize = -1;
+ }
+
+ /**
+ * A default implementation of a correctness test that exercises the padder
+ * implementation, using block sizes varying from 2 to 256 bytes.
+ *
+ * @return <code>true</code> if the concrete implementation correctly unpads
+ * what it pads for all tested block sizes. Returns <code>false</code>
+ * if the test fails for any block size.
+ */
+ public boolean selfTest()
+ {
+ final byte[] in = new byte[1024];
+ for (int bs = 2; bs < 256; bs++)
+ if (! test1BlockSize(bs, in))
+ return false;
+ return true;
+ }
+
+ /**
+ * The basic symmetric test for a padder given a specific block size.
+ * <p>
+ * The code ensures that the implementation is capable of unpadding what it
+ * pads.
+ *
+ * @param size the block size to test.
+ * @param buffer a work buffer. It is exposed as an argument for this method
+ * to reduce un-necessary object allocations.
+ * @return <code>true</code> if the test passes; <code>false</code>
+ * otherwise.
+ */
+ protected boolean test1BlockSize(int size, byte[] buffer)
+ {
+ byte[] padBytes;
+ final int offset = 5;
+ final int limit = buffer.length;
+ this.init(size);
+ for (int i = 0; i < limit - offset - blockSize; i++)
+ {
+ padBytes = pad(buffer, offset, i);
+ if (((i + padBytes.length) % blockSize) != 0)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Length of padded text MUST be a multiple of "
+ + blockSize, new RuntimeException(name()));
+ return false;
+ }
+ System.arraycopy(padBytes, 0, buffer, offset + i, padBytes.length);
+ try
+ {
+ if (padBytes.length != unpad(buffer, offset, i + padBytes.length))
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "IPad [" + name() + "] failed symmetric operation",
+ new RuntimeException(name()));
+ return false;
+ }
+ }
+ catch (WrongPaddingException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "test1BlockSize", x);
+ return false;
+ }
+ }
+ this.reset();
+ return true;
+ }
+
+ /**
+ * If any additional checks or resource setup must be done by the subclass,
+ * then this is the hook for it. This method will be called before the
+ * {@link #init(int)} method returns.
+ */
+ public abstract void setup();
+
+ public abstract byte[] pad(byte[] in, int off, int len);
+
+ public abstract int unpad(byte[] in, int off, int len)
+ throws WrongPaddingException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/IPad.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/IPad.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/IPad.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/IPad.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* IPad.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.pad;
+
+import java.util.Map;
+
+/**
+ * The basic visible methods, and attribute names, of every padding algorithm.
+ * <p>
+ * Padding algorithms serve to <i>pad</i> and <i>unpad</i> byte arrays usually
+ * as the last step in an <i>encryption</i> or respectively a <i>decryption</i>
+ * operation. Their input buffers are usually those processed by instances of
+ * {@link gnu.javax.crypto.mode.IMode} and/or
+ * {@link gnu.javax.crypto.cipher.IBlockCipher}.
+ */
+public interface IPad
+{
+ /**
+ * Property name of the block size in which to operate the padding algorithm.
+ * The value associated with this property name is taken to be a positive
+ * {@link Integer} greater than zero.
+ */
+ String PADDING_BLOCK_SIZE = "gnu.crypto.pad.block.size";
+
+ /** @return the canonical name of this instance. */
+ String name();
+
+ /**
+ * Initialises the padding scheme with a designated block size.
+ *
+ * @param bs the designated block size.
+ * @exception IllegalStateException if the instance is already initialised.
+ * @exception IllegalArgumentException if the block size value is invalid.
+ */
+ void init(int bs) throws IllegalStateException;
+
+ /**
+ * Initialises the algorithm with designated attributes. Names, valid and/or
+ * recognisable by all concrete implementations are described in the class
+ * documentation above. Other algorithm-specific attributes MUST be documented
+ * in the implementation class of that padding algorithm.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @exception IllegalStateException if the instance is already initialised.
+ * @exception IllegalArgumentException if the block size value is invalid.
+ */
+ void init(Map attributes) throws IllegalStateException;
+
+ /**
+ * Returns the byte sequence that should be appended to the designated input.
+ *
+ * @param in the input buffer containing the bytes to pad.
+ * @param offset the starting index of meaningful data in <i>in</i>.
+ * @param length the number of meaningful bytes in <i>in</i>.
+ * @return the possibly 0-byte long sequence to be appended to the designated
+ * input.
+ */
+ byte[] pad(byte[] in, int offset, int length);
+
+ /**
+ * Returns the number of bytes to discard from a designated input buffer.
+ *
+ * @param in the input buffer containing the bytes to unpad.
+ * @param offset the starting index of meaningful data in <i>in</i>.
+ * @param length the number of meaningful bytes in <i>in</i>.
+ * @return the number of bytes to discard, to the left of index position
+ * <code>offset + length</code> in <i>in</i>. In other words, if
+ * the return value of a successful invocation of this method is
+ * <code>result</code>, then the unpadded byte sequence will be
+ * <code>offset + length - result</code> bytes in <i>in</i>,
+ * starting from index position <code>offset</code>.
+ * @exception WrongPaddingException if the data is not terminated with the
+ * expected padding bytes.
+ */
+ int unpad(byte[] in, int offset, int length) throws WrongPaddingException;
+
+ /**
+ * Resets the scheme instance for re-initialisation and use with other
+ * characteristics. This method always succeeds.
+ */
+ void reset();
+
+ /**
+ * A basic symmetric pad/unpad test.
+ *
+ * @return <code>true</code> if the implementation passes a basic symmetric
+ * self-test. Returns <code>false</code> otherwise.
+ */
+ boolean selfTest();
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,109 @@
+/* ISO10126.java -- An implementation of the ISO 10126-2 padding scheme
+ 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.javax.crypto.pad;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.PRNG;
+
+/**
+ * The implementation of the ISO 10126-2 padding algorithm.
+ * <p>
+ * The last byte of the padding block is the number of padding bytes, all other
+ * padding bytes are random.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption Syntax and
+ * Processing</a> Section "5.2 Block Encryption Algorithms"; "Padding".</li>
+ * </ol>
+ */
+public final class ISO10126
+ extends BasePad
+{
+ /** Used to generate random numbers for padding bytes. */
+ private PRNG prng;
+
+ ISO10126()
+ {
+ super(Registry.ISO10126_PAD);
+ prng = PRNG.getInstance();
+ }
+
+ public void setup()
+ {
+ // Nothing to do here
+ }
+
+ public byte[] pad(byte[] in, int offset, int length)
+ {
+ int padLength = blockSize - (length % blockSize);
+ final byte[] pad = new byte[padLength];
+
+ // generate random numbers for the padding bytes except for the last byte
+ prng.nextBytes(pad, 0, padLength - 1);
+ // the last byte contains the number of padding bytes
+ pad[padLength - 1] = (byte) padLength;
+
+ return pad;
+ }
+
+ public int unpad(byte[] in, int offset, int length)
+ throws WrongPaddingException
+ {
+ // the last byte contains the number of padding bytes
+ int padLength = in[offset + length - 1] & 0xFF;
+ if (padLength > length)
+ throw new WrongPaddingException();
+
+ return padLength;
+ }
+
+ /**
+ * The default self-test in the super-class would take too long to finish
+ * with this type of padder --due to the large amount of random data needed.
+ * We override the default test and replace it with a simple one for a 16-byte
+ * block-size (default AES block-size). The Mauve test TestOfISO10126 will
+ * exercise all block-sizes that the default self-test uses for the other
+ * padders.
+ */
+ public boolean selfTest()
+ {
+ return test1BlockSize(16, new byte[1024]);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS1_V1_5.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS1_V1_5.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS1_V1_5.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS1_V1_5.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,156 @@
+/* PKCS1_V1_5.java --
+ Copyright (C) 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.javax.crypto.pad;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.sig.rsa.EME_PKCS1_V1_5;
+import gnu.java.security.util.PRNG;
+import gnu.java.security.util.Util;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * A padding algorithm implementation of the EME-PKCS1-V1.5 encoding/decoding
+ * algorithm as described in section 7.2 of RFC-3447. This is effectively an
+ * <i>Adapter</i> over an instance of {@link EME_PKCS1_V1_5} initialised with
+ * the RSA public shared modulus length (in bytes).
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
+ * Standards (PKCS) #1:</a><br>
+ * RSA Cryptography Specifications Version 2.1.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ *
+ * @see EME_PKCS1_V1_5
+ */
+public class PKCS1_V1_5
+ extends BasePad
+{
+ private static final Logger log = Logger.getLogger(PKCS1_V1_5.class.getName());
+ private EME_PKCS1_V1_5 codec;
+
+ /**
+ * Trivial package-private constructor for use by the <i>Factory</i> class.
+ *
+ * @see PadFactory
+ */
+ PKCS1_V1_5()
+ {
+ super(Registry.EME_PKCS1_V1_5_PAD);
+ }
+
+ public void setup()
+ {
+ codec = EME_PKCS1_V1_5.getInstance(blockSize);
+ }
+
+ public byte[] pad(final byte[] in, final int offset, final int length)
+ {
+ final byte[] M = new byte[length];
+ System.arraycopy(in, offset, M, 0, length);
+ final byte[] EM = codec.encode(M);
+ final byte[] result = new byte[blockSize - length];
+ System.arraycopy(EM, 0, result, 0, result.length);
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
+ return result;
+ }
+
+ public int unpad(final byte[] in, final int offset, final int length)
+ throws WrongPaddingException
+ {
+ final byte[] EM = new byte[length];
+ System.arraycopy(in, offset, EM, 0, length);
+ final int result = length - codec.decode(EM).length;
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + String.valueOf(result));
+ return result;
+ }
+
+ public boolean selfTest()
+ {
+ final int[] mLen = new int[] { 16, 20, 32, 48, 64 };
+ final byte[] M = new byte[mLen[mLen.length - 1]];
+ PRNG.getInstance().nextBytes(M);
+ final byte[] EM = new byte[1024];
+ byte[] p;
+ int bs, i, j;
+ for (bs = 256; bs < 1025; bs += 256)
+ {
+ init(bs);
+ for (i = 0; i < mLen.length; i++)
+ {
+ j = mLen[i];
+ p = pad(M, 0, j);
+ if (j + p.length != blockSize)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Length of padded text MUST be a multiple of "
+ + blockSize, new RuntimeException(name()));
+ return false;
+ }
+ System.arraycopy(p, 0, EM, 0, p.length);
+ System.arraycopy(M, 0, EM, p.length, j);
+ try
+ {
+ if (p.length != unpad(EM, 0, blockSize))
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE, "Failed symmetric operation",
+ new RuntimeException(name()));
+ return false;
+ }
+ }
+ catch (WrongPaddingException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "selfTest", x);
+ return false;
+ }
+ }
+ reset();
+ }
+ return true;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* PKCS7.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.pad;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+
+import java.util.logging.Logger;
+
+/**
+ * The implementation of the PKCS7 padding algorithm.
+ * <p>
+ * This algorithm is described for 8-byte blocks in [RFC-1423] and extended to
+ * block sizes of up to 256 bytes in [PKCS-7].
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc1423.txt">RFC-1423</a>: Privacy
+ * Enhancement for Internet Electronic Mail: Part III: Algorithms, Modes, and
+ * Identifiers.</li>
+ * <li><a href="http://www.ietf.org/">IETF</a>.</li>
+ * <li><a href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-7/">[PKCS-7]</a>
+ * PKCS #7: Cryptographic Message Syntax Standard - An RSA Laboratories
+ * Technical Note.</li>
+ * <li><a href="http://www.rsasecurity.com/">RSA Security</a>.</li>
+ * </ol>
+ */
+public final class PKCS7
+ extends BasePad
+{
+ private static final Logger log = Logger.getLogger(PKCS7.class.getName());
+
+ /**
+ * Trivial package-private constructor for use by the <i>Factory</i> class.
+ *
+ * @see PadFactory
+ */
+ PKCS7()
+ {
+ super(Registry.PKCS7_PAD);
+ }
+
+ public void setup()
+ {
+ if (blockSize < 2 || blockSize > 256)
+ throw new IllegalArgumentException();
+ }
+
+ public byte[] pad(byte[] in, int offset, int length)
+ {
+ int padLength = blockSize;
+ if (length % blockSize != 0)
+ padLength = blockSize - length % blockSize;
+ byte[] result = new byte[padLength];
+ for (int i = 0; i < padLength;)
+ result[i++] = (byte) padLength;
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
+ return result;
+ }
+
+ public int unpad(byte[] in, int offset, int length)
+ throws WrongPaddingException
+ {
+ int limit = offset + length;
+ int result = in[--limit] & 0xFF;
+ for (int i = 0; i < result - 1; i++)
+ if (result != (in[--limit] & 0xFF))
+ throw new WrongPaddingException();
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + result);
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,120 @@
+/* PadFactory.java --
+ Copyright (C) 2001, 2002, 2003, 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.javax.crypto.pad;
+
+import gnu.java.security.Registry;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A Factory to instantiate padding schemes.
+ */
+public class PadFactory
+ implements Registry
+{
+ /** Collection of padding algorithm names --cached for speed. */
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private PadFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a padding algorithm given its name.
+ *
+ * @param pad the case-insensitive name of the padding algorithm.
+ * @return an instance of the padding algorithm, operating with a given block
+ * size, or <code>null</code> if none found.
+ * @throws InternalError if the implementation does not pass its self-test.
+ */
+ public static final IPad getInstance(String pad)
+ {
+ if (pad == null)
+ return null;
+
+ pad = pad.trim().toLowerCase();
+ if (pad.endsWith("padding"))
+ pad = pad.substring(0, pad.length() - "padding".length());
+ IPad result = null;
+ if (pad.equals(PKCS7_PAD) || pad.equals(PKCS5_PAD))
+ result = new PKCS7();
+ else if (pad.equals(TBC_PAD))
+ result = new TBC();
+ else if (pad.equals(EME_PKCS1_V1_5_PAD))
+ result = new PKCS1_V1_5();
+ else if (pad.equals(SSL3_PAD))
+ result = new SSL3();
+ else if (pad.equals(TLS1_PAD))
+ result = new TLS1();
+ else if (pad.equals(ISO10126_PAD))
+ result = new ISO10126();
+
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of names of padding algorithms supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of padding algorithm names (Strings).
+ */
+ public static final Set getNames()
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(PKCS5_PAD);
+ hs.add(PKCS7_PAD);
+ hs.add(TBC_PAD);
+ hs.add(EME_PKCS1_V1_5_PAD);
+ hs.add(SSL3_PAD);
+ hs.add(TLS1_PAD);
+ hs.add(ISO10126_PAD);
+ names = Collections.unmodifiableSet(hs);
+ }
+ return names;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/SSL3.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/SSL3.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/SSL3.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/SSL3.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,90 @@
+/* SSL3.java -- SSLv3 padding scheme.
+ 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.javax.crypto.pad;
+
+/**
+ * The padding scheme used by the Secure Sockets Layer, version 3. This padding
+ * scheme is used in the block-ciphered struct, e.g.:
+ * <pre>
+ * block-ciphered struct {
+ * opaque content[SSLCompressed.length];
+ * opaque MAC[CipherSpec.hash_size];
+ * uint8 padding[GenericBlockCipher.padding_length];
+ * uint8 padding_length;
+ * } GenericBlockCipher;
+ * </pre>
+ * <p>
+ * Where <i>padding_length</i> is <i>cipher_block_size</i> -
+ * ((<i>SSLCompressed.length</i> + <i>CipherSpec.hash_size</i>) %
+ * <i>cipher_block_size</i>) - 1. That is, the padding is enough bytes to make
+ * the plaintext a multiple of the block size minus one, plus one additional
+ * byte for the padding length. The padding can be any arbitrary data.
+ */
+public class SSL3
+ extends BasePad
+{
+ public SSL3()
+ {
+ super("ssl3");
+ }
+
+ public void setup()
+ {
+ if (blockSize <= 0 || blockSize > 255)
+ throw new IllegalArgumentException("invalid block size: " + blockSize);
+ }
+
+ public byte[] pad(final byte[] in, final int off, final int len)
+ {
+ int padlen = blockSize - (len % blockSize);
+ byte[] pad = new byte[padlen];
+ for (int i = 0; i < padlen; i++)
+ pad[i] = (byte)(padlen - 1);
+ return pad;
+ }
+
+ public int unpad(final byte[] in, final int off, final int len)
+ throws WrongPaddingException
+ {
+ int padlen = in[off + len - 1] & 0xFF;
+ if (padlen >= blockSize)
+ throw new WrongPaddingException();
+ return padlen + 1;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TBC.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TBC.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TBC.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TBC.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,118 @@
+/* TBC.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.pad;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+
+import java.util.logging.Logger;
+
+/**
+ * The implementation of the Trailing Bit Complement (TBC) padding algorithm.
+ * <p>
+ * In this mode, "...the data string is padded at the trailing end with the
+ * complement of the trailing bit of the unpadded message: if the trailing bit
+ * is <tt>1</tt>, then <tt>0</tt> bits are appended, and if the trailing
+ * bit is <tt>0</tt>, then <tt>1</tt> bits are appended. As few bits are
+ * added as are necessary to meet the formatting size requirement."
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://csrc.nist.gov/encryption/modes/Recommendation/Modes01.pdf">
+ * Recommendation for Block Cipher Modes of Operation Methods and
+ * Techniques</a>, Morris Dworkin.</li>
+ * </ol>
+ */
+public final class TBC
+ extends BasePad
+{
+ private static final Logger log = Logger.getLogger(TBC.class.getName());
+
+ /**
+ * Trivial package-private constructor for use by the <i>Factory</i> class.
+ *
+ * @see PadFactory
+ */
+ TBC()
+ {
+ super(Registry.TBC_PAD);
+ }
+
+ public void setup()
+ {
+ if (blockSize < 1 || blockSize > 256)
+ throw new IllegalArgumentException();
+ }
+
+ public byte[] pad(byte[] in, int offset, int length)
+ {
+ int padLength = blockSize;
+ if (length % blockSize != 0)
+ padLength = blockSize - length % blockSize;
+ byte[] result = new byte[padLength];
+ int lastBit = in[offset + length - 1] & 0x01;
+ if (lastBit == 0)
+ for (int i = 0; i < padLength;)
+ result[i++] = 0x01;
+ // else it's already set to zeroes by virtue of initialisation
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
+ return result;
+ }
+
+ public int unpad(byte[] in, int offset, int length)
+ throws WrongPaddingException
+ {
+ int limit = offset + length - 1;
+ int lastBit = in[limit] & 0xFF;
+ int result = 0;
+ while (lastBit == (in[limit] & 0xFF))
+ {
+ result++;
+ limit--;
+ }
+ if (result > length)
+ throw new WrongPaddingException();
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + result);
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TLS1.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TLS1.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TLS1.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/TLS1.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,91 @@
+/* TLS1.java -- TLSv1 padding scheme.
+ 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.javax.crypto.pad;
+
+/**
+ * The padding scheme used by the Transport Layer Security protocol, version 1.
+ * This padding scheme is used in the block-ciphered struct, e.g.:
+ * <pre>
+ * block-ciphered struct {
+ * opaque content[TLSCompressed.length];
+ * opaque MAC[CipherSpec.hash_size];
+ * uint8 padding[GenericBlockCipher.padding_length];
+ * uint8 padding_length;
+ * } GenericBlockCipher;
+ * </pre>
+ * <p>
+ * Where <i>padding_length</i> is any multiple of <i>cipher_block_size</i> -
+ * ((<i>SSLCompressed.length</i> + <i>CipherSpec.hash_size</i>) %
+ * <i>cipher_block_size</i>) - 1 that is less than 255. Every byte of the
+ * padding must be equal to <i>padding_length</i>. That is, the end of the
+ * plaintext is <i>n</i> + 1 copies of the unsigned byte <i>n</i>.
+ */
+public class TLS1
+ extends BasePad
+{
+ public TLS1()
+ {
+ super("tls1");
+ }
+
+ public void setup()
+ {
+ if (blockSize <= 0 || blockSize > 255)
+ throw new IllegalArgumentException("invalid block size: " + blockSize);
+ }
+
+ public byte[] pad(final byte[] in, final int off, final int len)
+ {
+ int padlen = blockSize - (len % blockSize);
+ byte[] pad = new byte[padlen];
+ for (int i = 0; i < padlen; i++)
+ pad[i] = (byte)(padlen - 1);
+ return pad;
+ }
+
+ public int unpad(final byte[] in, final int off, final int len)
+ throws WrongPaddingException
+ {
+ int padlen = in[off + len - 1] & 0xFF;
+ for (int i = off + (len - padlen - 1); i < off + len - 1; i++)
+ if ((in[i] & 0xFF) != padlen)
+ throw new WrongPaddingException();
+ return padlen + 1;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,48 @@
+/* WrongPaddingException.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.pad;
+
+/**
+ * A checked exception that indicates that a padding algorithm did not find the
+ * expected padding bytes when unpadding some data.
+ */
+public class WrongPaddingException
+ extends Exception
+{
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,137 @@
+/* ARCFour.java --
+ Copyright (C) 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.javax.crypto.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.LimitReachedException;
+
+import java.util.Map;
+
+/**
+ * RC4 is a stream cipher developed by Ron Rivest. Until 1994 RC4 was a trade
+ * secret of RSA Data Security, Inc., when it was released anonymously to a
+ * mailing list. This version is a descendent of that code, and since there is
+ * no proof that the leaked version was in fact RC4 and because "RC4" is a
+ * trademark, it is called "ARCFOUR", short for "Allegedly RC4".
+ * <p>
+ * This class only implements the <i>keystream</i> of ARCFOUR. To use this as a
+ * stream cipher, one would say:
+ * <pre>
+ * out = in ˆ arcfour.nextByte();
+ * </pre>
+ * <p>
+ * This operation works for encryption and decryption.
+ * <p>
+ * References:
+ * <ol>
+ * <li>Schneier, Bruce: <i>Applied Cryptography: Protocols, Algorithms, and
+ * Source Code in C, Second Edition.</i> (1996 John Wiley and Sons), pp.
+ * 397--398. ISBN 0-471-11709-9</li>
+ * <li>K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm
+ * 'Arcfour'", Internet Draft (expired), <a
+ * href="http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt">draft-kaukonen-cipher-arcfour-03.txt</a></li>
+ * </ol>
+ */
+public class ARCFour
+ extends BasePRNG
+ implements Cloneable
+{
+ /** The attributes property name for the key bytes. */
+ public static final String ARCFOUR_KEY_MATERIAL = "gnu.crypto.prng.arcfour.key-material";
+ /** The size of the internal S-box. */
+ public static final int ARCFOUR_SBOX_SIZE = 256;
+ /** The S-box. */
+ private byte[] s;
+ private byte m, n;
+
+ /** Default 0-arguments constructor. */
+ public ARCFour()
+ {
+ super(Registry.ARCFOUR_PRNG);
+ }
+
+ public void setup(Map attributes)
+ {
+ byte[] kb = (byte[]) attributes.get(ARCFOUR_KEY_MATERIAL);
+ if (kb == null)
+ throw new IllegalArgumentException("ARCFOUR needs a key");
+ s = new byte[ARCFOUR_SBOX_SIZE];
+ m = n = 0;
+ byte[] k = new byte[ARCFOUR_SBOX_SIZE];
+ for (int i = 0; i < ARCFOUR_SBOX_SIZE; i++)
+ s[i] = (byte) i;
+ if (kb.length > 0)
+ for (int i = 0, j = 0; i < ARCFOUR_SBOX_SIZE; i++)
+ {
+ k[i] = kb[j++];
+ if (j >= kb.length)
+ j = 0;
+ }
+ for (int i = 0, j = 0; i < ARCFOUR_SBOX_SIZE; i++)
+ {
+ j = j + s[i] + k[i];
+ byte temp = s[i];
+ s[i] = s[j & 0xff];
+ s[j & 0xff] = temp;
+ }
+ buffer = new byte[ARCFOUR_SBOX_SIZE];
+ try
+ {
+ fillBlock();
+ }
+ catch (LimitReachedException wontHappen)
+ {
+ }
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ for (int i = 0; i < buffer.length; i++)
+ {
+ m++;
+ n = (byte)(n + s[m & 0xff]);
+ byte temp = s[m & 0xff];
+ s[m & 0xff] = s[n & 0xff];
+ s[n & 0xff] = temp;
+ temp = (byte)(s[m & 0xff] + s[n & 0xff]);
+ buffer[i] = s[temp & 0xff];
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/CSPRNG.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/CSPRNG.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/CSPRNG.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/CSPRNG.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,985 @@
+/* CSPRNG.java -- continuously-seeded pseudo-random number generator.
+ 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.javax.crypto.prng;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Properties;
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.EntropySource;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.SimpleList;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.InvalidKeyException;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * An entropy pool-based pseudo-random number generator based on the PRNG in
+ * Peter Gutmann's cryptlib (<a
+ * href="http://www.cs.auckland.ac.nz/~pgut001/cryptlib/">http://www.cs.auckland.ac.nz/~pgut001/cryptlib/</a>).
+ * <p>
+ * The basic properties of this generator are:
+ * <ol>
+ * <li>The internal state cannot be determined by knowledge of the input.</li>
+ * <li>It is resistant to bias introduced by specific inputs.</li>
+ * <li>The output does not reveal the state of the generator.</li>
+ * </ol>
+ */
+public class CSPRNG
+ extends BasePRNG
+{
+ private static final Logger log = Logger.getLogger(CSPRNG.class.getName());
+ /**
+ * Property name for the list of files to read for random values. The mapped
+ * value is a list with the following values:
+ * <ol>
+ * <li>A {@link Double}, indicating the suggested <i>quality</i> of this
+ * source. This value must be between 0 and 100.</li>
+ * <li>An {@link Integer}, indicating the number of bytes to skip in the
+ * file before reading bytes. This can be any nonnegative value.</li>
+ * <li>An {@link Integer}, indicating the number of bytes to read.</li>
+ * <li>A {@link String}, indicating the path to the file.</li>
+ * </ol>
+ *
+ * @see gnu.java.security.util.SimpleList
+ */
+ public static final String FILE_SOURCES = "gnu.crypto.prng.pool.files";
+ /**
+ * Property name for the list of URLs to poll for random values. The mapped
+ * value is a list formatted similarly as in {@link #FILE_SOURCES}, but the
+ * fourth member is a {@link URL}.
+ */
+ public static final String URL_SOURCES = "gnu.crypto.prng.pool.urls";
+ /**
+ * Property name for the list of programs to execute, and use the output as
+ * new random bytes. The mapped property is formatted similarly an in
+ * {@link #FILE_SOURCES} and {@link #URL_SOURCES}, except the fourth member
+ * is a {@link String} of the program to execute.
+ */
+ public static final String PROGRAM_SOURCES = "gnu.crypto.prng.pool.programs";
+ /**
+ * Property name for a list of other sources of entropy. The mapped value must
+ * be a list of {@link EntropySource} objects.
+ */
+ public static final String OTHER_SOURCES = "gnu.crypto.prng.pool.other";
+ /**
+ * Property name for whether or not to wait for the slow poll to complete,
+ * passed as a {@link Boolean}. The default value is true.
+ */
+ public static final String BLOCKING = "gnu.crypto.prng.pool.blocking";
+ private static final String FILES = "gnu.crypto.csprng.file.";
+ private static final String URLS = "gnu.crypto.csprng.url.";
+ private static final String PROGS = "gnu.crypto.csprng.program.";
+ private static final String OTHER = "gnu.crypto.csprng.other.";
+ private static final String BLOCK = "gnu.crypto.csprng.blocking";
+ private static final int POOL_SIZE = 256;
+ private static final int ALLOC_SIZE = 260;
+ private static final int OUTPUT_SIZE = POOL_SIZE / 2;
+ private static final int X917_POOL_SIZE = 16;
+ private static final String HASH_FUNCTION = Registry.SHA160_HASH;
+ private static final String CIPHER = Registry.AES_CIPHER;
+ private static final int MIX_COUNT = 10;
+ private static final int X917_LIFETIME = 8192;
+ // FIXME this should be configurable.
+ private static final int SPINNER_COUNT = 8;
+ /**
+ * The spinner group singleton. We use this to add a small amount of
+ * randomness (in addition to the current time and the amount of free memory)
+ * based on the randomness (if any) present due to system load and thread
+ * scheduling.
+ */
+ private static final Spinner[] SPINNERS = new Spinner[SPINNER_COUNT];
+ private static final Thread[] SPINNER_THREADS = new Thread[SPINNER_COUNT];
+ static
+ {
+ for (int i = 0; i < SPINNER_COUNT; i++)
+ {
+ SPINNER_THREADS[i] = new Thread(SPINNERS[i] = new Spinner(),
+ "spinner-" + i);
+ SPINNER_THREADS[i].setDaemon(true);
+ SPINNER_THREADS[i].setPriority(Thread.MIN_PRIORITY);
+ SPINNER_THREADS[i].start();
+ }
+ }
+ /** The message digest (SHA-1) used in the mixing function. */
+ private final IMessageDigest hash;
+ /** The cipher (AES) used in the output masking function. */
+ private final IBlockCipher cipher;
+ /** The number of times the pool has been mixed. */
+ private int mixCount;
+ /** The entropy pool. */
+ private final byte[] pool;
+ /** The quality of the random pool (percentage). */
+ private double quality;
+ /** The index of the next byte in the entropy pool. */
+ private int index;
+ /** The pool for the X9.17-like generator. */
+ private byte[] x917pool;
+ /** The number of iterations of the X9.17-like generators. */
+ private int x917count;
+ /** Whether or not the X9.17-like generator is initialized. */
+ private boolean x917init;
+ /** The list of file soures. */
+ private final List files;
+ /** The list of URL sources. */
+ private final List urls;
+ /** The list of program sources. */
+ private final List progs;
+ /** The list of other sources. */
+ private final List other;
+ /** Whether or not to wait for the slow poll to complete. */
+ private boolean blocking;
+ /** The thread that polls for random data. */
+ private Poller poller;
+ private Thread pollerThread;
+
+ public CSPRNG()
+ {
+ super("CSPRNG");
+ pool = new byte[ALLOC_SIZE];
+ x917pool = new byte[X917_POOL_SIZE];
+ x917count = 0;
+ x917init = false;
+ quality = 0.0;
+ hash = HashFactory.getInstance(HASH_FUNCTION);
+ cipher = CipherFactory.getInstance(CIPHER);
+ buffer = new byte[OUTPUT_SIZE];
+ ndx = 0;
+ initialised = false;
+ files = new LinkedList();
+ urls = new LinkedList();
+ progs = new LinkedList();
+ other = new LinkedList();
+ }
+
+ /**
+ * Create and initialize a CSPRNG instance with the "system" parameters; the
+ * files, URLs, programs, and {@link EntropySource} sources used by the
+ * instance are derived from properties set in the system {@link Properties}.
+ * <p>
+ * All properties are of the from <i>name</i>.</i>N</i>, where <i>name</i>
+ * is the name of the source, and <i>N</i> is an integer (staring at 1) that
+ * indicates the preference number for that source.
+ * <p>
+ * The following vales for <i>name</i> are used here:
+ * <dl>
+ * <dt>gnu.crypto.csprng.file</dt>
+ * <dd>
+ * <p>
+ * These properties are file sources, passed as the {@link #FILE_SOURCES}
+ * parameter of the instance. The property value is a 4-tuple formatted as:
+ * </p>
+ * <blockquote><i>quality</i> ; <i>offset</i> ; <i>count</i> ; <i>path</i></blockquote>
+ * <p>
+ * The parameters are mapped to the parameters defined for {@link
+ * #FILE_SOURCES}. Leading or trailing spaces on any item are trimmed off.
+ * </p>
+ * </dd>
+ * <dt>gnu.crypto.csprng.url</dt>
+ * <dd>
+ * <p>
+ * These properties are URL sources, passed as the {@link #URL_SOURCES}
+ * parameter of the instance. The property is formatted the same way as file
+ * sources, but the <i>path</i> argument must be a valid URL.
+ * </p>
+ * </dd>
+ * <dt>gnu.crypto.csprng.program</dt>
+ * <dd>
+ * <p>
+ * These properties are program sources, passed as the {@link
+ * #PROGRAM_SOURCES} parameter of the instance. This property is formatted the
+ * same way as file and URL sources, but the last argument is a program and
+ * its arguments.
+ * </p>
+ * </dd>
+ * <dt>gnu.crypto.cspring.other</dt>
+ * <dd>
+ * <p>
+ * These properties are other sources, passed as the {@link #OTHER_SOURCES}
+ * parameter of the instance. The property value must be the full name of a
+ * class that implements the {@link EntropySource} interface and has a public
+ * no-argument constructor.
+ * </p>
+ * </dd>
+ * </dl>
+ * <p>
+ * Finally, a boolean property "gnu.crypto.csprng.blocking" can be set to the
+ * desired value of {@link #BLOCKING}.
+ * <p>
+ * An example of valid properties would be:
+ * <pre>
+ * gnu.crypto.csprng.blocking=true
+ *
+ * gnu.crypto.csprng.file.1=75.0;0;256;/dev/random
+ * gnu.crypto.csprng.file.2=10.0;0;100;/home/user/file
+ *
+ * gnu.crypto.csprng.url.1=5.0;0;256;http://www.random.org/cgi-bin/randbyte?nbytes=256
+ * gnu.crypto.csprng.url.2=0;256;256;http://slashdot.org/
+ *
+ * gnu.crypto.csprng.program.1=0.5;0;10;last -n 50
+ * gnu.crypto.csprng.program.2=0.5;0;10;tcpdump -c 5
+ *
+ * gnu.crypto.csprng.other.1=foo.bar.MyEntropySource
+ * gnu.crypto.csprng.other.2=com.company.OtherEntropySource
+ * </pre>
+ */
+ public static IRandom getSystemInstance() throws ClassNotFoundException,
+ MalformedURLException, NumberFormatException
+ {
+ CSPRNG instance = new CSPRNG();
+ HashMap attrib = new HashMap();
+ attrib.put(BLOCKING, Boolean.valueOf(getProperty(BLOCK)));
+ String s = null;
+ // Get each file source "gnu.crypto.csprng.file.N".
+ List l = new LinkedList();
+ for (int i = 0; (s = getProperty(FILES + i)) != null; i++)
+ try
+ {
+ l.add(parseString(s.trim()));
+ }
+ catch (NumberFormatException nfe)
+ {
+ }
+ attrib.put(FILE_SOURCES, l);
+ l = new LinkedList();
+ for (int i = 0; (s = getProperty(URLS + i)) != null; i++)
+ try
+ {
+ l.add(parseURL(s.trim()));
+ }
+ catch (NumberFormatException nfe)
+ {
+ }
+ catch (MalformedURLException mue)
+ {
+ }
+ attrib.put(URL_SOURCES, l);
+ l = new LinkedList();
+ for (int i = 0; (s = getProperty(PROGS + i)) != null; i++)
+ try
+ {
+ l.add(parseString(s.trim()));
+ }
+ catch (NumberFormatException nfe)
+ {
+ }
+ attrib.put(PROGRAM_SOURCES, l);
+ l = new LinkedList();
+ for (int i = 0; (s = getProperty(OTHER + i)) != null; i++)
+ try
+ {
+ Class c = Class.forName(s.trim());
+ l.add(c.newInstance());
+ }
+ catch (ClassNotFoundException cnfe)
+ {
+ }
+ catch (InstantiationException ie)
+ {
+ }
+ catch (IllegalAccessException iae)
+ {
+ }
+ attrib.put(OTHER_SOURCES, l);
+ instance.init(attrib);
+ return instance;
+ }
+
+ private static String getProperty(final String name)
+ {
+ return (String) AccessController.doPrivileged(new PrivilegedAction()
+ {
+ public Object run()
+ {
+ return Properties.getProperty(name);
+ }
+ });
+ }
+
+ private static List parseString(String s) throws NumberFormatException
+ {
+ StringTokenizer tok = new StringTokenizer(s, ";");
+ if (tok.countTokens() != 4)
+ throw new IllegalArgumentException("malformed property");
+ Double quality = new Double(tok.nextToken());
+ Integer offset = new Integer(tok.nextToken());
+ Integer length = new Integer(tok.nextToken());
+ String str = tok.nextToken();
+ return new SimpleList(quality, offset, length, str);
+ }
+
+ private static List parseURL(String s) throws MalformedURLException,
+ NumberFormatException
+ {
+ StringTokenizer tok = new StringTokenizer(s, ";");
+ if (tok.countTokens() != 4)
+ throw new IllegalArgumentException("malformed property");
+ Double quality = new Double(tok.nextToken());
+ Integer offset = new Integer(tok.nextToken());
+ Integer length = new Integer(tok.nextToken());
+ URL url = new URL(tok.nextToken());
+ return new SimpleList(quality, offset, length, url);
+ }
+
+ public Object clone()
+ {
+ return new CSPRNG();
+ }
+
+ public void setup(Map attrib)
+ {
+ List list = null;
+ if (Configuration.DEBUG)
+ log.fine("attrib=" + String.valueOf(attrib));
+ try
+ {
+ list = (List) attrib.get(FILE_SOURCES);
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
+ if (list != null)
+ {
+ files.clear();
+ for (Iterator it = list.iterator(); it.hasNext();)
+ {
+ List l = (List) it.next();
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
+ if (l.size() != 4)
+ {
+ if (Configuration.DEBUG)
+ log.fine("file list too small: " + l.size());
+ throw new IllegalArgumentException("invalid file list");
+ }
+ Double quality = (Double) l.get(0);
+ Integer offset = (Integer) l.get(1);
+ Integer length = (Integer) l.get(2);
+ String source = (String) l.get(3);
+ files.add(new SimpleList(quality, offset, length, source));
+ }
+ }
+ }
+ catch (ClassCastException cce)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad file list", cce);
+ throw new IllegalArgumentException("invalid file list");
+ }
+ try
+ {
+ list = (List) attrib.get(URL_SOURCES);
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
+ if (list != null)
+ {
+ urls.clear();
+ for (Iterator it = list.iterator(); it.hasNext();)
+ {
+ List l = (List) it.next();
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
+ if (l.size() != 4)
+ {
+ if (Configuration.DEBUG)
+ log.fine("URL list too small: " + l.size());
+ throw new IllegalArgumentException("invalid URL list");
+ }
+ Double quality = (Double) l.get(0);
+ Integer offset = (Integer) l.get(1);
+ Integer length = (Integer) l.get(2);
+ URL source = (URL) l.get(3);
+ urls.add(new SimpleList(quality, offset, length, source));
+ }
+ }
+ }
+ catch (ClassCastException cce)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad URL list", cce);
+ throw new IllegalArgumentException("invalid URL list");
+ }
+ try
+ {
+ list = (List) attrib.get(PROGRAM_SOURCES);
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
+ if (list != null)
+ {
+ progs.clear();
+ for (Iterator it = list.iterator(); it.hasNext();)
+ {
+ List l = (List) it.next();
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
+ if (l.size() != 4)
+ {
+ if (Configuration.DEBUG)
+ log.fine("program list too small: " + l.size());
+ throw new IllegalArgumentException("invalid program list");
+ }
+ Double quality = (Double) l.get(0);
+ Integer offset = (Integer) l.get(1);
+ Integer length = (Integer) l.get(2);
+ String source = (String) l.get(3);
+ progs.add(new SimpleList(quality, offset, length, source));
+ }
+ }
+ }
+ catch (ClassCastException cce)
+ {
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad program list", cce);
+ throw new IllegalArgumentException("invalid program list");
+ }
+ try
+ {
+ list = (List) attrib.get(OTHER_SOURCES);
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
+ if (list != null)
+ {
+ other.clear();
+ for (Iterator it = list.iterator(); it.hasNext();)
+ {
+ EntropySource src = (EntropySource) it.next();
+ if (Configuration.DEBUG)
+ log.fine("src=" + src);
+ if (src == null)
+ throw new NullPointerException("null source in source list");
+ other.add(src);
+ }
+ }
+ }
+ catch (ClassCastException cce)
+ {
+ throw new IllegalArgumentException("invalid source list");
+ }
+
+ try
+ {
+ Boolean block = (Boolean) attrib.get(BLOCKING);
+ if (block != null)
+ blocking = block.booleanValue();
+ else
+ blocking = true;
+ }
+ catch (ClassCastException cce)
+ {
+ throw new IllegalArgumentException("invalid blocking parameter");
+ }
+ poller = new Poller(files, urls, progs, other, this);
+ try
+ {
+ fillBlock();
+ }
+ catch (LimitReachedException lre)
+ {
+ throw new RuntimeException("bootstrapping CSPRNG failed");
+ }
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ if (Configuration.DEBUG)
+ log.fine("fillBlock");
+ if (getQuality() < 100.0)
+ {
+ if (Configuration.DEBUG)
+ log.fine("doing slow poll");
+ slowPoll();
+ }
+ do
+ {
+ fastPoll();
+ mixRandomPool();
+ }
+ while (mixCount < MIX_COUNT);
+ if (! x917init || x917count >= X917_LIFETIME)
+ {
+ mixRandomPool(pool);
+ Map attr = new HashMap();
+ byte[] key = new byte[32];
+ System.arraycopy(pool, 0, key, 0, 32);
+ cipher.reset();
+ attr.put(IBlockCipher.KEY_MATERIAL, key);
+ try
+ {
+ cipher.init(attr);
+ }
+ catch (InvalidKeyException ike)
+ {
+ throw new Error(ike.toString());
+ }
+ mixRandomPool(pool);
+ generateX917(pool);
+ mixRandomPool(pool);
+ generateX917(pool);
+ if (x917init)
+ quality = 0.0;
+ x917init = true;
+ x917count = 0;
+ }
+ byte[] export = new byte[ALLOC_SIZE];
+ for (int i = 0; i < ALLOC_SIZE; i++)
+ export[i] = (byte)(pool[i] ^ 0xFF);
+ mixRandomPool();
+ mixRandomPool(export);
+ generateX917(export);
+ for (int i = 0; i < OUTPUT_SIZE; i++)
+ buffer[i] = (byte)(export[i] ^ export[i + OUTPUT_SIZE]);
+ Arrays.fill(export, (byte) 0);
+ }
+
+ /**
+ * Add an array of bytes into the randomness pool. Note that this method will
+ * <i>not</i> increment the pool's quality counter (this can only be done via
+ * a source provided to the setup method).
+ *
+ * @param buf The byte array.
+ * @param off The offset from whence to start reading bytes.
+ * @param len The number of bytes to add.
+ * @throws ArrayIndexOutOfBoundsException If <i>off</i> or <i>len</i> are
+ * out of the range of <i>buf</i>.
+ */
+ public synchronized void addRandomBytes(byte[] buf, int off, int len)
+ {
+ if (off < 0 || len < 0 || off + len > buf.length)
+ throw new ArrayIndexOutOfBoundsException();
+ if (Configuration.DEBUG)
+ {
+ log.fine("adding random bytes:");
+ log.fine(Util.toString(buf, off, len));
+ }
+ final int count = off + len;
+ for (int i = off; i < count; i++)
+ {
+ pool[index++] ^= buf[i];
+ if (index == pool.length)
+ {
+ mixRandomPool();
+ index = 0;
+ }
+ }
+ }
+
+ /**
+ * Add a single random byte to the randomness pool. Note that this method will
+ * <i>not</i> increment the pool's quality counter (this can only be done via
+ * a source provided to the setup method).
+ *
+ * @param b The byte to add.
+ */
+ public synchronized void addRandomByte(byte b)
+ {
+ if (Configuration.DEBUG)
+ log.fine("adding byte " + Integer.toHexString(b));
+ pool[index++] ^= b;
+ if (index >= pool.length)
+ {
+ mixRandomPool();
+ index = 0;
+ }
+ }
+
+ synchronized void addQuality(double quality)
+ {
+ if (Configuration.DEBUG)
+ log.fine("adding quality " + quality);
+ if (this.quality < 100)
+ this.quality += quality;
+ if (Configuration.DEBUG)
+ log.fine("quality now " + this.quality);
+ }
+
+ synchronized double getQuality()
+ {
+ return quality;
+ }
+
+ /**
+ * The mix operation. This method will, for every 20-byte block in the random
+ * pool, hash that block, the previous 20 bytes, and the next 44 bytes with
+ * SHA-1, writing the result back into that block.
+ */
+ private void mixRandomPool(byte[] buf)
+ {
+ int hashSize = hash.hashSize();
+ for (int i = 0; i < buf.length; i += hashSize)
+ {
+ // First update the bytes [p-19..p-1].
+ if (i == 0)
+ hash.update(buf, buf.length - hashSize, hashSize);
+ else
+ hash.update(buf, i - hashSize, hashSize);
+ // Now the next 64 bytes.
+ if (i + 64 < buf.length)
+ hash.update(buf, i, 64);
+ else
+ {
+ hash.update(buf, i, buf.length - i);
+ hash.update(buf, 0, 64 - (buf.length - i));
+ }
+ byte[] digest = hash.digest();
+ System.arraycopy(digest, 0, buf, i, hashSize);
+ }
+ }
+
+ private void mixRandomPool()
+ {
+ mixRandomPool(pool);
+ mixCount++;
+ }
+
+ private void generateX917(byte[] buf)
+ {
+ int off = 0;
+ for (int i = 0; i < buf.length; i += X917_POOL_SIZE)
+ {
+ int copy = Math.min(buf.length - i, X917_POOL_SIZE);
+ for (int j = 0; j < copy; j++)
+ x917pool[j] ^= pool[off + j];
+ cipher.encryptBlock(x917pool, 0, x917pool, 0);
+ System.arraycopy(x917pool, 0, buf, off, copy);
+ cipher.encryptBlock(x917pool, 0, x917pool, 0);
+ off += copy;
+ x917count++;
+ }
+ }
+
+ /**
+ * Add random data always immediately available into the random pool, such as
+ * the values of the eight asynchronous counters, the current time, the
+ * current memory usage, the calling thread name, and the current stack trace.
+ * <p>
+ * This method does not alter the quality counter, and is provided more to
+ * maintain randomness, not to seriously improve the current random state.
+ */
+ private void fastPoll()
+ {
+ byte b = 0;
+ for (int i = 0; i < SPINNER_COUNT; i++)
+ b ^= SPINNERS[i].counter;
+ addRandomByte(b);
+ addRandomByte((byte) System.currentTimeMillis());
+ addRandomByte((byte) Runtime.getRuntime().freeMemory());
+ String s = Thread.currentThread().getName();
+ if (s != null)
+ {
+ byte[] buf = s.getBytes();
+ addRandomBytes(buf, 0, buf.length);
+ }
+ ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
+ PrintStream pout = new PrintStream(bout);
+ Throwable t = new Throwable();
+ t.printStackTrace(pout);
+ pout.flush();
+ byte[] buf = bout.toByteArray();
+ addRandomBytes(buf, 0, buf.length);
+ }
+
+ private void slowPoll() throws LimitReachedException
+ {
+ if (Configuration.DEBUG)
+ log.fine("poller is alive? "
+ + (pollerThread == null ? false : pollerThread.isAlive()));
+ if (pollerThread == null || ! pollerThread.isAlive())
+ {
+ boolean interrupted = false;
+ pollerThread = new Thread(poller);
+ pollerThread.setDaemon(true);
+ pollerThread.setPriority(Thread.NORM_PRIORITY - 1);
+ pollerThread.start();
+ if (blocking)
+ try
+ {
+ pollerThread.join();
+ }
+ catch (InterruptedException ie)
+ {
+ interrupted = true;
+ }
+ // If the full slow poll has completed after we waited for it,
+ // and there in insufficient randomness, throw an exception.
+ if (! interrupted && blocking && quality < 100.0)
+ {
+ if (Configuration.DEBUG)
+ log.fine("insufficient quality: " + quality);
+ throw new LimitReachedException("insufficient randomness was polled");
+ }
+ }
+ }
+
+ protected void finalize() throws Throwable
+ {
+ if (poller != null && pollerThread != null && pollerThread.isAlive())
+ {
+ pollerThread.interrupt();
+ poller.stopUpdating();
+ pollerThread.interrupt();
+ }
+ Arrays.fill(pool, (byte) 0);
+ Arrays.fill(x917pool, (byte) 0);
+ Arrays.fill(buffer, (byte) 0);
+ }
+
+ /**
+ * A simple thread that constantly updates a byte counter. This class is used
+ * in a group of lowest-priority threads and the values of their counters
+ * (updated in competition with all other threads) is used as a source of
+ * entropy bits.
+ */
+ private static class Spinner
+ implements Runnable
+ {
+ protected byte counter;
+
+ private Spinner()
+ {
+ }
+
+ public void run()
+ {
+ while (true)
+ {
+ counter++;
+ try
+ {
+ Thread.sleep(100);
+ }
+ catch (InterruptedException ie)
+ {
+ }
+ }
+ }
+ }
+
+ private final class Poller
+ implements Runnable
+ {
+ private final List files;
+ private final List urls;
+ private final List progs;
+ private final List other;
+ private final CSPRNG pool;
+ private boolean running;
+
+ Poller(List files, List urls, List progs, List other, CSPRNG pool)
+ {
+ super();
+ this.files = Collections.unmodifiableList(files);
+ this.urls = Collections.unmodifiableList(urls);
+ this.progs = Collections.unmodifiableList(progs);
+ this.other = Collections.unmodifiableList(other);
+ this.pool = pool;
+ }
+
+ public void run()
+ {
+ running = true;
+ if (Configuration.DEBUG)
+ {
+ log.fine("files: " + files);
+ log.fine("URLs: " + urls);
+ log.fine("progs: " + progs);
+ }
+ Iterator files_it = files.iterator();
+ Iterator urls_it = urls.iterator();
+ Iterator prog_it = progs.iterator();
+ Iterator other_it = other.iterator();
+
+ while (files_it.hasNext() || urls_it.hasNext() || prog_it.hasNext()
+ || other_it.hasNext())
+ {
+ // There is enough random data. Go away.
+ if (pool.getQuality() >= 100.0 || ! running)
+ return;
+ if (files_it.hasNext())
+ try
+ {
+ List l = (List) files_it.next();
+ if (Configuration.DEBUG)
+ log.fine(l.toString());
+ double qual = ((Double) l.get(0)).doubleValue();
+ int offset = ((Integer) l.get(1)).intValue();
+ int count = ((Integer) l.get(2)).intValue();
+ String src = (String) l.get(3);
+ InputStream in = new FileInputStream(src);
+ byte[] buf = new byte[count];
+ if (offset > 0)
+ in.skip(offset);
+ int len = in.read(buf);
+ if (len >= 0)
+ {
+ pool.addRandomBytes(buf, 0, len);
+ pool.addQuality(qual * ((double) len / (double) count));
+ }
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
+ }
+ catch (Exception x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
+ }
+ if (pool.getQuality() >= 100.0 || ! running)
+ return;
+ if (urls_it.hasNext())
+ try
+ {
+ List l = (List) urls_it.next();
+ if (Configuration.DEBUG)
+ log.fine(l.toString());
+ double qual = ((Double) l.get(0)).doubleValue();
+ int offset = ((Integer) l.get(1)).intValue();
+ int count = ((Integer) l.get(2)).intValue();
+ URL src = (URL) l.get(3);
+ InputStream in = src.openStream();
+ byte[] buf = new byte[count];
+ if (offset > 0)
+ in.skip(offset);
+ int len = in.read(buf);
+ if (len >= 0)
+ {
+ pool.addRandomBytes(buf, 0, len);
+ pool.addQuality(qual * ((double) len / (double) count));
+ }
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
+ }
+ catch (Exception x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
+ }
+ if (pool.getQuality() >= 100.0 || ! running)
+ return;
+ Process proc = null;
+ if (prog_it.hasNext())
+ try
+ {
+ List l = (List) prog_it.next();
+ if (Configuration.DEBUG)
+ log.finer(l.toString());
+ double qual = ((Double) l.get(0)).doubleValue();
+ int offset = ((Integer) l.get(1)).intValue();
+ int count = ((Integer) l.get(2)).intValue();
+ String src = (String) l.get(3);
+ proc = null;
+ proc = Runtime.getRuntime().exec(src);
+ InputStream in = proc.getInputStream();
+ byte[] buf = new byte[count];
+ if (offset > 0)
+ in.skip(offset);
+ int len = in.read(buf);
+ if (len >= 0)
+ {
+ pool.addRandomBytes(buf, 0, len);
+ pool.addQuality(qual * ((double) len / (double) count));
+ }
+ proc.destroy();
+ proc.waitFor();
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
+ }
+ catch (Exception x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
+ try
+ {
+ if (proc != null)
+ {
+ proc.destroy();
+ proc.waitFor();
+ }
+ }
+ catch (Exception ignored)
+ {
+ }
+ }
+ if (pool.getQuality() >= 100.0 || ! running)
+ return;
+ if (other_it.hasNext())
+ try
+ {
+ EntropySource src = (EntropySource) other_it.next();
+ byte[] buf = src.nextBytes();
+ if (pool == null)
+ return;
+ pool.addRandomBytes(buf, 0, buf.length);
+ pool.addQuality(src.quality());
+ if (Configuration.DEBUG)
+ log.fine("got " + buf.length + " bytes from " + src);
+ }
+ catch (Exception x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
+ }
+ }
+ }
+
+ public void stopUpdating()
+ {
+ running = false;
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,349 @@
+/* Fortuna.java -- The Fortuna PRNG.
+ 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.javax.crypto.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.prng.RandomEvent;
+import gnu.java.security.prng.RandomEventListener;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * The Fortuna continuously-seeded pseudo-random number generator. This
+ * generator is composed of two major pieces: the entropy accumulator and the
+ * generator function. The former takes in random bits and incorporates them
+ * into the generator's state. The latter takes this base entropy and generates
+ * pseudo-random bits from it.
+ * <p>
+ * There are some things users of this class <em>must</em> be aware of:
+ * <dl>
+ * <dt>Adding Random Data</dt>
+ * <dd>This class does not do any polling of random sources, but rather
+ * provides an interface for adding random events. Applications that use this
+ * code <em>must</em> provide this mechanism. We use this design because an
+ * application writer who knows the system he is targeting is in a better
+ * position to judge what random data is available.</dd>
+ * <dt>Storing the Seed</dt>
+ * <dd>This class implements {@link Serializable} in such a way that it writes
+ * a 64 byte seed to the stream, and reads it back again when being
+ * deserialized. This is the extent of seed file management, however, and those
+ * using this class are encouraged to think deeply about when, how often, and
+ * where to store the seed.</dd>
+ * </dl>
+ * <p>
+ * <b>References:</b>
+ * <ul>
+ * <li>Niels Ferguson and Bruce Schneier, <i>Practical Cryptography</i>, pp.
+ * 155--184. Wiley Publishing, Indianapolis. (2003 Niels Ferguson and Bruce
+ * Schneier). ISBN 0-471-22357-3.</li>
+ * </ul>
+ */
+public class Fortuna
+ extends BasePRNG
+ implements Serializable, RandomEventListener
+{
+ private static final long serialVersionUID = 0xFACADE;
+ private static final int SEED_FILE_SIZE = 64;
+ private static final int NUM_POOLS = 32;
+ private static final int MIN_POOL_SIZE = 64;
+ private final Generator generator;
+ private final IMessageDigest[] pools;
+ private long lastReseed;
+ private int pool;
+ private int pool0Count;
+ private int reseedCount;
+ public static final String SEED = "gnu.crypto.prng.fortuna.seed";
+
+ public Fortuna()
+ {
+ super(Registry.FORTUNA_PRNG);
+ generator = new Generator(CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER),
+ HashFactory.getInstance(Registry.SHA256_HASH));
+ pools = new IMessageDigest[NUM_POOLS];
+ for (int i = 0; i < NUM_POOLS; i++)
+ pools[i] = HashFactory.getInstance(Registry.SHA256_HASH);
+ lastReseed = 0;
+ pool = 0;
+ pool0Count = 0;
+ buffer = new byte[256];
+ }
+
+ public void setup(Map attributes)
+ {
+ lastReseed = 0;
+ reseedCount = 0;
+ pool = 0;
+ pool0Count = 0;
+ generator.init(attributes);
+ try
+ {
+ fillBlock();
+ }
+ catch (LimitReachedException shouldNotHappen)
+ {
+ throw new RuntimeException(shouldNotHappen);
+ }
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ if (pool0Count >= MIN_POOL_SIZE
+ && System.currentTimeMillis() - lastReseed > 100)
+ {
+ reseedCount++;
+ byte[] seed = new byte[0];
+ for (int i = 0; i < NUM_POOLS; i++)
+ if (reseedCount % (1 << i) == 0)
+ generator.addRandomBytes(pools[i].digest());
+ lastReseed = System.currentTimeMillis();
+ pool0Count = 0;
+ }
+ generator.nextBytes(buffer);
+ }
+
+ public void addRandomByte(byte b)
+ {
+ pools[pool].update(b);
+ if (pool == 0)
+ pool0Count++;
+ pool = (pool + 1) % NUM_POOLS;
+ }
+
+ public void addRandomBytes(byte[] buf, int offset, int length)
+ {
+ pools[pool].update(buf, offset, length);
+ if (pool == 0)
+ pool0Count += length;
+ pool = (pool + 1) % NUM_POOLS;
+ }
+
+ public void addRandomEvent(RandomEvent event)
+ {
+ if (event.getPoolNumber() < 0 || event.getPoolNumber() >= pools.length)
+ throw new IllegalArgumentException("pool number out of range: "
+ + event.getPoolNumber());
+ pools[event.getPoolNumber()].update(event.getSourceNumber());
+ pools[event.getPoolNumber()].update((byte) event.getData().length);
+ pools[event.getPoolNumber()].update(event.getData());
+ if (event.getPoolNumber() == 0)
+ pool0Count += event.getData().length;
+ }
+
+ // Reading and writing this object is equivalent to storing and retrieving
+ // the seed.
+
+ private void writeObject(ObjectOutputStream out) throws IOException
+ {
+ byte[] seed = new byte[SEED_FILE_SIZE];
+ try
+ {
+ generator.nextBytes(seed);
+ }
+ catch (LimitReachedException shouldNeverHappen)
+ {
+ throw new Error(shouldNeverHappen);
+ }
+ out.write(seed);
+ }
+
+ private void readObject(ObjectInputStream in) throws IOException
+ {
+ byte[] seed = new byte[SEED_FILE_SIZE];
+ in.readFully(seed);
+ generator.addRandomBytes(seed);
+ }
+
+ /**
+ * The Fortuna generator function. The generator is a PRNG in its own right;
+ * Fortuna itself is basically a wrapper around this generator that manages
+ * reseeding in a secure way.
+ */
+ public static class Generator
+ extends BasePRNG
+ implements Cloneable
+ {
+ private static final int LIMIT = 1 << 20;
+ private final IBlockCipher cipher;
+ private final IMessageDigest hash;
+ private final byte[] counter;
+ private final byte[] key;
+ private boolean seeded;
+
+ public Generator(final IBlockCipher cipher, final IMessageDigest hash)
+ {
+ super(Registry.FORTUNA_GENERATOR_PRNG);
+ this.cipher = cipher;
+ this.hash = hash;
+ counter = new byte[cipher.defaultBlockSize()];
+ buffer = new byte[cipher.defaultBlockSize()];
+ int keysize = 0;
+ for (Iterator it = cipher.keySizes(); it.hasNext();)
+ {
+ int ks = ((Integer) it.next()).intValue();
+ if (ks > keysize)
+ keysize = ks;
+ if (keysize >= 32)
+ break;
+ }
+ key = new byte[keysize];
+ }
+
+ public byte nextByte()
+ {
+ byte[] b = new byte[1];
+ nextBytes(b, 0, 1);
+ return b[0];
+ }
+
+ public void nextBytes(byte[] out, int offset, int length)
+ {
+ if (! seeded)
+ throw new IllegalStateException("generator not seeded");
+ int count = 0;
+ do
+ {
+ int amount = Math.min(LIMIT, length - count);
+ try
+ {
+ super.nextBytes(out, offset + count, amount);
+ }
+ catch (LimitReachedException shouldNeverHappen)
+ {
+ throw new Error(shouldNeverHappen);
+ }
+ count += amount;
+ for (int i = 0; i < key.length; i += counter.length)
+ {
+ fillBlock();
+ int l = Math.min(key.length - i, cipher.currentBlockSize());
+ System.arraycopy(buffer, 0, key, i, l);
+ }
+ resetKey();
+ }
+ while (count < length);
+ fillBlock();
+ ndx = 0;
+ }
+
+ public void addRandomByte(byte b)
+ {
+ addRandomBytes(new byte[] { b });
+ }
+
+ public void addRandomBytes(byte[] seed, int offset, int length)
+ {
+ hash.update(key);
+ hash.update(seed, offset, length);
+ byte[] newkey = hash.digest();
+ System.arraycopy(newkey, 0, key, 0, Math.min(key.length, newkey.length));
+ resetKey();
+ incrementCounter();
+ seeded = true;
+ }
+
+ public void fillBlock()
+ {
+ if (! seeded)
+ throw new IllegalStateException("generator not seeded");
+ cipher.encryptBlock(counter, 0, buffer, 0);
+ incrementCounter();
+ }
+
+ public void setup(Map attributes)
+ {
+ seeded = false;
+ Arrays.fill(key, (byte) 0);
+ Arrays.fill(counter, (byte) 0);
+ byte[] seed = (byte[]) attributes.get(SEED);
+ if (seed != null)
+ addRandomBytes(seed);
+ fillBlock();
+ }
+
+ /**
+ * Resets the cipher's key. This is done after every reseed, which combines
+ * the old key and the seed, and processes that throigh the hash function.
+ */
+ private void resetKey()
+ {
+ try
+ {
+ cipher.reset();
+ cipher.init(Collections.singletonMap(IBlockCipher.KEY_MATERIAL, key));
+ }
+ // We expect to never get an exception here.
+ catch (InvalidKeyException ike)
+ {
+ throw new Error(ike);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ throw new Error(iae);
+ }
+ }
+
+ /**
+ * Increment `counter' as a sixteen-byte little-endian unsigned integer by
+ * one.
+ */
+ private void incrementCounter()
+ {
+ for (int i = 0; i < counter.length; i++)
+ {
+ counter[i]++;
+ if (counter[i] != 0)
+ break;
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ICMGenerator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ICMGenerator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ICMGenerator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/ICMGenerator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,297 @@
+/* ICMGenerator.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Counter Mode is a way to define a pseudorandom keystream generator using a
+ * block cipher. The keystream can be used for additive encryption, key
+ * derivation, or any other application requiring pseudorandom data.
+ * <p>
+ * In ICM, the keystream is logically broken into segments. Each segment is
+ * identified with a segment index, and the segments have equal lengths. This
+ * segmentation makes ICM especially appropriate for securing packet-based
+ * protocols.
+ * <p>
+ * This implementation adheres to the definition of the ICM keystream generation
+ * function that allows for any symetric key block cipher algorithm
+ * (initialisation parameter <code>gnu.crypto.prng.icm.cipher.name</code>
+ * taken to be an instance of {@link java.lang.String}) to be used. If such a
+ * parameter is not defined/included in the initialisation <code>Map</code>,
+ * then the "Rijndael" algorithm is used. Furthermore, if the initialisation
+ * parameter <code>gnu.crypto.cipher.block.size</code> (taken to be a instance
+ * of {@link java.lang.Integer}) is missing or undefined in the initialisation
+ * <code>Map</code>, then the cipher's <em>default</em> block size is used.
+ * <p>
+ * The practical limits and constraints of such generator are:
+ * <ul>
+ * <li>The number of blocks in any segment <b>MUST NOT</b> exceed <code>
+ * 256 ** BLOCK_INDEX_LENGTH</code>.
+ * The number of segments <b>MUST NOT</b> exceed
+ * <code>256 ** SEGMENT_INDEX_LENGTH</code>. These restrictions ensure the
+ * uniqueness of each block cipher input.</li>
+ * <li>Each segment contains <code>SEGMENT_LENGTH</code> octets; this value
+ * <b>MUST NOT</b> exceed the value <code>(256 ** BLOCK_INDEX_LENGTH) *
+ * BLOCK_LENGTH</code>.</li>
+ * <li>The sum of <code>SEGMENT_INDEX_LENGTH</code> and
+ * <code>BLOCK_INDEX_LENGTH</code> <b>MUST NOT</b> exceed <code>BLOCK_LENGTH
+ * / 2</code>.
+ * This requirement protects the ICM keystream generator from potentially
+ * failing to be pseudorandom.</li>
+ * </ul>
+ * <p>
+ * <b>NOTE</b>: Rijndael is used as the default symmetric key block cipher
+ * algorithm because, with its default block and key sizes, it is the AES. Yet
+ * being Rijndael, the algorithm offers more versatile block and key sizes which
+ * may prove to be useful for generating <em>longer</em> key streams.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.ietf.org/internet-drafts/draft-mcgrew-saag-icm-00.txt">
+ * Integer Counter Mode</a>, David A. McGrew.</li>
+ * </ol>
+ */
+public class ICMGenerator
+ extends BasePRNG
+ implements Cloneable
+{
+ /** Property name of underlying block cipher for this ICM generator. */
+ public static final String CIPHER = "gnu.crypto.prng.icm.cipher.name";
+ /** Property name of ICM's block index length. */
+ public static final String BLOCK_INDEX_LENGTH =
+ "gnu.crypto.prng.icm.block.index.length";
+ /** Property name of ICM's segment index length. */
+ public static final String SEGMENT_INDEX_LENGTH =
+ "gnu.crypto.prng.icm.segment.index.length";
+ /** Property name of ICM's offset. */
+ public static final String OFFSET = "gnu.crypto.prng.icm.offset";
+ /** Property name of ICM's segment index. */
+ public static final String SEGMENT_INDEX = "gnu.crypto.prng.icm.segment.index";
+ /** The integer value 256 as a BigInteger. */
+ private static final BigInteger TWO_FIFTY_SIX = new BigInteger("256");
+ /** The underlying cipher implementation. */
+ private IBlockCipher cipher;
+ /** This keystream block index length in bytes. */
+ private int blockNdxLength = -1;
+ /** This keystream segment index length in bytes. */
+ private int segmentNdxLength = -1;
+ /** The index of the next block for a given keystream segment. */
+ private BigInteger blockNdx = BigInteger.ZERO;
+ /** The segment index for this keystream. */
+ private BigInteger segmentNdx;
+ /** The initial counter for a given keystream segment. */
+ private BigInteger C0;
+
+ /** Trivial 0-arguments constructor. */
+ public ICMGenerator()
+ {
+ super(Registry.ICM_PRNG);
+ }
+
+ // Conceptually, ICM is a keystream generator that takes a secret key and a
+ // segment index as an input and then outputs a keystream segment. The
+ // segmentation lends itself to packet encryption, as each keystream segment
+ // can be used to encrypt a distinct packet.
+ //
+ // An ICM key consists of the block cipher key and an Offset. The Offset is
+ // an integer with BLOCK_LENGTH octets...
+ public void setup(Map attributes)
+ {
+ // find out which cipher algorithm to use
+ boolean newCipher = true;
+ String underlyingCipher = (String) attributes.get(CIPHER);
+ if (underlyingCipher == null)
+ if (cipher == null) // happy birthday
+ // ensure we have a reliable implementation of this cipher
+ cipher = CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER);
+ else
+ // we already have one. use it as is
+ newCipher = false;
+ else // ensure we have a reliable implementation of this cipher
+ cipher = CipherFactory.getInstance(underlyingCipher);
+
+ // find out what block size we should use it in
+ int cipherBlockSize = 0;
+ Integer bs = (Integer) attributes.get(IBlockCipher.CIPHER_BLOCK_SIZE);
+ if (bs != null)
+ cipherBlockSize = bs.intValue();
+ else
+ {
+ if (newCipher) // assume we'll use its default block size
+ cipherBlockSize = cipher.defaultBlockSize();
+ // else use as is
+ }
+ // get the key material
+ byte[] key = (byte[]) attributes.get(IBlockCipher.KEY_MATERIAL);
+ if (key == null)
+ throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
+ // now initialise the cipher
+ HashMap map = new HashMap();
+ if (cipherBlockSize != 0) // only needed if new or changed
+ map.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
+ map.put(IBlockCipher.KEY_MATERIAL, key);
+ try
+ {
+ cipher.init(map);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
+ }
+ // at this point we have an initialised (new or otherwise) cipher
+ // ensure that remaining params make sense
+ cipherBlockSize = cipher.currentBlockSize();
+ BigInteger counterRange = TWO_FIFTY_SIX.pow(cipherBlockSize);
+ // offset, like the underlying cipher key is not cloneable
+ // always look for it and throw an exception if it's not there
+ Object obj = attributes.get(OFFSET);
+ // allow either a byte[] or a BigInteger
+ BigInteger r;
+ if (obj instanceof BigInteger)
+ r = (BigInteger) obj;
+ else // assume byte[]. should be same length as cipher block size
+ {
+ byte[] offset = (byte[]) obj;
+ if (offset.length != cipherBlockSize)
+ throw new IllegalArgumentException(OFFSET);
+ r = new BigInteger(1, offset);
+ }
+ int wantBlockNdxLength = -1; // number of octets in the block index
+ Integer i = (Integer) attributes.get(BLOCK_INDEX_LENGTH);
+ if (i != null)
+ {
+ wantBlockNdxLength = i.intValue();
+ if (wantBlockNdxLength < 1)
+ throw new IllegalArgumentException(BLOCK_INDEX_LENGTH);
+ }
+ int wantSegmentNdxLength = -1; // number of octets in the segment index
+ i = (Integer) attributes.get(SEGMENT_INDEX_LENGTH);
+ if (i != null)
+ {
+ wantSegmentNdxLength = i.intValue();
+ if (wantSegmentNdxLength < 1)
+ throw new IllegalArgumentException(SEGMENT_INDEX_LENGTH);
+ }
+ // if both are undefined check if it's a reuse
+ if ((wantBlockNdxLength == -1) && (wantSegmentNdxLength == -1))
+ {
+ if (blockNdxLength == -1) // new instance
+ throw new IllegalArgumentException(BLOCK_INDEX_LENGTH + ", "
+ + SEGMENT_INDEX_LENGTH);
+ // else reuse old values
+ }
+ else // only one is undefined, set it to BLOCK_LENGTH/2 minus the other
+ {
+ int limit = cipherBlockSize / 2;
+ if (wantBlockNdxLength == -1)
+ wantBlockNdxLength = limit - wantSegmentNdxLength;
+ else if (wantSegmentNdxLength == -1)
+ wantSegmentNdxLength = limit - wantBlockNdxLength;
+ else if ((wantSegmentNdxLength + wantBlockNdxLength) > limit)
+ throw new IllegalArgumentException(BLOCK_INDEX_LENGTH + ", "
+ + SEGMENT_INDEX_LENGTH);
+ // save new values
+ blockNdxLength = wantBlockNdxLength;
+ segmentNdxLength = wantSegmentNdxLength;
+ }
+ // get the segment index as a BigInteger
+ BigInteger s = (BigInteger) attributes.get(SEGMENT_INDEX);
+ if (s == null)
+ {
+ if (segmentNdx == null) // segment index was never set
+ throw new IllegalArgumentException(SEGMENT_INDEX);
+ // reuse; check if still valid
+ if (segmentNdx.compareTo(TWO_FIFTY_SIX.pow(segmentNdxLength)) > 0)
+ throw new IllegalArgumentException(SEGMENT_INDEX);
+ }
+ else
+ {
+ if (s.compareTo(TWO_FIFTY_SIX.pow(segmentNdxLength)) > 0)
+ throw new IllegalArgumentException(SEGMENT_INDEX);
+ segmentNdx = s;
+ }
+ // The initial counter of the keystream segment with segment index s is
+ // defined as follows, where r denotes the Offset:
+ //
+ // C[0] = (s * (256^BLOCK_INDEX_LENGTH) + r) modulo (256^BLOCK_LENGTH)
+ C0 = segmentNdx.multiply(TWO_FIFTY_SIX.pow(blockNdxLength))
+ .add(r).modPow(BigInteger.ONE, counterRange);
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ if (C0 == null)
+ throw new IllegalStateException();
+ if (blockNdx.compareTo(TWO_FIFTY_SIX.pow(blockNdxLength)) >= 0)
+ throw new LimitReachedException();
+ int cipherBlockSize = cipher.currentBlockSize();
+ BigInteger counterRange = TWO_FIFTY_SIX.pow(cipherBlockSize);
+ // encrypt the counter for the current blockNdx
+ // C[i] = (C[0] + i) modulo (256^BLOCK_LENGTH).
+ BigInteger Ci = C0.add(blockNdx).modPow(BigInteger.ONE, counterRange);
+ buffer = Ci.toByteArray();
+ int limit = buffer.length;
+ if (limit < cipherBlockSize)
+ {
+ byte[] data = new byte[cipherBlockSize];
+ System.arraycopy(buffer, 0, data, cipherBlockSize - limit, limit);
+ buffer = data;
+ }
+ else if (limit > cipherBlockSize)
+ {
+ byte[] data = new byte[cipherBlockSize];
+ System.arraycopy(buffer, limit - cipherBlockSize, data, 0,
+ cipherBlockSize);
+ buffer = data;
+ }
+ cipher.encryptBlock(buffer, 0, buffer, 0);
+ blockNdx = blockNdx.add(BigInteger.ONE); // increment blockNdx
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/IPBE.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/IPBE.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/IPBE.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/IPBE.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,81 @@
+/* IPBE.java --
+ Copyright (C) 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.javax.crypto.prng;
+
+/**
+ * Trivial interface to group Password-based encryption property names and
+ * constants.
+ */
+public interface IPBE
+{
+ /**
+ * Property name for the iteration count in a PBE algorithm. The property
+ * associated with this is expected to be an {@link Integer}.
+ */
+ String ITERATION_COUNT = "gnu.crypto.pbe.iteration.count";
+
+ /**
+ * Property name for the password in a PBE algorithm. The property associated
+ * with this is expected to be a char array.
+ */
+ String PASSWORD = "gnu.crypto.pbe.password";
+
+ /**
+ * Property name for the password character encoding in a PBE algorithm. The
+ * property associated with this is expected to be a String denoting a valid
+ * character-encoding name. If this property is not set, and a password is
+ * used, then {@link #DEFAULT_PASSWORD_ENCODING} will be used when converting
+ * the password character(s) to bytes.
+ */
+ String PASSWORD_ENCODING = "gnu.crypto.pbe.password.encoding";
+
+ /**
+ * Property name for the salt in a PBE algorithm. The property associated
+ * with this is expected to be a byte array.
+ */
+ String SALT = "gnu.crypto.pbe.salt";
+
+ /**
+ * The default character set encoding name to be used if (a) a password is
+ * to be used as the source for a PBE-based Key Derivation Function (KDF) and
+ * (b) no character set encoding name was specified among the attributes used
+ * to initialize the instance.
+ */
+ String DEFAULT_PASSWORD_ENCODING = "UTF-8";
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PBKDF2.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PBKDF2.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PBKDF2.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PBKDF2.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,184 @@
+/* PBKDF2.java --
+ Copyright (C) 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.javax.crypto.prng;
+
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.mac.HMac;
+import gnu.javax.crypto.mac.IMac;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * An implementation of the <i>key derivation function</i> KDF2 from PKCS #5:
+ * Password-Based Cryptography (<b>PBE</b>). This KDF is essentially a way to
+ * transform a password and a salt into a stream of random bytes, which may then
+ * be used to initialize a cipher or a MAC.
+ * <p>
+ * This version uses a MAC as its pseudo-random function, and the password is
+ * used as the key.
+ * <p>
+ * References:
+ * <ol>
+ * <li>B. Kaliski, <a href="http://www.ietf.org/rfc/rfc2898.txt">RFC 2898:
+ * Password-Based Cryptography Specification, Version 2.0</a></li>
+ * </ol>
+ */
+public class PBKDF2
+ extends BasePRNG
+ implements Cloneable
+{
+ /**
+ * The bytes fed into the MAC. This is initially the concatenation of the salt
+ * and the block number.
+ */
+ private byte[] in;
+ /** The iteration count. */
+ private int iterationCount;
+ /** The salt. */
+ private byte[] salt;
+ /** The MAC (the pseudo-random function we use). */
+ private IMac mac;
+ /** The number of hLen-sized blocks generated. */
+ private long count;
+
+ /**
+ * Creates a new PBKDF2 object. The argument is the MAC that will serve as the
+ * pseudo-random function. The MAC does not need to be initialized.
+ *
+ * @param mac The pseudo-random function.
+ */
+ public PBKDF2(IMac mac)
+ {
+ super("PBKDF2-" + mac.name());
+ this.mac = mac;
+ iterationCount = -1;
+ }
+
+ public void setup(Map attributes)
+ {
+ Map macAttrib = new HashMap();
+ macAttrib.put(HMac.USE_WITH_PKCS5_V2, Boolean.TRUE);
+ byte[] s = (byte[]) attributes.get(IPBE.SALT);
+ if (s == null)
+ {
+ if (salt == null)
+ throw new IllegalArgumentException("no salt specified");
+ // Otherwise re-use.
+ }
+ else
+ salt = s;
+ byte[] macKeyMaterial;
+ char[] password = (char[]) attributes.get(IPBE.PASSWORD);
+ if (password != null)
+ {
+ String encoding = (String) attributes.get(IPBE.PASSWORD_ENCODING);
+ if (encoding == null || encoding.trim().length() == 0)
+ encoding = IPBE.DEFAULT_PASSWORD_ENCODING;
+ else
+ encoding = encoding.trim();
+ try
+ {
+ macKeyMaterial = new String(password).getBytes(encoding);
+ }
+ catch (UnsupportedEncodingException uee)
+ {
+ throw new IllegalArgumentException("Unknown or unsupported encoding: "
+ + encoding, uee);
+ }
+ }
+ else
+ macKeyMaterial = (byte[]) attributes.get(IMac.MAC_KEY_MATERIAL);
+
+ if (macKeyMaterial != null)
+ macAttrib.put(IMac.MAC_KEY_MATERIAL, macKeyMaterial);
+ else if (! initialised)
+ throw new IllegalArgumentException(
+ "Neither password nor key-material were specified");
+ // otherwise re-use previous password/key-material
+ try
+ {
+ mac.init(macAttrib);
+ }
+ catch (Exception x)
+ {
+ throw new IllegalArgumentException(x.getMessage());
+ }
+ Integer ic = (Integer) attributes.get(IPBE.ITERATION_COUNT);
+ if (ic != null)
+ iterationCount = ic.intValue();
+ if (iterationCount <= 0)
+ throw new IllegalArgumentException("bad iteration count");
+ count = 0L;
+ buffer = new byte[mac.macSize()];
+ try
+ {
+ fillBlock();
+ }
+ catch (LimitReachedException x)
+ {
+ throw new Error(x.getMessage());
+ }
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ if (++count > ((1L << 32) - 1))
+ throw new LimitReachedException();
+ Arrays.fill(buffer, (byte) 0x00);
+ int limit = salt.length;
+ in = new byte[limit + 4];
+ System.arraycopy(salt, 0, in, 0, salt.length);
+ in[limit++] = (byte)(count >>> 24);
+ in[limit++] = (byte)(count >>> 16);
+ in[limit++] = (byte)(count >>> 8);
+ in[limit ] = (byte) count;
+ for (int i = 0; i < iterationCount; i++)
+ {
+ mac.reset();
+ mac.update(in, 0, in.length);
+ in = mac.digest();
+ for (int j = 0; j < buffer.length; j++)
+ buffer[j] ^= in[j];
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,115 @@
+/* PRNGFactory.java --
+ 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.javax.crypto.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.IRandom;
+import gnu.javax.crypto.mac.HMacFactory;
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * A Factory to instantiate pseudo random number generators.
+ */
+public class PRNGFactory
+ implements Registry
+{
+ /** Trivial constructor to enforce <i>Singleton</i> pattern. */
+ private PRNGFactory()
+ {
+ }
+
+ /**
+ * Returns an instance of a padding algorithm given its name.
+ *
+ * @param prng the case-insensitive name of the PRNG.
+ * @return an instance of the pseudo-random number generator.
+ * @exception InternalError if the implementation does not pass its self-
+ * test.
+ */
+ public static IRandom getInstance(String prng)
+ {
+ if (prng == null)
+ return null;
+ prng = prng.trim();
+ IRandom result = null;
+ if (prng.equalsIgnoreCase(ARCFOUR_PRNG) || prng.equalsIgnoreCase(RC4_PRNG))
+ result = new ARCFour();
+ else if (prng.equalsIgnoreCase(ICM_PRNG))
+ result = new ICMGenerator();
+ else if (prng.equalsIgnoreCase(UMAC_PRNG))
+ result = new UMacGenerator();
+ else if (prng.toLowerCase().startsWith(PBKDF2_PRNG_PREFIX))
+ {
+ String macName = prng.substring(PBKDF2_PRNG_PREFIX.length());
+ IMac mac = MacFactory.getInstance(macName);
+ if (mac == null)
+ return null;
+ result = new PBKDF2(mac);
+ }
+
+ if (result != null)
+ return result;
+
+ return gnu.java.security.prng.PRNGFactory.getInstance(prng);
+ }
+
+ /**
+ * Returns a {@link Set} of names of padding algorithms supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of pseudo-random number generator algorithm names
+ * (Strings).
+ */
+ public static Set getNames()
+ {
+ HashSet hs = new HashSet(gnu.java.security.prng.PRNGFactory.getNames());
+ hs.add(ICM_PRNG);
+ hs.add(UMAC_PRNG);
+ // add all hmac implementations as candidate PBKDF2 ones too
+ for (Iterator it = HMacFactory.getNames().iterator(); it.hasNext();)
+ hs.add(PBKDF2_PRNG_PREFIX + ((String) it.next()));
+ return Collections.unmodifiableSet(hs);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,186 @@
+/* UMacGenerator.java --
+ Copyright (C) 2001, 2002, 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.javax.crypto.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.BasePRNG;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.security.InvalidKeyException;
+
+/**
+ * <i>KDF</i>s (Key Derivation Functions) are used to stretch user-supplied key
+ * material to specific size(s) required by high level cryptographic primitives.
+ * Described in the <A
+ * HREF="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">UMAC</A>
+ * paper, this function basically operates an underlying <em>symmetric key block
+ * cipher</em> instance in output feedback mode (OFB), as a <b>strong</b>
+ * pseudo-random number generator.
+ * <p>
+ * <code>UMacGenerator</code> requires an <em>index</em> parameter
+ * (initialisation parameter <code>gnu.crypto.prng.umac.kdf.index</code> taken
+ * to be an instance of {@link Integer} with a value between <code>0</code> and
+ * <code>255</code>). Using the same key, but different indices, generates
+ * different pseudorandom outputs.
+ * <p>
+ * This implementation generalises the definition of the
+ * <code>UmacGenerator</code> algorithm to allow for other than the AES
+ * symetric key block cipher algorithm (initialisation parameter
+ * <code>gnu.crypto.prng.umac.cipher.name</code> taken to be an instance of
+ * {@link String}). If such a parameter is not defined/included in the
+ * initialisation <code>Map</code>, then the "Rijndael" algorithm is used.
+ * Furthermore, if the initialisation parameter
+ * <code>gnu.crypto.cipher.block.size</code> (taken to be a instance of
+ * {@link Integer}) is missing or undefined in the initialisation
+ * <code>Map</code>, then the cipher's <em>default</em> block size is used.
+ * <p>
+ * <b>NOTE</b>: Rijndael is used as the default symmetric key block cipher
+ * algorithm because, with its default block and key sizes, it is the AES. Yet
+ * being Rijndael, the algorithm offers more versatile block and key sizes which
+ * may prove to be useful for generating "longer" key streams.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/internet-drafts/draft-krovetz-umac-01.txt">
+ * UMAC</a>: Message Authentication Code using Universal Hashing.<br>
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.</li>
+ * </ol>
+ */
+public class UMacGenerator
+ extends BasePRNG
+ implements Cloneable
+{
+ /**
+ * Property name of the KDF <code>index</code> value to use in this
+ * instance. The value is taken to be an {@link Integer} less than
+ * <code>256</code>.
+ */
+ public static final String INDEX = "gnu.crypto.prng.umac.index";
+ /** The name of the underlying symmetric key block cipher algorithm. */
+ public static final String CIPHER = "gnu.crypto.prng.umac.cipher.name";
+ /** The generator's underlying block cipher. */
+ private IBlockCipher cipher;
+
+ /** Trivial 0-arguments constructor. */
+ public UMacGenerator()
+ {
+ super(Registry.UMAC_PRNG);
+ }
+
+ public void setup(Map attributes)
+ {
+ boolean newCipher = true;
+ String cipherName = (String) attributes.get(CIPHER);
+ if (cipherName == null)
+ if (cipher == null) // happy birthday
+ cipher = CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER);
+ else // we already have one. use it as is
+ newCipher = false;
+ else
+ cipher = CipherFactory.getInstance(cipherName);
+ // find out what block size we should use it in
+ int cipherBlockSize = 0;
+ Integer bs = (Integer) attributes.get(IBlockCipher.CIPHER_BLOCK_SIZE);
+ if (bs != null)
+ cipherBlockSize = bs.intValue();
+ else
+ {
+ if (newCipher) // assume we'll use its default block size
+ cipherBlockSize = cipher.defaultBlockSize();
+ // else use as is
+ }
+ // get the key material
+ byte[] key = (byte[]) attributes.get(IBlockCipher.KEY_MATERIAL);
+ if (key == null)
+ throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
+
+ int keyLength = key.length;
+ // ensure that keyLength is valid for the chosen underlying cipher
+ boolean ok = false;
+ for (Iterator it = cipher.keySizes(); it.hasNext();)
+ {
+ ok = (keyLength == ((Integer) it.next()).intValue());
+ if (ok)
+ break;
+ }
+ if (! ok)
+ throw new IllegalArgumentException("key length");
+ // ensure that remaining params make sense
+ int index = -1;
+ Integer i = (Integer) attributes.get(INDEX);
+ if (i != null)
+ {
+ index = i.intValue();
+ if (index < 0 || index > 255)
+ throw new IllegalArgumentException(INDEX);
+ }
+ // now initialise the underlying cipher
+ Map map = new HashMap();
+ if (cipherBlockSize != 0) // only needed if new or changed
+ map.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
+ map.put(IBlockCipher.KEY_MATERIAL, key);
+ try
+ {
+ cipher.init(map);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
+ }
+ buffer = new byte[cipher.currentBlockSize()];
+ buffer[cipher.currentBlockSize() - 1] = (byte) index;
+ try
+ {
+ fillBlock();
+ }
+ catch (LimitReachedException impossible)
+ {
+ }
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ cipher.encryptBlock(buffer, 0, buffer, 0);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,129 @@
+/* AuthInfo.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+
+/**
+ * A static class for creating {@link IAuthInfoProvider} providers. It
+ * transparently locates and uses any provider instances, based on the value
+ * assigned to the System property with the key
+ * <code>gnu.crypto.sasl.auth.info.provider.pkgs</code>. If more than one is
+ * specified they SHOULD be separated with a vertical bar character. Please note
+ * that the GNU provider is always added last to the list, disregarding whether
+ * it was mentioned or not in the value of that property, or if it that property
+ * was not defined.
+ */
+public class AuthInfo
+{
+ private static final ArrayList factories = new ArrayList();
+ static
+ {
+ IAuthInfoProviderFactory ours = new AuthInfoProviderFactory();
+ // if SASL_AUTH_INFO_PROVIDER_PKGS is defined then parse it
+ String clazz;
+ String pkgs = System.getProperty(Registry.SASL_AUTH_INFO_PROVIDER_PKGS,
+ null);
+ if (pkgs != null)
+ {
+ for (StringTokenizer st = new StringTokenizer(pkgs, "|"); st.hasMoreTokens();)
+ {
+ clazz = st.nextToken().trim();
+ if (! "gnu.javax.crypto.sasl".equals(clazz))
+ {
+ clazz += ".AuthInfoProviderFactory";
+ try
+ {
+ IAuthInfoProviderFactory factory =
+ (IAuthInfoProviderFactory) Class.forName(clazz).newInstance();
+ factories.add(factory);
+ }
+ catch (ClassCastException ignored)
+ {
+ }
+ catch (ClassNotFoundException ignored)
+ {
+ }
+ catch (InstantiationException ignored)
+ {
+ }
+ catch (IllegalAccessException ignored)
+ {
+ }
+ }
+ }
+ }
+ // always add ours last; unless it's already there
+ if (!factories.contains(ours))
+ factories.add(ours);
+ }
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private AuthInfo()
+ {
+ super();
+ }
+
+ /**
+ * A convenience method to return the authentication information provider for
+ * a designated SASL mechnanism. It goes through all the installed provider
+ * factories, one at a time, and attempts to return a new instance of the
+ * provider for the designated mechanism. It stops at the first factory
+ * returning a non-null provider.
+ *
+ * @param mechanism the name of a SASL mechanism.
+ * @return an implementation that provides {@link IAuthInfoProvider} for that
+ * mechanism; or <code>null</code> if none found.
+ */
+ public static IAuthInfoProvider getProvider(String mechanism)
+ {
+ for (Iterator it = factories.iterator(); it.hasNext();)
+ {
+ IAuthInfoProviderFactory factory = (IAuthInfoProviderFactory) it.next();
+ IAuthInfoProvider result = factory.getInstance(mechanism);
+ if (result != null)
+ return result;
+ }
+ return null;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,67 @@
+/* AuthInfoProviderFactory.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.crammd5.CramMD5AuthInfoProvider;
+import gnu.javax.crypto.sasl.plain.PlainAuthInfoProvider;
+import gnu.javax.crypto.sasl.srp.SRPAuthInfoProvider;
+
+/**
+ * The concrete SASL authentication information provider factory.
+ */
+public class AuthInfoProviderFactory
+ implements IAuthInfoProviderFactory
+{
+ // implicit 0-args constructor
+
+ public IAuthInfoProvider getInstance(String mechanism)
+ {
+ if (mechanism == null)
+ return null;
+ mechanism = mechanism.trim().toUpperCase();
+ if (mechanism.startsWith(Registry.SASL_SRP_MECHANISM))
+ return new SRPAuthInfoProvider();
+ if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
+ return new CramMD5AuthInfoProvider();
+ if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
+ return new PlainAuthInfoProvider();
+ return null;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,168 @@
+/* ClientFactory.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.anonymous.AnonymousClient;
+import gnu.javax.crypto.sasl.crammd5.CramMD5Client;
+import gnu.javax.crypto.sasl.plain.PlainClient;
+import gnu.javax.crypto.sasl.srp.SRPClient;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslClientFactory;
+import javax.security.sasl.SaslException;
+
+/**
+ * The implementation of {@link SaslClientFactory}.
+ */
+public class ClientFactory
+ implements SaslClientFactory
+{
+ // implicit 0-arguments constructor
+
+ public static final Set getNames()
+ {
+ return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
+ }
+
+ private static final String[] getNamesInternal(Map props)
+ {
+ String[] all = new String[] {
+ Registry.SASL_SRP_MECHANISM,
+ Registry.SASL_CRAM_MD5_MECHANISM,
+ Registry.SASL_PLAIN_MECHANISM,
+ Registry.SASL_ANONYMOUS_MECHANISM };
+ if (props == null)
+ return all;
+ if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props))
+ return new String[0];
+ List result = new ArrayList(all.length);
+ for (int i = 0; i < all.length;)
+ result.add(all[i++]);
+ if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_NODICTIONARY, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_NOANONYMOUS, props))
+ {
+ result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_FORWARD_SECRECY, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ return (String[]) result.toArray(new String[0]);
+ }
+
+ public static final ClientMechanism getInstance(String mechanism)
+ {
+ if (mechanism == null)
+ return null;
+ mechanism = mechanism.trim().toUpperCase();
+ if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
+ return new SRPClient();
+ if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
+ return new CramMD5Client();
+ if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
+ return new PlainClient();
+ if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
+ return new AnonymousClient();
+ return null;
+ }
+
+ public SaslClient createSaslClient(String[] mechanisms,
+ String authorisationID, String protocol,
+ String serverName, Map props,
+ CallbackHandler cbh) throws SaslException
+ {
+ ClientMechanism result = null;
+ String mechanism;
+ for (int i = 0; i < mechanisms.length; i++)
+ {
+ mechanism = mechanisms[i];
+ result = getInstance(mechanism);
+ if (result != null)
+ break;
+ }
+ if (result != null)
+ {
+ HashMap attributes = new HashMap();
+ if (props != null)
+ attributes.putAll(props);
+ attributes.put(Registry.SASL_AUTHORISATION_ID, authorisationID);
+ attributes.put(Registry.SASL_PROTOCOL, protocol);
+ attributes.put(Registry.SASL_SERVER_NAME, serverName);
+ attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
+ result.init(attributes);
+ return result;
+ }
+ throw new SaslException("No supported mechanism found in given mechanism list");
+ }
+
+ public String[] getMechanismNames(Map props)
+ {
+ return getNamesInternal(props);
+ }
+
+ private static boolean hasPolicy(String propertyName, Map props)
+ {
+ return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,293 @@
+/* ClientMechanism.java --
+ Copyright (C) 2003, 2005, 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+
+/**
+ * A base class to facilitate implementing SASL client-side mechanisms.
+ */
+public abstract class ClientMechanism
+ implements SaslClient
+{
+ /** Name of this mechanism. */
+ protected String mechanism;
+ /** The authorisation identity. */
+ protected String authorizationID;
+ /** Name of protocol using this mechanism. */
+ protected String protocol;
+ /** Name of server to authenticate to. */
+ protected String serverName;
+ /** Properties of qualities desired for this mechanism. */
+ protected Map properties;
+ /** Callback handler to use with this mechanism instance. */
+ protected CallbackHandler handler;
+ /** Channel binding data to use with this mechanism instance. */
+ protected byte[] channelBinding;
+ /** Whether authentication phase is completed (true) or not (false). */
+ protected boolean complete = false;
+ /** The state of the authentication automaton. */
+ protected int state = -1;
+
+ protected ClientMechanism(final String mechanism)
+ {
+ super();
+
+ this.mechanism = mechanism;
+ this.state = -1;
+ }
+
+ protected abstract void initMechanism() throws SaslException;
+
+ protected abstract void resetMechanism() throws SaslException;
+
+ public abstract byte[] evaluateChallenge(byte[] challenge)
+ throws SaslException;
+
+ public abstract boolean hasInitialResponse();
+
+ public boolean isComplete()
+ {
+ return complete;
+ }
+
+ public byte[] unwrap(final byte[] incoming, final int offset, final int len)
+ throws SaslException
+ {
+ if (! isComplete())
+ throw new IllegalMechanismStateException();
+ return this.engineUnwrap(incoming, offset, len);
+ }
+
+ public byte[] wrap(final byte[] outgoing, final int offset, final int len)
+ throws SaslException
+ {
+ if (! isComplete())
+ throw new IllegalMechanismStateException();
+ return this.engineWrap(outgoing, offset, len);
+ }
+
+ public String getMechanismName()
+ {
+ return mechanism;
+ }
+
+ public Object getNegotiatedProperty(final String propName)
+ {
+ if (! isComplete())
+ throw new IllegalStateException();
+ if (Sasl.QOP.equals(propName))
+ return getNegotiatedQOP();
+ if (Sasl.STRENGTH.equals(propName))
+ return getNegotiatedStrength();
+ if (Sasl.SERVER_AUTH.equals(propName))
+ return getNegotiatedServerAuth();
+ if (Sasl.MAX_BUFFER.equals(propName))
+ return getNegotiatedMaxBuffer();
+ if (Sasl.RAW_SEND_SIZE.equals(propName))
+ return getNegotiatedRawSendSize();
+ if (Sasl.POLICY_NOPLAINTEXT.equals(propName))
+ return getNegotiatedPolicyNoPlainText();
+ if (Sasl.POLICY_NOACTIVE.equals(propName))
+ return getNegotiatedPolicyNoActive();
+ if (Sasl.POLICY_NODICTIONARY.equals(propName))
+ return getNegotiatedPolicyNoDictionary();
+ if (Sasl.POLICY_NOANONYMOUS.equals(propName))
+ return getNegotiatedPolicyNoAnonymous();
+ if (Sasl.POLICY_FORWARD_SECRECY.equals(propName))
+ return getNegotiatedPolicyForwardSecrecy();
+ if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName))
+ return getNegotiatedPolicyPassCredentials();
+ if (Sasl.REUSE.equals(propName))
+ return getReuse();
+ return null;
+ }
+
+ public void dispose() throws SaslException
+ {
+ }
+
+ public String getAuthorizationID()
+ {
+ return authorizationID;
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+
+ protected String getNegotiatedStrength()
+ {
+ return Registry.STRENGTH_LOW;
+ }
+
+ protected String getNegotiatedServerAuth()
+ {
+ return Registry.SERVER_AUTH_FALSE;
+ }
+
+ protected String getNegotiatedMaxBuffer()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedRawSendSize()
+ {
+ return String.valueOf(Registry.SASL_BUFFER_MAX_LIMIT);
+ }
+
+ protected String getNegotiatedPolicyNoPlainText()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoActive()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoDictionary()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoAnonymous()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyForwardSecrecy()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyPassCredentials()
+ {
+ return null;
+ }
+
+ protected String getReuse()
+ {
+ return Registry.REUSE_FALSE;
+ }
+
+ protected byte[] engineUnwrap(final byte[] incoming, final int offset,
+ final int len) throws SaslException
+ {
+ final byte[] result = new byte[len];
+ System.arraycopy(incoming, offset, result, 0, len);
+ return result;
+ }
+
+ protected byte[] engineWrap(final byte[] outgoing, final int offset,
+ final int len) throws SaslException
+ {
+ final byte[] result = new byte[len];
+ System.arraycopy(outgoing, offset, result, 0, len);
+ return result;
+ }
+
+ /**
+ * Initialises the mechanism with designated attributes. Permissible names and
+ * values are mechanism specific.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @throws IllegalMechanismStateException if the instance is already
+ * initialised.
+ * @throws SaslException if an exception occurs during the process.
+ */
+ public void init(final Map attributes) throws SaslException
+ {
+ if (state != -1)
+ throw new IllegalMechanismStateException("init()");
+ if (properties == null)
+ properties = new HashMap();
+ else
+ properties.clear();
+ if (attributes != null)
+ {
+ authorizationID = (String) attributes.get(Registry.SASL_AUTHORISATION_ID);
+ protocol = (String) attributes.get(Registry.SASL_PROTOCOL);
+ serverName = (String) attributes.get(Registry.SASL_SERVER_NAME);
+ handler = (CallbackHandler) attributes.get(Registry.SASL_CALLBACK_HANDLER);
+ channelBinding = (byte[]) attributes.get(Registry.SASL_CHANNEL_BINDING);
+ properties.putAll(attributes);
+ }
+ else
+ handler = null;
+
+ if (authorizationID == null)
+ authorizationID = "";
+ if (protocol == null)
+ protocol = "";
+ if (serverName == null)
+ serverName = "";
+ if (channelBinding == null)
+ channelBinding = new byte[0];
+ initMechanism();
+ complete = false;
+ state = 0;
+ }
+
+ /**
+ * Resets the mechanism instance for re-initialisation and use with other
+ * characteristics.
+ *
+ * @throws SaslException if an exception occurs during the process.
+ */
+ public void reset() throws SaslException
+ {
+ resetMechanism();
+ properties.clear();
+ authorizationID = protocol = serverName = null;
+ channelBinding = null;
+ complete = false;
+ state = -1;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,82 @@
+/* ConfidentialityException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * Used by mechanisms that offer a security services layer, this checked
+ * exception is thrown to indicate that a violation has occured during the
+ * processing of a <i>confidentiality</i> protection filter.
+ */
+public class ConfidentialityException
+ extends SaslException
+{
+ /**
+ * Constructs a new instance of <code>ConfidentialityException</code> with
+ * no detail message.
+ */
+ public ConfidentialityException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a new instance of <code>ConfidentialityException</code> with
+ * the specified detail message.
+ *
+ * @param s the detail message.
+ */
+ public ConfidentialityException(String s)
+ {
+ super(s);
+ }
+
+ /**
+ * Constructs a new instance of <code>ConfidentialityException</code> with a
+ * detailed message and a root exception.
+ *
+ * @param s possibly null additional detail about the exception.
+ * @param x a possibly null root exception that caused this one.
+ */
+ public ConfidentialityException(String s, Throwable x)
+ {
+ super(s, x);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,116 @@
+/* IAuthInfoProvider.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import java.util.Map;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * The visible methods of any authentication information provider.
+ */
+public interface IAuthInfoProvider
+{
+ /**
+ * Activates (initialises) this provider instance. SHOULD be the first method
+ * invoked on the provider.
+ *
+ * @param context a collection of name-value bindings describing the
+ * activation context.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ void activate(Map context) throws AuthenticationException;
+
+ /**
+ * Passivates (releases) this provider instance. SHOULD be the last method
+ * invoked on the provider. Once it is done, no other method may be invoked on
+ * the same instance before it is <i>activated</i> agains.
+ *
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ void passivate() throws AuthenticationException;
+
+ /**
+ * Checks if a user with a designated name is known to this provider.
+ *
+ * @param userName the name of a user to check.
+ * @return <code>true</code> if the user with the designated name is known
+ * to this provider; <code>false</code> otherwise.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ boolean contains(String userName) throws AuthenticationException;
+
+ /**
+ * Returns a collection of information about a designated user. The contents
+ * of the returned map is provider-specific of name-to-value mappings.
+ *
+ * @param userID a map of name-to-value bindings that fully describe a user.
+ * @return a collection of information about the designated user.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ Map lookup(Map userID) throws AuthenticationException;
+
+ /**
+ * Updates the credentials of a designated user.
+ *
+ * @param userCredentials a map of name-to-value bindings that fully describe
+ * a user, including per new credentials.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ void update(Map userCredentials) throws AuthenticationException;
+
+ /**
+ * A provider may operate in more than mode; e.g. SRP-II caters for user
+ * credentials computed in more than one message digest algorithm. This method
+ * returns the set of name-to-value bindings describing the mode of the
+ * provider.
+ *
+ * @param mode a unique identifier describing the operational mode.
+ * @return a collection of name-to-value bindings describing the designated
+ * mode.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
+ */
+ Map getConfiguration(String mode) throws AuthenticationException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,55 @@
+/* IAuthInfoProviderFactory.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+/**
+ * The visible method of every authentication information provider factory.
+ */
+public interface IAuthInfoProviderFactory
+{
+ /**
+ * Returns an implementation of a provider for a designated mechanism capable
+ * of honouring {@link IAuthInfoProvider} requests.
+ *
+ * @param mechanism the unique name of a mechanism.
+ * @return an implementation of {@link IAuthInfoProvider} for that mechanism
+ * or <code>null</code> if none found.
+ */
+ IAuthInfoProvider getInstance(String mechanism);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,84 @@
+/* IllegalMechanismStateException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * A checked exception thrown to indicate that an operation that should be
+ * invoked on a completed mechanism was invoked but the authentication phase of
+ * that mechanism was not completed yet, or that an operation that should be
+ * invoked on incomplete mechanisms was invoked but the authentication phase of
+ * that mechanism was already completed.
+ */
+public class IllegalMechanismStateException
+ extends AuthenticationException
+{
+ /**
+ * Constructs a new instance of <code>IllegalMechanismStateException</code>
+ * with no detail message.
+ */
+ public IllegalMechanismStateException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a new instance of <code>IllegalMechanismStateException</code>
+ * with the specified detail message.
+ *
+ * @param detail the detail message.
+ */
+ public IllegalMechanismStateException(String detail)
+ {
+ super(detail);
+ }
+
+ /**
+ * Constructs a new instance of <code>IllegalMechanismStateException</code>
+ * with the specified detail message, and cause.
+ *
+ * @param detail the detail message.
+ * @param ex the original cause.
+ */
+ public IllegalMechanismStateException(String detail, Throwable ex)
+ {
+ super(detail, ex);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,272 @@
+/* InputBuffer.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+
+/**
+ * The implementation of an incoming SASL buffer.
+ * <p>
+ * The data elements this class caters for are described in [1].
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt">
+ * Secure Remote Password Authentication Mechanism</a>;<br/>
+ * draft-burdis-cat-srp-sasl-09,<br/> <a
+ * href="mailto:keith at rucus.ru.ac.za">Keith Burdis</a> and <a
+ * href="mailto:raif at forge.com.au">Raïf S. Naffah</a>.</li>
+ * </ol>
+ */
+public class InputBuffer
+{
+ /** The internal buffer stream containing the buffer's contents. */
+ protected ByteArrayInputStream in;
+ /** The length of the buffer, according to its header. */
+ protected int length;
+
+ /**
+ * Constructs a SASL buffer given the buffer's encoded form, including its
+ * header bytes.
+ *
+ * @param frame the encoded form, including the header bytes, of a SASL
+ * buffer.
+ * @throws SaslEncodingException if the buffer is malformed.
+ */
+ public InputBuffer(byte[] frame) throws SaslEncodingException
+ {
+ this();
+
+ if (frame.length < 4)
+ throw new SaslEncodingException("SASL buffer header too short");
+ length = (frame[0] & 0xFF) << 24
+ | (frame[1] & 0xFF) << 16
+ | (frame[2] & 0xFF) << 8
+ | (frame[3] & 0xFF);
+ if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0)
+ throw new SaslEncodingException("SASL buffer size limit exceeded");
+ in = new ByteArrayInputStream(frame, 4, length);
+ }
+
+ /** Trivial private constructor for use by the class method. */
+ private InputBuffer()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a SASL buffer given the buffer's encoded contents,
+ * excluding the buffer's header bytes.
+ * <p>
+ * Calls the method with the same name and three arguments as:
+ * <code>getInstance(raw, 0, raw.length)</code>.
+ *
+ * @param raw the encoded form, excluding the header bytes, of a SASL buffer.
+ * @return a new instance of {@link InputBuffer}.
+ */
+ public static InputBuffer getInstance(byte[] raw)
+ {
+ return getInstance(raw, 0, raw.length);
+ }
+
+ /**
+ * Returns an instance of a SASL buffer given the buffer's encoded contents,
+ * excluding the buffer's header bytes.
+ *
+ * @param raw the encoded form, excluding the header bytes, of a SASL buffer.
+ * @param offset offset where to start using raw bytes from.
+ * @param len number of bytes to use.
+ * @return a new instance of {@link InputBuffer}.
+ */
+ public static InputBuffer getInstance(byte[] raw, int offset, int len)
+ {
+ InputBuffer result = new InputBuffer();
+ result.in = new ByteArrayInputStream(raw, offset, len);
+ return result;
+ }
+
+ /**
+ * Converts two octets into the number that they represent.
+ *
+ * @param b the two octets.
+ * @return the length.
+ */
+ public static int twoBytesToLength(byte[] b) throws SaslEncodingException
+ {
+ final int result = (b[0] & 0xFF) << 8 | (b[1] & 0xFF);
+ if (result > Registry.SASL_TWO_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL MPI/Text size limit exceeded");
+ return result;
+ }
+
+ public boolean hasMoreElements()
+ {
+ return (in.available() > 0);
+ }
+
+ /**
+ * Decodes a SASL scalar quantity, <code>count</code>-octet long, from the
+ * current buffer.
+ *
+ * @param count the number of octets of this scalar quantity.
+ * @return a native representation of a SASL scalar (unsigned integer)
+ * quantity.
+ * @throws SaslEncodingException if an encoding exception occurs during the
+ * operation.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public long getScalar(int count) throws IOException
+ {
+ if (count < 0 || count > 4)
+ throw new SaslEncodingException("Invalid SASL scalar octet count: "
+ + String.valueOf(count));
+ if (! hasMoreElements())
+ throw new SaslEncodingException("Not enough bytes for a scalar in buffer");
+ if (in.available() < count)
+ throw new SaslEncodingException("Illegal SASL scalar encoding");
+ byte[] element = new byte[count];
+ in.read(element);
+ long result = 0L;
+ for (int i = 0; i < count; i++)
+ {
+ result <<= 8;
+ result |= element[i] & 0xFFL;
+ }
+ return result;
+ }
+
+ /**
+ * Decodes a SASL OS from the current buffer.
+ *
+ * @return a native representation of a SASL OS.
+ * @throws SaslEncodingException if an encoding exception occurs during the
+ * operation.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public byte[] getOS() throws IOException
+ {
+ if (! hasMoreElements())
+ throw new SaslEncodingException(
+ "Not enough bytes for an octet-sequence in buffer");
+ final int elementLength = in.read();
+ if (elementLength > Registry.SASL_ONE_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL octet-sequence size limit exceeded");
+ if (in.available() < elementLength)
+ throw new SaslEncodingException("Illegal SASL octet-sequence encoding");
+ byte[] result = new byte[elementLength];
+ in.read(result);
+ return result;
+ }
+
+ /**
+ * Decodes a SASL EOS from the current buffer.
+ *
+ * @return a native representation of a SASL EOS.
+ * @throws SaslEncodingException if an encoding exception occurs during the
+ * operation.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public byte[] getEOS() throws IOException
+ {
+ if (in.available() < 2)
+ throw new SaslEncodingException(
+ "Not enough bytes for an extended octet-sequence in buffer");
+ byte[] elementLengthBytes = new byte[2];
+ in.read(elementLengthBytes);
+ final int elementLength = twoBytesToLength(elementLengthBytes);
+ if (in.available() < elementLength)
+ throw new SaslEncodingException(
+ "Illegal SASL extended octet-sequence encoding");
+ byte[] result = new byte[elementLength];
+ in.read(result);
+ return result;
+ }
+
+ /**
+ * Decodes a SASL MPI from the current buffer.
+ *
+ * @return a native representation of a SASL MPI.
+ * @throws SaslEncodingException if an encoding exception occurs during the
+ * operation.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public BigInteger getMPI() throws IOException
+ {
+ if (in.available() < 2)
+ throw new SaslEncodingException("Not enough bytes for an MPI in buffer");
+ byte[] elementLengthBytes = new byte[2];
+ in.read(elementLengthBytes);
+ final int elementLength = twoBytesToLength(elementLengthBytes);
+ if (in.available() < elementLength)
+ throw new SaslEncodingException(
+ "Illegal SASL multi-precision integer encoding");
+ byte[] element = new byte[elementLength];
+ in.read(element);
+ return new BigInteger(1, element);
+ }
+
+ /**
+ * Decodes a SASL Text from the current buffer.
+ *
+ * @return a native representation of a SASL Text.
+ * @throws SaslEncodingException if an encoding exception occurs during the
+ * operation.
+ * @throws SaslEncodingException if the UTF-8 character encoding is not
+ * supported on this platform.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public String getText() throws IOException
+ {
+ if (in.available() < 2)
+ throw new SaslEncodingException("Not enough bytes for a text in buffer");
+ byte[] elementLengthBytes = new byte[2];
+ in.read(elementLengthBytes);
+ final int elementLength = twoBytesToLength(elementLengthBytes);
+ if (in.available() < elementLength)
+ throw new SaslEncodingException("Illegal SASL text encoding");
+ byte[] element = new byte[elementLength];
+ in.read(element);
+ return new String(element, "UTF8");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* IntegrityException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * Used by mechanisms that offer a security services layer, this checked
+ * exception is thrown to indicate that a violation has occured during the
+ * processing of an <i>integrity</i> protection filter, including <i>replay
+ * detection</i>.
+ */
+public class IntegrityException
+ extends SaslException
+{
+ /**
+ * Constructs a new instance of <code>IntegrityException</code> with no
+ * detail message.
+ */
+ public IntegrityException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a new instance of <code>IntegrityException</code> with the
+ * specified detail message.
+ *
+ * @param s the detail message.
+ */
+ public IntegrityException(String s)
+ {
+ super(s);
+ }
+
+ /**
+ * Constructs a new instance of <code>IntegrityException</code> with a
+ * detailed message and a root exception.
+ *
+ * @param s possibly null additional detail about the exception.
+ * @param x a possibly null root exception that caused this one.
+ */
+ public IntegrityException(String s, Throwable x)
+ {
+ super(s, x);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,62 @@
+/* NoSuchMechanismException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A checked exception thrown to indicate that a designated SASL mechanism
+ * implementation was not found.
+ */
+public class NoSuchMechanismException
+ extends SaslException
+{
+ /**
+ * Constructs a <code>NoSuchMechanismException</code> with the specified
+ * detail message. In the case of this exception, the detail message
+ * designates the offending mechanism name.
+ *
+ * @param arg the detail message, which in this case is the offending
+ * mechanism name.
+ */
+ public NoSuchMechanismException(String arg)
+ {
+ super(arg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,67 @@
+/* NoSuchUserException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * A checked exception thrown to indicate that a designated user is unknown to
+ * the authentication layer.
+ */
+public class NoSuchUserException
+ extends AuthenticationException
+{
+ /** Constructs a <code>NoSuchUserException</code> with no detail message. */
+ public NoSuchUserException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a <code>NoSuchUserException</code> with the specified detail
+ * message. In the case of this exception, the detail message designates the
+ * offending username.
+ *
+ * @param arg the detail message, which in this case is the username.
+ */
+ public NoSuchUserException(String arg)
+ {
+ super(arg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,198 @@
+/* OutputBuffer.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+
+/**
+ * The implementation of an outgoing SASL buffer.
+ * <p>
+ * The data elements this class caters for are described in [1].
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt">
+ * Secure Remote Password Authentication Mechanism</a>;<br/>
+ * draft-burdis-cat-srp-sasl-09,<br/> <a
+ * href="mailto:keith at rucus.ru.ac.za">Keith Burdis</a> and <a
+ * href="mailto:raif at forge.com.au">Raïf S. Naffah</a>.</li>
+ * </ol>
+ */
+public class OutputBuffer
+{
+ /** The internal output stream. */
+ private ByteArrayOutputStream out;
+
+ public OutputBuffer()
+ {
+ super();
+
+ out = new ByteArrayOutputStream();
+ }
+
+ /**
+ * Encodes a SASL scalar quantity, <code>count</code>-octet long, to the
+ * current buffer.
+ *
+ * @param count number of octets to encode <code>b</code> with.
+ * @param b the scalar quantity.
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public void setScalar(int count, int b) throws IOException
+ {
+ if (count < 0 || count > 4)
+ throw new SaslEncodingException("Invalid SASL scalar octet count: "
+ + String.valueOf(count));
+ byte[] element = new byte[count];
+ for (int i = count; --i >= 0; b >>>= 8)
+ element[i] = (byte) b;
+ out.write(element);
+ }
+
+ /**
+ * Encodes a SASL OS to the current buffer.
+ *
+ * @param b the OS element.
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public void setOS(byte[] b) throws IOException
+ {
+ final int length = b.length;
+ if (length > Registry.SASL_ONE_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL octet-sequence too long");
+ out.write(length & 0xFF);
+ out.write(b);
+ }
+
+ /**
+ * Encodes a SASL EOS to the current buffer.
+ *
+ * @param b the EOS element.
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public void setEOS(byte[] b) throws IOException
+ {
+ final int length = b.length;
+ if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL extended octet-sequence too long");
+ byte[] lengthBytes = { (byte)(length >>> 8), (byte) length };
+ out.write(lengthBytes);
+ out.write(b);
+ }
+
+ /**
+ * Encodes a SASL MPI to the current buffer.
+ *
+ * @param val the MPI element.
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public void setMPI(BigInteger val) throws IOException
+ {
+ byte[] b = Util.trim(val);
+ final int length = b.length;
+ if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL multi-precision integer too long");
+ byte[] lengthBytes = { (byte)(length >>> 8), (byte) length };
+ out.write(lengthBytes);
+ out.write(b);
+ }
+
+ /**
+ * Encodes a SASL Text to the current buffer.
+ *
+ * @param str the Text element.
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ * @throws SaslEncodingException if the UTF-8 encoding is not supported on
+ * this platform.
+ * @throws IOException if any other I/O exception occurs during the operation.
+ */
+ public void setText(String str) throws IOException
+ {
+ byte[] b = str.getBytes("UTF8");
+ final int length = b.length;
+ if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT)
+ throw new SaslEncodingException("SASL text too long");
+ byte[] lengthBytes = { (byte)(length >>> 8), (byte) length };
+ out.write(lengthBytes);
+ out.write(b);
+ }
+
+ /**
+ * Returns the encoded form of the current buffer including the 4-byte length
+ * header.
+ *
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ */
+ public byte[] encode() throws SaslEncodingException
+ {
+ byte[] buffer = wrap();
+ final int length = buffer.length;
+ byte[] result = new byte[length + 4];
+ result[0] = (byte)(length >>> 24);
+ result[1] = (byte)(length >>> 16);
+ result[2] = (byte)(length >>> 8);
+ result[3] = (byte) length;
+ System.arraycopy(buffer, 0, result, 4, length);
+ return result;
+ }
+
+ /**
+ * Returns the encoded form of the current buffer excluding the 4-byte length
+ * header.
+ *
+ * @throws SaslEncodingException if an encoding size constraint is violated.
+ */
+ public byte[] wrap() throws SaslEncodingException
+ {
+ final int length = out.size();
+ if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0)
+ throw new SaslEncodingException("SASL buffer too long");
+ return out.toByteArray();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,66 @@
+/* SaslEncodingException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A checked exception, thrown when an exception occurs while decoding a SASL
+ * buffer and/or a SASL data element from/to a buffer.
+ */
+public class SaslEncodingException
+ extends SaslException
+{
+ /** Constructs a <code>SaslEncodingException</code> with no detail message. */
+ public SaslEncodingException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a <code>SaslEncodingException</code> with the specified detail
+ * message.
+ *
+ * @param s the detail message.
+ */
+ public SaslEncodingException(String s)
+ {
+ super(s);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,393 @@
+/* SaslInputStream.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.util.Util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.util.logging.Logger;
+
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslServer;
+
+/**
+ * An input stream that uses either a {@link SaslClient} or a {@link SaslServer}
+ * to process the data through these entities' security layer filter(s).
+ */
+public class SaslInputStream
+ extends InputStream
+{
+ private static final Logger log = Logger.getLogger(SaslInputStream.class.getName());
+ private SaslClient client;
+ private SaslServer server;
+ private int maxRawSendSize;
+ private InputStream source;
+ private byte[] internalBuf;
+
+ public SaslInputStream(SaslClient client, InputStream source)
+ throws IOException
+ {
+ super();
+
+ this.client = client;
+ String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
+ server = null;
+ this.source = source;
+ }
+
+ public SaslInputStream(SaslServer server, InputStream source)
+ throws IOException
+ {
+ super();
+
+ this.server = server;
+ String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
+ client = null;
+ this.source = source;
+ }
+
+ public int available() throws IOException
+ {
+ return (internalBuf == null) ? 0 : internalBuf.length;
+ }
+
+ public void close() throws IOException
+ {
+ source.close();
+ }
+
+ /**
+ * Reads the next byte of data from the input stream. The value byte is
+ * returned as an <code>int</code> in the range <code>0</code> to
+ * <code>255</code>. If no byte is available because the end of the stream
+ * has been reached, the value <code>-1</code> is returned. This method
+ * blocks until input data is available, the end of the stream is detected, or
+ * an exception is thrown.
+ * <p>
+ * From a SASL mechanism provider's perspective, if a security layer has been
+ * negotiated, the underlying <i>source</i> is expected to contain SASL
+ * buffers, as defined in RFC 2222. Four octets in network byte order in the
+ * front of each buffer identify the length of the buffer. The provider is
+ * responsible for performing any integrity checking or other processing on
+ * the buffer before returning the data as a stream of octets. For example,
+ * the protocol driver's request for a single octet from the stream might;
+ * i.e. an invocation of this method, may result in an entire SASL buffer
+ * being read and processed before that single octet can be returned.
+ *
+ * @return the next byte of data, or <code>-1</code> if the end of the
+ * stream is reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ public int read() throws IOException
+ {
+ int result = -1;
+ if (internalBuf != null && internalBuf.length > 0)
+ {
+ result = internalBuf[0] & 0xFF;
+ if (internalBuf.length == 1)
+ internalBuf = new byte[0];
+ else
+ {
+ byte[] tmp = new byte[internalBuf.length - 1];
+ System.arraycopy(internalBuf, 1, tmp, 0, tmp.length);
+ internalBuf = tmp;
+ }
+ }
+ else
+ {
+ byte[] buf = new byte[1];
+ int check = read(buf);
+ result = (check > 0) ? (buf[0] & 0xFF) : -1;
+ }
+ return result;
+ }
+
+ /**
+ * Reads up to <code>len</code> bytes of data from the underlying <i>source</i>
+ * input stream into an array of bytes. An attempt is made to read as many as
+ * <code>len</code> bytes, but a smaller number may be read, possibly zero.
+ * The number of bytes actually read is returned as an integer.
+ * <p>
+ * This method blocks until input data is available, end of file is detected,
+ * or an exception is thrown.
+ * <p>
+ * If <code>b</code> is <code>null</code>, a {@link NullPointerException}
+ * is thrown.
+ * <p>
+ * If <code>off</code> is negative, or <code>len</code> is negative, or
+ * <code>off+len</code> is greater than the length of the array
+ * <code>b</code>, then an {@link IndexOutOfBoundsException} is thrown.
+ * <p>
+ * If <code>len</code> is zero, then no bytes are read and <code>0</code>
+ * is returned; otherwise, there is an attempt to read at least one byte. If
+ * no byte is available because the stream is at end of file, the value
+ * <code>-1</code> is returned; otherwise, at least one byte is read and
+ * stored into <code>b</code>.
+ * <p>
+ * The first byte read is stored into element <code>b[off]</code>, the next
+ * one into <code>b[off+1]</code>, and so on. The number of bytes read is,
+ * at most, equal to <code>len</code>. Let <code>k</code> be the number
+ * of bytes actually read; these bytes will be stored in elements
+ * <code>b[off]</code> through <code>b[off+k-1]</code>, leaving elements
+ * <code>b[off+k]</code> through <code>b[off+len-1]</code> unaffected.
+ * <p>
+ * In every case, elements <code>b[0]</code> through <code>b[off]</code>
+ * and elements <code>b[off+len]</code> through <code>b[b.length-1]</code>
+ * are unaffected.
+ * <p>
+ * If the first byte cannot be read for any reason other than end of file,
+ * then an {@link IOException} is thrown. In particular, an
+ * {@link IOException} is thrown if the input stream has been closed.
+ * <p>
+ * From the SASL mechanism provider's perspective, if a security layer has
+ * been negotiated, the underlying <i>source</i> is expected to contain SASL
+ * buffers, as defined in RFC 2222. Four octets in network byte order in the
+ * front of each buffer identify the length of the buffer. The provider is
+ * responsible for performing any integrity checking or other processing on
+ * the buffer before returning the data as a stream of octets. The protocol
+ * driver's request for a single octet from the stream might result in an
+ * entire SASL buffer being read and processed before that single octet can be
+ * returned.
+ *
+ * @param b the buffer into which the data is read.
+ * @param off the start offset in array <code>b</code> at which the data is
+ * wricodeen.
+ * @param len the maximum number of bytes to read.
+ * @return the total number of bytes read into the buffer, or <code>-1</code>
+ * if there is no more data because the end of the stream has been
+ * reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ public int read(byte[] b, int off, int len) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "read", new Object[] {
+ b, Integer.valueOf(off), Integer.valueOf(len)
+ });
+ if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
+ || ((off + len) < 0))
+ throw new IndexOutOfBoundsException("off=" + off + ", len=" + len
+ + ", b.length=" + b.length);
+ if (len == 0)
+ {
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "read", Integer.valueOf(0));
+ return 0;
+ }
+ if (Configuration.DEBUG)
+ log.finer("Available: " + available());
+ int result = 0;
+ if (internalBuf == null || internalBuf.length < 1)
+ try
+ {
+ internalBuf = readSaslBuffer();
+ if (internalBuf == null)
+ {
+ if (Configuration.DEBUG)
+ {
+ log.finer("Underlying stream empty. Returning -1");
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
+ return -1;
+ }
+ }
+ catch (InterruptedIOException x)
+ {
+ if (Configuration.DEBUG)
+ {
+ log.finer("Reading thread was interrupted. Returning -1");
+ log.throwing(this.getClass().getName(), "read", x);
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
+ return -1;
+ }
+ if (len <= internalBuf.length)
+ {
+ result = len;
+ System.arraycopy(internalBuf, 0, b, off, len);
+ if (len == internalBuf.length)
+ internalBuf = null;
+ else
+ {
+ byte[] tmp = new byte[internalBuf.length - len];
+ System.arraycopy(internalBuf, len, tmp, 0, tmp.length);
+ internalBuf = tmp;
+ }
+ }
+ else
+ {
+ // first copy the available bytes to b
+ result = internalBuf.length;
+ System.arraycopy(internalBuf, 0, b, off, result);
+ internalBuf = null;
+ off += result;
+ len -= result;
+ int remaining; // count of bytes remaining in buffer after an iteration
+ int delta; // count of bytes moved to b after an iteration
+ int datalen;
+ byte[] data;
+ while (len > 0)
+ // we need to read SASL buffers, as long as there are at least
+ // 4 bytes available at the source
+ if (source.available() > 3)
+ {
+ // process a buffer
+ data = readSaslBuffer();
+ if (data == null)
+ {
+ if (Configuration.DEBUG)
+ log.finer("Underlying stream exhausted. Breaking...");
+ break;
+ }
+ datalen = data.length;
+ // copy [part of] the result to b
+ remaining = (datalen <= len) ? 0 : datalen - len;
+ delta = datalen - remaining;
+ System.arraycopy(data, 0, b, off, delta);
+ if (remaining > 0)
+ {
+ internalBuf = new byte[remaining];
+ System.arraycopy(data, delta, internalBuf, 0, remaining);
+ }
+ // update off, result and len
+ off += delta;
+ result += delta;
+ len -= delta;
+ }
+ else
+ { // nothing much we can do except return what we have
+ if (Configuration.DEBUG)
+ log.finer("Not enough bytes in source to read a buffer. Breaking...");
+ break;
+ }
+ }
+ if (Configuration.DEBUG)
+ {
+ log.finer("Remaining: "
+ + (internalBuf == null ? 0 : internalBuf.length));
+ log.exiting(this.getClass().getName(), "read()", String.valueOf(result));
+ }
+ return result;
+ }
+
+ /**
+ * Reads a SASL buffer from the underlying source if at least 4 bytes are
+ * available.
+ *
+ * @return the byte[] of decoded buffer contents, or null if the underlying
+ * source was exhausted.
+ * @throws IOException if an I/O exception occurs during the operation.
+ */
+ private byte[] readSaslBuffer() throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "readSaslBuffer()");
+ int realLength; // check if we read as many bytes as we're supposed to
+ byte[] result = new byte[4];
+ try
+ {
+ realLength = source.read(result);
+ if (realLength == -1)
+ {
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
+ return null;
+ }
+ }
+ catch (IOException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
+ throw x;
+ }
+ if (realLength != 4)
+ throw new IOException("Was expecting 4 but found " + realLength);
+ int bufferLength = result[0] << 24
+ | (result[1] & 0xFF) << 16
+ | (result[2] & 0xFF) << 8
+ | (result[3] & 0xFF);
+ if (Configuration.DEBUG)
+ log.finer("SASL buffer size: " + bufferLength);
+ if (bufferLength > maxRawSendSize || bufferLength < 0)
+ throw new SaslEncodingException("SASL buffer (security layer) too long");
+
+ result = new byte[bufferLength];
+ try
+ {
+ realLength = source.read(result);
+ }
+ catch (IOException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
+ throw x;
+ }
+ if (realLength != bufferLength)
+ throw new IOException("Was expecting " + bufferLength + " but found "
+ + realLength);
+ if (Configuration.DEBUG)
+ {
+ log.finer("Incoming buffer (before security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (before security) (str): \""
+ + new String(result) + "\"");
+ }
+ if (client != null)
+ result = client.unwrap(result, 0, realLength);
+ else
+ result = server.unwrap(result, 0, realLength);
+ if (Configuration.DEBUG)
+ {
+ log.finer("Incoming buffer (after security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (after security) (str): \""
+ + new String(result) + "\"");
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,175 @@
+/* SaslOutputStream.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.util.Util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.logging.Logger;
+
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslServer;
+
+/**
+ * An output stream that uses either a {@link SaslClient} or a {@link SaslServer}
+ * to process the data through these entities' security layer filter(s).
+ */
+public class SaslOutputStream
+ extends OutputStream
+{
+ private static final Logger log = Logger.getLogger(SaslOutputStream.class.getName());
+ private SaslClient client;
+ private SaslServer server;
+ private int maxRawSendSize;
+ private OutputStream dest;
+
+ public SaslOutputStream(SaslClient client, OutputStream dest)
+ throws IOException
+ {
+ super();
+
+ this.client = client;
+ String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
+ server = null;
+ this.dest = dest;
+ }
+
+ public SaslOutputStream(SaslServer server, OutputStream dest)
+ throws IOException
+ {
+ super();
+
+ this.server = server;
+ String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
+ client = null;
+ this.dest = dest;
+ }
+
+ public void close() throws IOException
+ {
+ dest.flush();
+ dest.close();
+ }
+
+ public void flush() throws IOException
+ {
+ dest.flush();
+ }
+
+ /**
+ * When writing octets to the resulting stream, if a security layer has been
+ * negotiated, each piece of data written (by a single invocation of
+ * <code>write()</code>) will be encapsulated as a SASL buffer, as defined in
+ * RFC 2222, and then written to the underlying <i>dest</i> output stream.
+ */
+ public void write(int b) throws IOException
+ {
+ write(new byte[] { (byte) b });
+ }
+
+ /**
+ * When writing octets to the resulting stream, if a security layer has been
+ * negotiated, each piece of data written (by a single invocation of
+ * <code>write()</code>) will be encapsulated as a SASL buffer, as defined in
+ * RFC 2222, and then written to the underlying <i>dest</i> output stream.
+ */
+ public void write(byte[] b, int off, int len) throws IOException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "write");
+ if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
+ || ((off + len) < 0))
+ throw new IndexOutOfBoundsException("off=" + off + ", len=" + len
+ + ", b.length=" + b.length);
+ if (len == 0)
+ {
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
+ return;
+ }
+ int chunckSize, length, chunck = 1;
+ byte[] output = null, result;
+ if (Configuration.DEBUG)
+ log.finer("About to wrap " + len + " byte(s)...");
+ while (len > 0)
+ {
+ chunckSize = (len > maxRawSendSize ? maxRawSendSize : len);
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (before security) (hex): "
+ + Util.dumpString(b, off, chunckSize));
+ log.finer("Outgoing buffer (before security) (str): \""
+ + new String(b, off, chunckSize) + "\"");
+ }
+ if (client != null)
+ output = client.wrap(b, off, chunckSize);
+ else
+ output = server.wrap(b, off, chunckSize);
+
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (after security) (hex): "
+ + Util.dumpString(output));
+ log.finer("Outgoing buffer (after security) (str): \""
+ + new String(output) + "\"");
+ }
+ length = output.length;
+ result = new byte[length + 4];
+ result[0] = (byte)(length >>> 24);
+ result[1] = (byte)(length >>> 16);
+ result[2] = (byte)(length >>> 8);
+ result[3] = (byte) length;
+ System.arraycopy(output, 0, result, 4, length);
+ dest.write(result);
+ off += chunckSize;
+ len -= chunckSize;
+ if (Configuration.DEBUG)
+ log.finer("Wrapped chunck #" + chunck);
+ chunck++;
+ }
+ dest.flush();
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,75 @@
+/* SaslUtil.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.util.Util;
+
+import java.security.MessageDigest;
+
+/**
+ * Utility methods for SASL-related classes.
+ */
+public class SaslUtil
+{
+ private SaslUtil()
+ {
+ super();
+ }
+
+ public static final boolean validEmailAddress(String address)
+ {
+ // need to do better than this
+ return (address.indexOf("@") != -1);
+ }
+
+ /** Returns the context of the designated hash as a string. */
+ public static final String dump(MessageDigest md)
+ {
+ String result;
+ try
+ {
+ result = Util.dumpString(((MessageDigest) md.clone()).digest());
+ }
+ catch (Exception ignored)
+ {
+ result = "...";
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,158 @@
+/* ServerFactory.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.anonymous.AnonymousServer;
+import gnu.javax.crypto.sasl.crammd5.CramMD5Server;
+import gnu.javax.crypto.sasl.plain.PlainServer;
+import gnu.javax.crypto.sasl.srp.SRPServer;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+import javax.security.sasl.SaslServerFactory;
+
+/**
+ * The implementation of the {@link SaslServerFactory}.
+ */
+public class ServerFactory
+ implements SaslServerFactory
+{
+ // implicit 0-arguments constructor
+
+ public static final Set getNames()
+ {
+ return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
+ }
+
+ private static final String[] getNamesInternal(Map props)
+ {
+ String[] all = new String[] {
+ Registry.SASL_SRP_MECHANISM,
+ Registry.SASL_CRAM_MD5_MECHANISM,
+ Registry.SASL_PLAIN_MECHANISM,
+ Registry.SASL_ANONYMOUS_MECHANISM };
+ List result = new ArrayList(4);
+ int i;
+ for (i = 0; i < all.length;)
+ result.add(all[i++]);
+ if (props == null)
+ return (String[]) result.toArray(new String[0]); // all
+ if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) // none
+ return new String[0];
+ if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_NODICTIONARY, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_NOANONYMOUS, props))
+ {
+ result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
+ }
+ if (hasPolicy(Sasl.POLICY_FORWARD_SECRECY, props))
+ {
+ result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
+ result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
+ }
+ return (String[]) result.toArray(new String[0]);
+ }
+
+ public static final ServerMechanism getInstance(String mechanism)
+ {
+ if (mechanism == null)
+ return null;
+ mechanism = mechanism.trim().toUpperCase();
+ if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
+ return new SRPServer();
+ if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
+ return new CramMD5Server();
+ if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
+ return new PlainServer();
+ if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
+ return new AnonymousServer();
+ return null;
+ }
+
+ public SaslServer createSaslServer(String mechanism, String protocol,
+ String serverName, Map props,
+ CallbackHandler cbh) throws SaslException
+ {
+ ServerMechanism result = getInstance(mechanism);
+ if (result != null)
+ {
+ HashMap attributes = new HashMap();
+ if (props != null)
+ attributes.putAll(props);
+ attributes.put(Registry.SASL_PROTOCOL, protocol);
+ attributes.put(Registry.SASL_SERVER_NAME, serverName);
+ attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
+ result.init(attributes);
+ }
+ return result;
+ }
+
+ public String[] getMechanismNames(Map props)
+ {
+ return getNamesInternal(props);
+ }
+
+ private static boolean hasPolicy(String propertyName, Map props)
+ {
+ return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,294 @@
+/* ServerMechanism.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import gnu.java.security.Registry;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+/**
+ * A base class to facilitate implementing SASL server-side mechanisms.
+ */
+public abstract class ServerMechanism
+ implements SaslServer
+{
+ /** Name of this mechanism. */
+ protected String mechanism;
+ /** Name of protocol using this mechanism. */
+ protected String protocol;
+ /** Name of server to authenticate to. */
+ protected String serverName;
+ /** Properties of qualities desired for this mechanism. */
+ protected Map properties;
+ /** Callback handler to use with this mechanism instance. */
+ protected CallbackHandler handler;
+ /** Whether authentication phase is completed (true) or not (false). */
+ protected boolean complete = false;
+ /** The authorisation identity. */
+ protected String authorizationID;
+ /** Channel binding data to use with this mechanism instance. */
+ protected byte[] channelBinding;
+ /** The state of the authentication automaton. -1 means uninitialised. */
+ protected int state = -1;
+ /** The provider for authentication information. */
+ protected IAuthInfoProvider authenticator;
+
+ protected ServerMechanism(final String mechanism)
+ {
+ super();
+
+ this.mechanism = mechanism;
+ this.authenticator = AuthInfo.getProvider(mechanism);
+ this.state = -1;
+ }
+
+ protected abstract void initMechanism() throws SaslException;
+
+ protected abstract void resetMechanism() throws SaslException;
+
+ public abstract byte[] evaluateResponse(byte[] response) throws SaslException;
+
+ public boolean isComplete()
+ {
+ return complete;
+ }
+
+ public byte[] unwrap(final byte[] incoming, final int offset, final int len)
+ throws SaslException
+ {
+ if (! isComplete())
+ throw new IllegalMechanismStateException();
+ return this.engineUnwrap(incoming, offset, len);
+ }
+
+ public byte[] wrap(final byte[] outgoing, final int offset, final int len)
+ throws SaslException
+ {
+ if (! isComplete())
+ throw new IllegalMechanismStateException();
+ return this.engineWrap(outgoing, offset, len);
+ }
+
+ public String getMechanismName()
+ {
+ return this.mechanism;
+ }
+
+ public String getAuthorizationID()
+ {
+ return this.authorizationID;
+ }
+
+ public Object getNegotiatedProperty(final String propName)
+ {
+ if (! isComplete())
+ throw new IllegalStateException();
+ if (Sasl.QOP.equals(propName))
+ return getNegotiatedQOP();
+ if (Sasl.STRENGTH.equals(propName))
+ return getNegotiatedStrength();
+ if (Sasl.SERVER_AUTH.equals(propName))
+ return getNegotiatedServerAuth();
+ if (Sasl.MAX_BUFFER.equals(propName))
+ return getNegotiatedMaxBuffer();
+ if (Sasl.RAW_SEND_SIZE.equals(propName))
+ return getNegotiatedRawSendSize();
+ if (Sasl.POLICY_NOPLAINTEXT.equals(propName))
+ return getNegotiatedPolicyNoPlainText();
+ if (Sasl.POLICY_NOACTIVE.equals(propName))
+ return getNegotiatedPolicyNoActive();
+ if (Sasl.POLICY_NODICTIONARY.equals(propName))
+ return getNegotiatedPolicyNoDictionary();
+ if (Sasl.POLICY_NOANONYMOUS.equals(propName))
+ return getNegotiatedPolicyNoAnonymous();
+ if (Sasl.POLICY_FORWARD_SECRECY.equals(propName))
+ return getNegotiatedPolicyForwardSecrecy();
+ if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName))
+ return getNegotiatedPolicyPassCredentials();
+ if (Sasl.REUSE.equals(propName))
+ return getReuse();
+ return null;
+ }
+
+ public void dispose() throws SaslException
+ {
+ reset();
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+
+ protected String getNegotiatedStrength()
+ {
+ return Registry.STRENGTH_LOW;
+ }
+
+ protected String getNegotiatedServerAuth()
+ {
+ return Registry.SERVER_AUTH_FALSE;
+ }
+
+ protected String getNegotiatedMaxBuffer()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoPlainText()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoActive()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoDictionary()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyNoAnonymous()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyForwardSecrecy()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedPolicyPassCredentials()
+ {
+ return null;
+ }
+
+ protected String getNegotiatedRawSendSize()
+ {
+ return String.valueOf(Registry.SASL_BUFFER_MAX_LIMIT);
+ }
+
+ protected String getReuse()
+ {
+ return Registry.REUSE_FALSE;
+ }
+
+ protected byte[] engineUnwrap(final byte[] incoming, final int offset,
+ final int len) throws SaslException
+ {
+ final byte[] result = new byte[len];
+ System.arraycopy(incoming, offset, result, 0, len);
+ return result;
+ }
+
+ protected byte[] engineWrap(final byte[] outgoing, final int offset,
+ final int len) throws SaslException
+ {
+ final byte[] result = new byte[len];
+ System.arraycopy(outgoing, offset, result, 0, len);
+ return result;
+ }
+
+ /**
+ * Initialises the mechanism with designated attributes. Permissible names and
+ * values are mechanism specific.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @throws IllegalMechanismStateException if the instance is already
+ * initialised.
+ * @throws SaslException if an exception occurs during the process.
+ */
+ public void init(final Map attributes) throws SaslException
+ {
+ if (state != -1)
+ throw new IllegalMechanismStateException("init()");
+ if (properties == null)
+ properties = new HashMap();
+ else
+ properties.clear();
+ if (attributes != null)
+ {
+ protocol = (String) attributes.get(Registry.SASL_PROTOCOL);
+ serverName = (String) attributes.get(Registry.SASL_SERVER_NAME);
+ handler = (CallbackHandler) attributes.get(Registry.SASL_CALLBACK_HANDLER);
+ channelBinding = (byte[]) attributes.get(Registry.SASL_CHANNEL_BINDING);
+ properties.putAll(attributes);
+ }
+ else
+ handler = null;
+ if (protocol == null)
+ protocol = "";
+ if (serverName == null)
+ serverName = "";
+ if (authenticator != null)
+ authenticator.activate(properties);
+ if (channelBinding == null)
+ channelBinding = new byte[0];
+ initMechanism();
+ complete = false;
+ state = 0;
+ }
+
+ /**
+ * Resets the mechanism instance for re-initialisation and use with other
+ * characteristics.
+ *
+ * @throws SaslException if an exception occurs during the process.
+ */
+ public void reset() throws SaslException
+ {
+ resetMechanism();
+ properties.clear();
+ if (authenticator != null)
+ authenticator.passivate();
+ protocol = serverName = null;
+ channelBinding = null;
+ complete = false;
+ state = -1;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,70 @@
+/* UserAlreadyExistsException.java --
+ Copyright (C) 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.javax.crypto.sasl;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A checked exception thrown to indicate that a designated user is already
+ * known to the the authentication layer.
+ */
+public class UserAlreadyExistsException
+ extends SaslException
+{
+ /**
+ * Constructs a <code>UserAlreadyExistsException</code> with no detail
+ * message.
+ */
+ public UserAlreadyExistsException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a <code>UserAlreadyExistsException</code> with the specified
+ * detail message. In the case of this exception, the detail message
+ * designates the offending username.
+ *
+ * @param userName the detail message, which in this case is the username.
+ */
+ public UserAlreadyExistsException(String userName)
+ {
+ super(userName);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,102 @@
+/* AnonymousClient.java --
+ Copyright (C) 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.javax.crypto.sasl.anonymous;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.ClientMechanism;
+import gnu.javax.crypto.sasl.IllegalMechanismStateException;
+
+import java.io.UnsupportedEncodingException;
+
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+
+/**
+ * The ANONYMOUS client-side mechanism.
+ */
+public class AnonymousClient
+ extends ClientMechanism
+ implements SaslClient
+{
+ public AnonymousClient()
+ {
+ super(Registry.SASL_ANONYMOUS_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public boolean hasInitialResponse()
+ {
+ return true;
+ }
+
+ public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
+ {
+ if (complete)
+ {
+ throw new IllegalMechanismStateException("evaluateChallenge()");
+ }
+ return response();
+ }
+
+ private byte[] response() throws SaslException
+ {
+ if (! AnonymousUtil.isValidTraceInformation(authorizationID))
+ throw new AuthenticationException(
+ "Authorisation ID is not a valid email address");
+ complete = true;
+ final byte[] result;
+ try
+ {
+ result = authorizationID.getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("response()", x);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,90 @@
+/* AnonymousServer.java --
+ Copyright (C) 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.javax.crypto.sasl.anonymous;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.ServerMechanism;
+
+import java.io.UnsupportedEncodingException;
+
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+/**
+ * The ANONYMOUS server-side mechanism.
+ */
+public class AnonymousServer
+ extends ServerMechanism
+ implements SaslServer
+{
+ public AnonymousServer()
+ {
+ super(Registry.SASL_ANONYMOUS_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public byte[] evaluateResponse(final byte[] response) throws SaslException
+ {
+ if (response == null)
+ return null;
+ try
+ {
+ authorizationID = new String(response, "UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("evaluateResponse()", x);
+ }
+ if (AnonymousUtil.isValidTraceInformation(authorizationID))
+ {
+ this.complete = true;
+ return null;
+ }
+ authorizationID = null;
+ throw new AuthenticationException("Invalid email address");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* AnonymousUtil.java --
+ Copyright (C) 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.javax.crypto.sasl.anonymous;
+
+import gnu.javax.crypto.sasl.SaslUtil;
+
+/**
+ * An ANONYMOUS-specific utility class.
+ */
+public class AnonymousUtil
+{
+ /** Trivial private constructor to enforce Singleton pattern. */
+ private AnonymousUtil()
+ {
+ super();
+ }
+
+ static boolean isValidTraceInformation(String traceInformation)
+ {
+ if (traceInformation == null)
+ return false;
+ if (traceInformation.length() == 0)
+ return true;
+ if (SaslUtil.validEmailAddress(traceInformation))
+ return true;
+ return isValidToken(traceInformation);
+ }
+
+ static boolean isValidToken(String token)
+ {
+ if (token == null)
+ return false;
+ if (token.length() == 0)
+ return false;
+ if (token.length() > 255)
+ return false;
+ if (token.indexOf('@') != -1)
+ return false;
+ for (int i = 0; i < token.length(); i++)
+ {
+ char c = token.charAt(i);
+ if (c < 0x20 || c > 0x7E)
+ return false;
+ }
+ return true;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,166 @@
+/* CramMD5AuthInfoProvider.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.IAuthInfoProvider;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * The CRAM-MD5 mechanism authentication information provider implementation.
+ */
+public class CramMD5AuthInfoProvider
+ implements IAuthInfoProvider
+{
+ private PasswordFile passwordFile = null;
+
+ // implicit 0-args constrcutor
+
+ public void activate(Map context) throws AuthenticationException
+ {
+ try
+ {
+ if (context == null)
+ passwordFile = new PasswordFile();
+ else
+ {
+ String pfn = (String) context.get(CramMD5Registry.PASSWORD_FILE);
+ if (pfn == null)
+ passwordFile = new PasswordFile();
+ else
+ passwordFile = new PasswordFile(pfn);
+ }
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("activate()", x);
+ }
+ }
+
+ public void passivate() throws AuthenticationException
+ {
+ passwordFile = null;
+ }
+
+ public boolean contains(String userName) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("contains()",
+ new IllegalStateException());
+ boolean result = false;
+ try
+ {
+ result = passwordFile.contains(userName);
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("contains()", x);
+ }
+ return result;
+ }
+
+ public Map lookup(Map userID) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("lookup()", new IllegalStateException());
+ Map result = new HashMap();
+ try
+ {
+ String userName = (String) userID.get(Registry.SASL_USERNAME);
+ if (userName == null)
+ throw new NoSuchUserException("");
+ String[] data = passwordFile.lookup(userName);
+ result.put(Registry.SASL_USERNAME, data[0]);
+ result.put(Registry.SASL_PASSWORD, data[1]);
+ result.put(CramMD5Registry.UID_FIELD, data[2]);
+ result.put(CramMD5Registry.GID_FIELD, data[3]);
+ result.put(CramMD5Registry.GECOS_FIELD, data[4]);
+ result.put(CramMD5Registry.DIR_FIELD, data[5]);
+ result.put(CramMD5Registry.SHELL_FIELD, data[6]);
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("lookup()", x);
+ }
+ return result;
+ }
+
+ public void update(Map userCredentials) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("update()", new IllegalStateException());
+ try
+ {
+ String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
+ String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
+ String uid = (String) userCredentials.get(CramMD5Registry.UID_FIELD);
+ String gid = (String) userCredentials.get(CramMD5Registry.GID_FIELD);
+ String gecos = (String) userCredentials.get(CramMD5Registry.GECOS_FIELD);
+ String dir = (String) userCredentials.get(CramMD5Registry.DIR_FIELD);
+ String shell = (String) userCredentials.get(CramMD5Registry.SHELL_FIELD);
+ if (uid == null || gid == null || gecos == null || dir == null
+ || shell == null)
+ passwordFile.changePasswd(userName, password);
+ else
+ {
+ String[] attributes = new String[] { uid, gid, gecos, dir, shell };
+ passwordFile.add(userName, password, attributes);
+ }
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("update()", x);
+ }
+ }
+
+ public Map getConfiguration(String mode) throws AuthenticationException
+ {
+ throw new AuthenticationException("", new UnsupportedOperationException());
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,168 @@
+/* CramMD5Client.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.sasl.ClientMechanism;
+
+import java.io.IOException;
+import java.security.InvalidKeyException;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+
+/**
+ * The CRAM-MD5 SASL client-side mechanism.
+ */
+public class CramMD5Client
+ extends ClientMechanism
+ implements SaslClient
+{
+ public CramMD5Client()
+ {
+ super(Registry.SASL_CRAM_MD5_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public boolean hasInitialResponse()
+ {
+ return false;
+ }
+
+ public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
+ {
+ if (challenge == null)
+ throw new SaslException("null challenge");
+ try
+ {
+ final String username;
+ final char[] password;
+ Callback[] callbacks;
+ if ((! properties.containsKey(Registry.SASL_USERNAME))
+ && (! properties.containsKey(Registry.SASL_PASSWORD)))
+ {
+ callbacks = new Callback[2];
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ callbacks[0] = nameCB;
+ callbacks[1] = pwdCB;
+ this.handler.handle(callbacks);
+ username = nameCB.getName();
+ password = pwdCB.getPassword();
+ }
+ else
+ {
+ if (properties.containsKey(Registry.SASL_USERNAME))
+ username = (String) properties.get(Registry.SASL_USERNAME);
+ else
+ {
+ callbacks = new Callback[1];
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ callbacks[0] = nameCB;
+ this.handler.handle(callbacks);
+ username = nameCB.getName();
+ }
+
+ if (properties.containsKey(Registry.SASL_PASSWORD))
+ password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray();
+ else
+ {
+ callbacks = new Callback[1];
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ callbacks[0] = pwdCB;
+ this.handler.handle(callbacks);
+ password = pwdCB.getPassword();
+ }
+ }
+ if (password == null)
+ throw new SaslException("null password supplied");
+ final byte[] digest;
+ try
+ {
+ digest = CramMD5Util.createHMac(password, challenge);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new AuthenticationException("evaluateChallenge()", x);
+ }
+ final String response = username + " "
+ + Util.toString(digest).toLowerCase();
+ this.complete = true;
+ return response.getBytes("UTF-8");
+ }
+ catch (UnsupportedCallbackException x)
+ {
+ throw new AuthenticationException("evaluateChallenge()", x);
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("evaluateChallenge()", x);
+ }
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,60 @@
+/* CramMD5Registry.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+/**
+ * A list of properties common to CRAM-MD5 classes.
+ */
+public interface CramMD5Registry
+{
+ /** Name of the password file (used by the server) property. */
+ String PASSWORD_FILE = "gnu.crypto.sasl.crammd5.password.file";
+ /** Default password file (used by the server) pathname. */
+ String DEFAULT_PASSWORD_FILE = "/etc/passwd";
+ /** Name of the UID field in the plain password file. */
+ String UID_FIELD = "crammd5.uid";
+ /** Name of the GID field in the plain password file. */
+ String GID_FIELD = "crammd5.gid";
+ /** Name of the GECOS field in the plain password file. */
+ String GECOS_FIELD = "crammd5.gecos";
+ /** Name of the DIR field in the plain password file. */
+ String DIR_FIELD = "crammd5.dir";
+ /** Name of the SHELL field in the plain password file. */
+ String SHELL_FIELD = "crammd5.shell";
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,158 @@
+/* CramMD5Server.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+import gnu.javax.crypto.sasl.ServerMechanism;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+/**
+ * The CRAM-MD5 SASL server-side mechanism.
+ */
+public class CramMD5Server
+ extends ServerMechanism
+ implements SaslServer
+{
+ private byte[] msgID;
+
+ public CramMD5Server()
+ {
+ super(Registry.SASL_CRAM_MD5_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public byte[] evaluateResponse(final byte[] response) throws SaslException
+ {
+ if (state == 0)
+ {
+ msgID = CramMD5Util.createMsgID();
+ state++;
+ return msgID;
+ }
+ final String responseStr = new String(response);
+ final int index = responseStr.lastIndexOf(" ");
+ final String username = responseStr.substring(0, index);
+ final byte[] responseDigest;
+ try
+ {
+ responseDigest = responseStr.substring(index + 1).getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("evaluateResponse()", x);
+ }
+ // Look up the password
+ final char[] password = lookupPassword(username);
+ // Compute the digest
+ byte[] digest;
+ try
+ {
+ digest = CramMD5Util.createHMac(password, msgID);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new AuthenticationException("evaluateResponse()", x);
+ }
+ try
+ {
+ digest = Util.toString(digest).toLowerCase().getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("evaluateResponse()", x);
+ }
+ // Compare the received and computed digests
+ if (! Arrays.equals(digest, responseDigest))
+ throw new AuthenticationException("Digest mismatch");
+ state++;
+ return null;
+ }
+
+ public boolean isComplete()
+ {
+ return (state == 2);
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+
+ private char[] lookupPassword(final String userName) throws SaslException
+ {
+ try
+ {
+ if (! authenticator.contains(userName))
+ throw new NoSuchUserException(userName);
+ final Map userID = new HashMap();
+ userID.put(Registry.SASL_USERNAME, userName);
+ final Map credentials = authenticator.lookup(userID);
+ final String password = (String) credentials.get(Registry.SASL_PASSWORD);
+ if (password == null)
+ throw new AuthenticationException("lookupPassword()",
+ new InternalError());
+ return password.toCharArray();
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("lookupPassword()", x);
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,120 @@
+/* CramMD5Util.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.mac.HMacFactory;
+import gnu.javax.crypto.mac.IMac;
+
+import java.io.UnsupportedEncodingException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A package-private CRAM-MD5-specific utility class.
+ */
+class CramMD5Util
+{
+ private CramMD5Util()
+ {
+ super();
+ }
+
+ static byte[] createMsgID() throws SaslException
+ {
+ final String encoded;
+ try
+ {
+ encoded = Util.toBase64(Thread.currentThread().getName().getBytes("UTF-8"));
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new SaslException("createMsgID()", x);
+ }
+ String hostname = "localhost";
+ try
+ {
+ hostname = InetAddress.getLocalHost().getHostAddress();
+ }
+ catch (UnknownHostException ignored)
+ {
+ }
+ final byte[] result;
+ try
+ {
+ result = new StringBuffer("<")
+ .append(encoded.substring(0,encoded.length()))
+ .append(".").append(String.valueOf(System.currentTimeMillis()))
+ .append("@").append(hostname).append(">")
+ .toString()
+ .getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new SaslException("createMsgID()", x);
+ }
+ return result;
+ }
+
+ static byte[] createHMac(final char[] passwd, final byte[] data)
+ throws InvalidKeyException, SaslException
+ {
+ final IMac mac = HMacFactory.getInstance(Registry.HMAC_NAME_PREFIX
+ + Registry.MD5_HASH);
+ final HashMap map = new HashMap();
+ final byte[] km;
+ try
+ {
+ km = new String(passwd).getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new SaslException("createHMac()", x);
+ }
+ map.put(IMac.MAC_KEY_MATERIAL, km);
+ mac.init(map);
+ mac.update(data, 0, data.length);
+ return mac.digest();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/PasswordFile.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/PasswordFile.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/PasswordFile.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/crammd5/PasswordFile.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,238 @@
+/* PasswordFile.java --
+ Copyright (C) 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.javax.crypto.sasl.crammd5;
+
+import gnu.javax.crypto.sasl.NoSuchUserException;
+import gnu.javax.crypto.sasl.UserAlreadyExistsException;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+/**
+ * The CRAM-MD5 password file representation.
+ */
+public class PasswordFile
+{
+ private static String DEFAULT_FILE;
+ static
+ {
+ DEFAULT_FILE = System.getProperty(CramMD5Registry.PASSWORD_FILE,
+ CramMD5Registry.DEFAULT_PASSWORD_FILE);
+ }
+ private HashMap entries;
+ private File passwdFile;
+ private long lastmod;
+
+ public PasswordFile() throws IOException
+ {
+ this(DEFAULT_FILE);
+ }
+
+ public PasswordFile(final File pwFile) throws IOException
+ {
+ this(pwFile.getAbsolutePath());
+ }
+
+ public PasswordFile(final String fileName) throws IOException
+ {
+ passwdFile = new File(fileName);
+ update();
+ }
+
+ public synchronized void add(final String user, final String passwd,
+ final String[] attributes) throws IOException
+ {
+ checkCurrent(); // check if the entry exists
+ if (entries.containsKey(user))
+ throw new UserAlreadyExistsException(user);
+ if (attributes.length != 5)
+ throw new IllegalArgumentException("Wrong number of attributes");
+ final String[] fields = new String[7]; // create the new entry
+ fields[0] = user;
+ fields[1] = passwd;
+ System.arraycopy(attributes, 0, fields, 2, 5);
+ entries.put(user, fields);
+ savePasswd();
+ }
+
+ public synchronized void changePasswd(final String user, final String passwd)
+ throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ final String[] fields = (String[]) entries.get(user); // get existing entry
+ fields[1] = passwd; // modify the password field
+ entries.remove(user); // delete the existing entry
+ entries.put(user, fields); // add the new entry
+ savePasswd();
+ }
+
+ public synchronized String[] lookup(final String user) throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ return (String[]) entries.get(user);
+ }
+
+ public synchronized boolean contains(final String s) throws IOException
+ {
+ checkCurrent();
+ return entries.containsKey(s);
+ }
+
+ private synchronized void update() throws IOException
+ {
+ lastmod = passwdFile.lastModified();
+ readPasswd(new FileInputStream(passwdFile));
+ }
+
+ private void checkCurrent() throws IOException
+ {
+ if (passwdFile.lastModified() > lastmod)
+ update();
+ }
+
+ private synchronized void readPasswd(final InputStream in) throws IOException
+ {
+ final BufferedReader din = new BufferedReader(new InputStreamReader(in));
+ String line;
+ entries = new HashMap();
+ while ((line = din.readLine()) != null)
+ {
+ final String[] fields = new String[7];
+ final StringTokenizer st = new StringTokenizer(line, ":", true);
+ try
+ {
+ fields[0] = st.nextToken(); // username
+ st.nextToken();
+ fields[1] = st.nextToken(); // passwd
+ if (fields[1].equals(":"))
+ fields[1] = "";
+ else
+ st.nextToken();
+ fields[2] = st.nextToken(); // uid
+ if (fields[2].equals(":"))
+ fields[2] = "";
+ else
+ st.nextToken();
+ fields[3] = st.nextToken(); // gid
+ if (fields[3].equals(":"))
+ fields[3] = "";
+ else
+ st.nextToken();
+ fields[4] = st.nextToken(); // gecos
+ if (fields[4].equals(":"))
+ fields[4] = "";
+ else
+ st.nextToken();
+ fields[5] = st.nextToken(); // dir
+ if (fields[5].equals(":"))
+ fields[5] = "";
+ else
+ st.nextToken();
+ fields[6] = st.nextToken(); // shell
+ if (fields[6].equals(":"))
+ fields[6] = "";
+ }
+ catch (NoSuchElementException x)
+ {
+ continue;
+ }
+ entries.put(fields[0], fields);
+ }
+ }
+
+ private synchronized void savePasswd() throws IOException
+ {
+ if (passwdFile != null)
+ {
+ final FileOutputStream fos = new FileOutputStream(passwdFile);
+ PrintWriter pw = null;
+ try
+ {
+ pw = new PrintWriter(fos);
+ String key;
+ String[] fields;
+ StringBuffer sb;
+ int i;
+ for (Iterator it = entries.keySet().iterator(); it.hasNext();)
+ {
+ key = (String) it.next();
+ fields = (String[]) entries.get(key);
+ sb = new StringBuffer(fields[0]);
+ for (i = 1; i < fields.length; i++)
+ sb.append(":").append(fields[i]);
+ pw.println(sb.toString());
+ }
+ }
+ finally
+ {
+ if (pw != null)
+ try
+ {
+ pw.flush();
+ }
+ finally
+ {
+ pw.close();
+ }
+ try
+ {
+ fos.close();
+ }
+ catch (IOException ignored)
+ {
+ }
+ lastmod = passwdFile.lastModified();
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PasswordFile.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PasswordFile.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PasswordFile.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PasswordFile.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,243 @@
+/* PasswordFile.java --
+ Copyright (C) 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.javax.crypto.sasl.plain;
+
+import gnu.java.security.action.GetPropertyAction;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+import gnu.javax.crypto.sasl.UserAlreadyExistsException;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.security.AccessController;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+/**
+ * A representation of a Plain password file.
+ */
+public class PasswordFile
+{
+ private static String DEFAULT_FILE;
+ static
+ {
+ DEFAULT_FILE = (String) AccessController.doPrivileged
+ (new GetPropertyAction(PlainRegistry.PASSWORD_FILE,
+ PlainRegistry.DEFAULT_PASSWORD_FILE));
+ }
+ private Hashtable entries;
+ private File passwdFile;
+ private long lastmod;
+
+ public PasswordFile() throws IOException
+ {
+ this(DEFAULT_FILE);
+ }
+
+ public PasswordFile(File pwFile) throws IOException
+ {
+ this(pwFile.getAbsolutePath());
+ }
+
+ public PasswordFile(String fileName) throws IOException
+ {
+ passwdFile = new File(fileName);
+ update();
+ }
+
+ public synchronized void add(String user, String passwd, String[] attributes)
+ throws IOException
+ {
+ checkCurrent();
+ if (entries.containsKey(user))
+ throw new UserAlreadyExistsException(user);
+ if (attributes.length != 5)
+ throw new IllegalArgumentException("Wrong number of attributes");
+ // create the new entry
+ String[] fields = new String[7];
+ fields[0] = user;
+ fields[1] = passwd;
+ System.arraycopy(attributes, 0, fields, 2, 5);
+ entries.put(user, fields);
+ savePasswd();
+ }
+
+ public synchronized void changePasswd(String user, String passwd)
+ throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ String[] fields = (String[]) entries.get(user); // get the existing entry
+ fields[1] = passwd; // modify the password field
+ entries.remove(user); // delete the existing entry
+ entries.put(user, fields); // add the new entry
+ savePasswd();
+ }
+
+ public synchronized String[] lookup(String user) throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ return (String[]) entries.get(user);
+ }
+
+ public synchronized boolean contains(String s) throws IOException
+ {
+ checkCurrent();
+ return entries.containsKey(s);
+ }
+
+ private synchronized void update() throws IOException
+ {
+ lastmod = passwdFile.lastModified();
+ readPasswd(new FileInputStream(passwdFile));
+ }
+
+ private void checkCurrent() throws IOException
+ {
+ if (passwdFile.lastModified() > lastmod)
+ update();
+ }
+
+ private synchronized void readPasswd(InputStream in) throws IOException
+ {
+ BufferedReader din = new BufferedReader(new InputStreamReader(in));
+ String line;
+ entries = new Hashtable();
+ String[] fields = new String[7];
+ while ((line = din.readLine()) != null)
+ {
+ StringTokenizer st = new StringTokenizer(line, ":", true);
+ try
+ {
+ fields[0] = st.nextToken(); // username
+ st.nextToken();
+ fields[1] = st.nextToken(); // passwd
+ if (fields[1].equals(":"))
+ fields[1] = "";
+ else
+ st.nextToken();
+ fields[2] = st.nextToken(); // uid
+ if (fields[2].equals(":"))
+ fields[2] = "";
+ else
+ st.nextToken();
+ fields[3] = st.nextToken(); // gid
+ if (fields[3].equals(":"))
+ fields[3] = "";
+ else
+ st.nextToken();
+ fields[4] = st.nextToken(); // gecos
+ if (fields[4].equals(":"))
+ fields[4] = "";
+ else
+ st.nextToken();
+ fields[5] = st.nextToken(); // dir
+ if (fields[5].equals(":"))
+ fields[5] = "";
+ else
+ st.nextToken();
+ fields[6] = st.nextToken(); // shell
+ if (fields[6].equals(":"))
+ fields[6] = "";
+ }
+ catch (NoSuchElementException ignored)
+ {
+ continue;
+ }
+ entries.put(fields[0], fields);
+ }
+ }
+
+ private synchronized void savePasswd() throws IOException
+ {
+ if (passwdFile != null)
+ {
+ FileOutputStream fos = new FileOutputStream(passwdFile);
+ PrintWriter pw = null;
+ try
+ {
+ pw = new PrintWriter(fos);
+ String key;
+ String[] fields;
+ StringBuffer sb;
+ Enumeration keys = entries.keys();
+ while (keys.hasMoreElements())
+ {
+ key = (String) keys.nextElement();
+ fields = (String[]) entries.get(key);
+ sb = new StringBuffer(fields[0]);
+ for (int i = 1; i < fields.length; i++)
+ sb.append(":" + fields[i]);
+ pw.println(sb.toString());
+ }
+ }
+ finally
+ {
+ if (pw != null)
+ try
+ {
+ pw.flush();
+ }
+ finally
+ {
+ pw.close();
+ }
+ if (fos != null)
+ try
+ {
+ fos.close();
+ }
+ catch (IOException ignored)
+ {
+ }
+ lastmod = passwdFile.lastModified();
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,166 @@
+/* PlainAuthInfoProvider.java --
+ Copyright (C) 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.javax.crypto.sasl.plain;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.IAuthInfoProvider;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * The PLAIN mechanism authentication information provider implementation.
+ */
+public class PlainAuthInfoProvider
+ implements IAuthInfoProvider, PlainRegistry
+{
+ private PasswordFile passwordFile = null;
+
+ // implicit 0-args constrcutor
+
+ public void activate(Map context) throws AuthenticationException
+ {
+ try
+ {
+ if (context == null)
+ passwordFile = new PasswordFile();
+ else
+ {
+ String pfn = (String) context.get(PASSWORD_FILE);
+ if (pfn == null)
+ passwordFile = new PasswordFile();
+ else
+ passwordFile = new PasswordFile(pfn);
+ }
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("activate()", x);
+ }
+ }
+
+ public void passivate() throws AuthenticationException
+ {
+ passwordFile = null;
+ }
+
+ public boolean contains(String userName) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("contains()",
+ new IllegalStateException());
+ boolean result = false;
+ try
+ {
+ result = passwordFile.contains(userName);
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("contains()", x);
+ }
+ return result;
+ }
+
+ public Map lookup(Map userID) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("lookup()", new IllegalStateException());
+ Map result = new HashMap();
+ try
+ {
+ String userName = (String) userID.get(Registry.SASL_USERNAME);
+ if (userName == null)
+ throw new NoSuchUserException("");
+ String[] data = passwordFile.lookup(userName);
+ result.put(Registry.SASL_USERNAME, data[0]);
+ result.put(Registry.SASL_PASSWORD, data[1]);
+ result.put(UID_FIELD, data[2]);
+ result.put(GID_FIELD, data[3]);
+ result.put(GECOS_FIELD, data[4]);
+ result.put(DIR_FIELD, data[5]);
+ result.put(SHELL_FIELD, data[6]);
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("lookup()", x);
+ }
+ return result;
+ }
+
+ public void update(Map userCredentials) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("update()", new IllegalStateException());
+ try
+ {
+ String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
+ String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
+ String uid = (String) userCredentials.get(UID_FIELD);
+ String gid = (String) userCredentials.get(GID_FIELD);
+ String gecos = (String) userCredentials.get(GECOS_FIELD);
+ String dir = (String) userCredentials.get(DIR_FIELD);
+ String shell = (String) userCredentials.get(SHELL_FIELD);
+ if (uid == null || gid == null || gecos == null || dir == null
+ || shell == null)
+ passwordFile.changePasswd(userName, password);
+ else
+ {
+ String[] attributes = new String[] { uid, gid, gecos, dir, shell };
+ passwordFile.add(userName, password, attributes);
+ }
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("update()", x);
+ }
+ }
+
+ public Map getConfiguration(String mode) throws AuthenticationException
+ {
+ throw new AuthenticationException("", new UnsupportedOperationException());
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainClient.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainClient.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainClient.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainClient.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,154 @@
+/* PlainClient.java --
+ Copyright (C) 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.javax.crypto.sasl.plain;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.ClientMechanism;
+
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+
+/**
+ * The PLAIN SASL client-side mechanism.
+ */
+public class PlainClient
+ extends ClientMechanism
+ implements SaslClient
+{
+ public PlainClient()
+ {
+ super(Registry.SASL_PLAIN_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public boolean hasInitialResponse()
+ {
+ return true;
+ }
+
+ public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
+ {
+ try
+ {
+ final String username;
+ final char[] password;
+ Callback[] callbacks;
+ if ((! properties.containsKey(Registry.SASL_USERNAME))
+ && (! properties.containsKey(Registry.SASL_PASSWORD)))
+ {
+ callbacks = new Callback[2];
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ callbacks[0] = nameCB;
+ callbacks[1] = pwdCB;
+ this.handler.handle(callbacks);
+ username = nameCB.getName();
+ password = pwdCB.getPassword();
+ }
+ else
+ {
+ if (properties.containsKey(Registry.SASL_USERNAME))
+ username = (String) properties.get(Registry.SASL_USERNAME);
+ else
+ {
+ callbacks = new Callback[1];
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ callbacks[0] = nameCB;
+ this.handler.handle(callbacks);
+ username = nameCB.getName();
+ }
+ if (properties.containsKey(Registry.SASL_PASSWORD))
+ password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray();
+ else
+ {
+ callbacks = new Callback[1];
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ callbacks[0] = pwdCB;
+ this.handler.handle(callbacks);
+ password = pwdCB.getPassword();
+ }
+ }
+ if (password == null)
+ throw new SaslException("null password supplied");
+ final StringBuffer sb = new StringBuffer();
+ if (authorizationID != null)
+ sb.append(authorizationID);
+ sb.append('\0');
+ sb.append(username);
+ sb.append('\0');
+ sb.append(password);
+ this.complete = true;
+ final byte[] response = sb.toString().getBytes("UTF-8");
+ return response;
+ }
+ catch (Exception x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("evaluateChallenge()", x);
+ }
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,57 @@
+/* PlainRegistry.java --
+ Copyright (C) 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.javax.crypto.sasl.plain;
+
+public interface PlainRegistry
+{
+ /** Name of PLAIN password file property. */
+ String PASSWORD_FILE = "gnu.crypto.sasl.plain.password.file";
+ /** Default fully qualified pathname of the PLAIN password file. */
+ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd";
+ /** Name of the UID field in the plain password file. */
+ String UID_FIELD = "plain.uid";
+ /** Name of the GID field in the plain password file. */
+ String GID_FIELD = "plain.gid";
+ /** Name of the GECOS field in the plain password file. */
+ String GECOS_FIELD = "plain.gecos";
+ /** Name of the DIR field in the plain password file. */
+ String DIR_FIELD = "plain.dir";
+ /** Name of the SHELL field in the plain password file. */
+ String SHELL_FIELD = "plain.shell";
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,155 @@
+/* PlainServer.java --
+ Copyright (C) 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.javax.crypto.sasl.plain;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+import gnu.javax.crypto.sasl.ServerMechanism;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+/**
+ * The PLAIN SASL server-side mechanism.
+ */
+public class PlainServer
+ extends ServerMechanism
+ implements SaslServer
+{
+ public PlainServer()
+ {
+ super(Registry.SASL_PLAIN_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ }
+
+ public byte[] evaluateResponse(final byte[] response) throws SaslException
+ {
+ if (response == null)
+ return null;
+ try
+ {
+ final String nullStr = new String("\0");
+ final StringTokenizer strtok = new StringTokenizer(new String(response),
+ nullStr, true);
+ authorizationID = strtok.nextToken();
+ if (! authorizationID.equals(nullStr))
+ strtok.nextToken();
+ else
+ authorizationID = null;
+ final String id = strtok.nextToken();
+ if (id.equals(nullStr))
+ throw new SaslException("No identity given");
+ if (authorizationID == null)
+ authorizationID = id;
+ if ((! authorizationID.equals(nullStr)) && (! authorizationID.equals(id)))
+ throw new SaslException("Delegation not supported");
+ strtok.nextToken();
+ final byte[] pwd;
+ try
+ {
+ pwd = strtok.nextToken().getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new SaslException("evaluateResponse()", x);
+ }
+ if (pwd == null)
+ throw new SaslException("No password given");
+ final byte[] password;
+ try
+ {
+ password = new String(lookupPassword(id)).getBytes("UTF-8");
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new SaslException("evaluateResponse()", x);
+ }
+ if (! Arrays.equals(pwd, password))
+ throw new SaslException("Password incorrect");
+ this.complete = true;
+ return null;
+ }
+ catch (NoSuchElementException x)
+ {
+ throw new SaslException("evaluateResponse()", x);
+ }
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ return Registry.QOP_AUTH;
+ }
+
+ private char[] lookupPassword(final String userName) throws SaslException
+ {
+ try
+ {
+ if (! authenticator.contains(userName))
+ throw new NoSuchUserException(userName);
+ final Map userID = new HashMap();
+ userID.put(Registry.SASL_USERNAME, userName);
+ final Map credentials = authenticator.lookup(userID);
+ final String password = (String) credentials.get(Registry.SASL_PASSWORD);
+ if (password == null)
+ throw new SaslException("lookupPassword()", new InternalError());
+ return password.toCharArray();
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("lookupPassword()", x);
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,221 @@
+/* CALG.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.assembly.Assembly;
+import gnu.javax.crypto.assembly.Cascade;
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.assembly.Stage;
+import gnu.javax.crypto.assembly.Transformer;
+import gnu.javax.crypto.assembly.TransformerException;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.mode.IMode;
+import gnu.javax.crypto.mode.ModeFactory;
+import gnu.javax.crypto.pad.IPad;
+import gnu.javax.crypto.pad.PadFactory;
+import gnu.javax.crypto.sasl.ConfidentialityException;
+
+import java.util.HashMap;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A Factory class that returns CALG (Confidentiality Algorithm) instances that
+ * operate as described in the draft-burdis-cat-sasl-srp-08.
+ * <p>
+ * The designated CALG block cipher should be used in OFB (Output Feedback
+ * Block) mode in the ISO variant, as described in <i>The Handbook of Applied
+ * Cryptography</i>, algorithm 7.20.
+ * <p>
+ * Let <code>k</code> be the block size of the chosen symmetric key block
+ * cipher algorithm; e.g. for AES this is <code>128</code> bits or
+ * <code>16</code> octets. The OFB mode used shall be of length/size
+ * <code>k</code>.
+ * <p>
+ * It is recommended that block ciphers operating in OFB mode be used with an
+ * Initial Vector (the mode's IV). In such a mode of operation - OFB with key
+ * re-use - the IV need not be secret. For the mechanism in question the IVs
+ * shall be a random octet sequence of <code>k</code> bytes.
+ * <p>
+ * The input data to the confidentiality protection algorithm shall be a
+ * multiple of the symmetric cipher block size <code>k</code>. When the input
+ * length is not a multiple of <code>k</code> octets, the data shall be padded
+ * according to the following scheme:
+ * <p>
+ * Assuming the length of the input is <code>l</code> octets,
+ * <code>(k - (l mod k))</code> octets, all having the value
+ * <code>(k - (l mod k))</code>, shall be appended to the original data. In
+ * other words, the input is padded at the trailing end with one of the
+ * following sequences:
+ * <pre>
+ *
+ * 01 -- if l mod k = k-1
+ * 02 02 -- if l mod k = k-2
+ * ...
+ * ...
+ * ...
+ * k k ... k k -- if l mod k = 0
+ * </pre>
+ * <p>
+ * The padding can be removed unambiguously since all input is padded and no
+ * padding sequence is a suffix of another. This padding method is well-defined
+ * if and only if <code>k < 256</code> octets, which is the case with
+ * symmetric key block ciphers today, and in the forseeable future.
+ */
+public final class CALG
+{
+ private Assembly assembly;
+ private Object modeNdx; // initialisation key of the cascade's attributes
+ private int blockSize; // the underlying cipher's blocksize == IV length
+ private int keySize; // the underlying cipher's key size (in bytes).
+
+ /** Private constructor to enforce instantiation through Factory method. */
+ private CALG(final int blockSize, final int keySize, final Object modeNdx,
+ final Assembly assembly)
+ {
+ super();
+
+ this.blockSize = blockSize;
+ this.keySize = keySize;
+ this.modeNdx = modeNdx;
+ this.assembly = assembly;
+ }
+
+ /**
+ * Returns an instance of a SASL-SRP CALG implementation.
+ *
+ * @param algorithm the name of the symmetric cipher algorithm.
+ * @return an instance of this object.
+ */
+ static synchronized CALG getInstance(final String algorithm)
+ {
+ final IBlockCipher cipher = CipherFactory.getInstance(algorithm);
+ final int blockSize = cipher.defaultBlockSize();
+ final int keySize = cipher.defaultKeySize();
+ final Cascade ofbCipher = new Cascade();
+ IMode ofbMode = ModeFactory.getInstance(Registry.OFB_MODE,
+ cipher,
+ blockSize);
+ Stage modeStage = Stage.getInstance(ofbMode, Direction.FORWARD);
+ final Object modeNdx = ofbCipher.append(modeStage);
+ final IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD);
+ final Assembly asm = new Assembly();
+ asm.addPreTransformer(Transformer.getCascadeTransformer(ofbCipher));
+ asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7));
+ return new CALG(blockSize, keySize, modeNdx, asm);
+ }
+
+ /**
+ * Initialises a SASL-SRP CALG implementation.
+ *
+ * @param kdf the key derivation function.
+ * @param iv the initial vector value to use.
+ * @param dir whether this CALG is used for encryption or decryption.
+ */
+ public void init(final KDF kdf, final byte[] iv, final Direction dir)
+ throws SaslException
+ {
+ final byte[] realIV;
+ if (iv.length == blockSize)
+ realIV = iv;
+ else
+ {
+ realIV = new byte[blockSize];
+ if (iv.length > blockSize)
+ System.arraycopy(iv, 0, realIV, 0, blockSize);
+ else // shouldnt happen
+ System.arraycopy(iv, 0, realIV, 0, iv.length);
+ }
+ final HashMap modeAttributes = new HashMap();
+ final byte[] sk = kdf.derive(keySize);
+ modeAttributes.put(IBlockCipher.KEY_MATERIAL, sk);
+ modeAttributes.put(IMode.IV, realIV);
+ final HashMap attributes = new HashMap();
+ attributes.put(Assembly.DIRECTION, dir);
+ attributes.put(modeNdx, modeAttributes);
+ try
+ {
+ assembly.init(attributes);
+ }
+ catch (TransformerException x)
+ {
+ throw new SaslException("getInstance()", x);
+ }
+ }
+
+ /**
+ * Encrypts or decrypts, depending on the mode already set, a designated array
+ * of bytes and returns the result.
+ *
+ * @param data the data to encrypt/decrypt.
+ * @return the decrypted/encrypted result.
+ * @throws ConfidentialityException if an exception occurs duirng the process.
+ */
+ public byte[] doFinal(final byte[] data) throws ConfidentialityException
+ {
+ return doFinal(data, 0, data.length);
+ }
+
+ /**
+ * Encrypts or decrypts, depending on the mode already set, a designated array
+ * of bytes and returns the result.
+ *
+ * @param data the data to encrypt/decrypt.
+ * @param offset where to start in <code>data</code>.
+ * @param length how many bytes to consider in <code>data</code>.
+ * @return the decrypted/encrypted result.
+ * @throws ConfidentialityException if an exception occurs duirng the process.
+ */
+ public byte[] doFinal(final byte[] data, final int offset, final int length)
+ throws ConfidentialityException
+ {
+ final byte[] result;
+ try
+ {
+ result = assembly.lastUpdate(data, offset, length);
+ }
+ catch (TransformerException x)
+ {
+ throw new ConfidentialityException("doFinal()", x);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,155 @@
+/* ClientStore.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import java.util.HashMap;
+
+/**
+ * The client-side implementation of the SRP security context store.
+ */
+public class ClientStore
+{
+ /** The underlying singleton. */
+ private static ClientStore singleton = null;
+ /** The map of uid --> SASL Security Context record. */
+ private static final HashMap uid2ssc = new HashMap();
+ /** The map of sid --> Session timing record. */
+ private static final HashMap uid2ttl = new HashMap();
+ /** A synchronisation lock. */
+ private static final Object lock = new Object();
+
+ /** Private constructor to enforce Singleton pattern. */
+ private ClientStore()
+ {
+ super();
+
+ // TODO: add a cleaning timer thread
+ }
+
+ /**
+ * Returns the classloader Singleton.
+ *
+ * @return the classloader Singleton instance.
+ */
+ static synchronized final ClientStore instance()
+ {
+ if (singleton == null)
+ singleton = new ClientStore();
+ return singleton;
+ }
+
+ /**
+ * Returns a boolean flag indicating if the designated client's session is
+ * still alive or not.
+ *
+ * @param uid the identifier of the client whose session to check.
+ * @return <code>true</code> if the designated client's session is still
+ * alive. <code>false</code> otherwise.
+ */
+ boolean isAlive(final String uid)
+ {
+ final boolean result;
+ synchronized (lock)
+ {
+ final Object obj = uid2ssc.get(uid);
+ result = (obj != null);
+ if (result) // is it still alive?
+ {
+ final StoreEntry sto = (StoreEntry) uid2ttl.get(uid);
+ if (! sto.isAlive()) // invalidate it
+ {
+ uid2ssc.remove(uid);
+ uid2ttl.remove(uid);
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Records a mapping between a client's unique identifier and its security
+ * context.
+ *
+ * @param uid the unique identifier of the SRP client for which the session is
+ * to be cached.
+ * @param ttl the session's Time-To-Live indicator (in seconds).
+ * @param ctx the client's security context.
+ */
+ void cacheSession(final String uid, final int ttl, final SecurityContext ctx)
+ {
+ synchronized (lock)
+ {
+ uid2ssc.put(uid, ctx);
+ uid2ttl.put(uid, new StoreEntry(ttl));
+ }
+ }
+
+ /**
+ * Removes the mapping between the designated SRP client unique identifier and
+ * the its session security context (and other timing information).
+ *
+ * @param uid the identifier of the client whose session is to invalidate.
+ */
+ void invalidateSession(final String uid)
+ {
+ synchronized (lock)
+ {
+ uid2ssc.remove(uid);
+ uid2ttl.remove(uid);
+ }
+ }
+
+ /**
+ * Returns an SRP client's security context record mapped by that client's
+ * unique identifier.
+ *
+ * @param uid the identifier of the client whose session is to restore.
+ * @return the SRP client's security context.
+ */
+ SecurityContext restoreSession(final String uid)
+ {
+ final SecurityContext result;
+ synchronized (lock)
+ {
+ result = (SecurityContext) uid2ssc.remove(uid);
+ uid2ttl.remove(uid);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* IALG.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+
+import javax.security.sasl.SaslException;
+
+/**
+ * A Factory class that returns IALG (Integrity Algorithm) instances that
+ * operate as described in the draft-burdis-cat-sasl-srp-04 and later.
+ */
+public final class IALG
+ implements Cloneable
+{
+ private IMac hmac;
+
+ /** Private constructor to enforce instantiation through Factory method. */
+ private IALG(final IMac hmac)
+ {
+ super();
+
+ this.hmac = hmac;
+ }
+
+ /**
+ * Returns an instance of a SASL-SRP IALG implementation.
+ *
+ * @param algorithm the name of the HMAC algorithm.
+ * @return an instance of this object.
+ */
+ static synchronized IALG getInstance(final String algorithm)
+ throws SaslException
+ {
+ final IMac hmac;
+ hmac = MacFactory.getInstance(algorithm);
+ if (hmac == null)
+ throw new SaslException("getInstance()",
+ new NoSuchAlgorithmException(algorithm));
+ return new IALG(hmac);
+ }
+
+ public Object clone() throws CloneNotSupportedException
+ {
+ return new IALG((IMac) hmac.clone());
+ }
+
+ public void init(final KDF kdf) throws SaslException
+ {
+ try
+ {
+ final byte[] sk = kdf.derive(hmac.macSize());
+ final HashMap map = new HashMap();
+ map.put(IMac.MAC_KEY_MATERIAL, sk);
+ hmac.init(map);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new SaslException("getInstance()", x);
+ }
+ }
+
+ public void update(final byte[] data)
+ {
+ hmac.update(data, 0, data.length);
+ }
+
+ public void update(final byte[] data, final int offset, final int length)
+ {
+ hmac.update(data, offset, length);
+ }
+
+ public byte[] doFinal()
+ {
+ return hmac.digest();
+ }
+
+ /**
+ * Returns the length (in bytes) of this SASL SRP Integrity Algorithm.
+ *
+ * @return the length, in bytes, of this integrity protection algorithm.
+ */
+ public int length()
+ {
+ return hmac.macSize();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,140 @@
+/* KDF.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Registry;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.prng.UMacGenerator;
+
+import java.util.HashMap;
+
+/**
+ * The SASL-SRP KDF implementation, which is also used, depending on how it was
+ * instantiated, as a secure Pseudo Random Number Generator.
+ */
+public class KDF
+{
+ private static final int AES_BLOCK_SIZE = 16; // default block size for AES
+ private static final int AES_KEY_SIZE = 16; // default key size for the AES
+ private static final byte[] buffer = new byte[1];
+ /** Our default source of randomness. */
+ private static final PRNG prng = PRNG.getInstance();
+ /** The underlying UMAC Generator instance. */
+ private UMacGenerator umac = null;
+
+ /**
+ * Constructs an instance of the <code>KDF</code> initialised with the
+ * designated shared secret bytes.
+ *
+ * @param keyMaterial the SASL SRP shared secret (K) bytes.
+ */
+ private KDF(final byte[] keyMaterial, final int ndx)
+ {
+ super();
+
+ final HashMap map = new HashMap();
+ map.put(UMacGenerator.CIPHER, Registry.AES_CIPHER);
+ map.put(UMacGenerator.INDEX, Integer.valueOf(ndx));
+ map.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(AES_BLOCK_SIZE));
+ final byte[] key = new byte[AES_KEY_SIZE];
+ System.arraycopy(keyMaterial, 0, key, 0, AES_KEY_SIZE);
+ map.put(IBlockCipher.KEY_MATERIAL, key);
+ umac = new UMacGenerator();
+ umac.init(map);
+ }
+
+ /**
+ * A Factory mehod that returns an instance of a <code>KDF</code> based on
+ * supplied seed data.
+ *
+ * @param K the SASL SRP shared secret for a <code>KDF</code> to be used for
+ * <i>CALG</i> and <i>IALG</i> setup. <code>null</code> otherwise.
+ * @return an instance of a <code>KDF</code>.
+ */
+ static final KDF getInstance(final byte[] K)
+ {
+ int ndx = -1;
+ final byte[] keyMaterial;
+ if (K != null)
+ {
+ keyMaterial = K;
+ ndx = 0;
+ }
+ else
+ {
+ keyMaterial = new byte[AES_BLOCK_SIZE];
+ while (ndx < 1 || ndx > 255)
+ ndx = (byte) nextByte();
+ }
+ return new KDF(keyMaterial, ndx);
+ }
+
+ private static synchronized final int nextByte()
+ {
+ prng.nextBytes(buffer);
+ return (buffer[0] & 0xFF);
+ }
+
+ /**
+ * Returns a designated number of bytes suitable for use in the SASL SRP
+ * mechanism.
+ *
+ * @param length the number of bytes needed.
+ * @return a byte array containing the generated/selected bytes.
+ */
+ public synchronized byte[] derive(final int length)
+ {
+ final byte[] result = new byte[length];
+ try
+ {
+ umac.nextBytes(result, 0, length);
+ }
+ catch (IllegalStateException x) // should not happen
+ {
+ x.printStackTrace(System.err);
+ }
+ catch (LimitReachedException x) // idem
+ {
+ x.printStackTrace(System.err);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,625 @@
+/* PasswordFile.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.key.srp6.SRPAlgorithm;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+import gnu.javax.crypto.sasl.UserAlreadyExistsException;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+/**
+ * The implementation of SRP password files.
+ * <p>
+ * For SRP, there are three (3) files:
+ * <ol>
+ * <li>The password configuration file: tpasswd.conf. It contains the pairs
+ * <N,g> indexed by a number for each pair used for a user. By default, this
+ * file's pathname is constructed from the base password file pathname by
+ * prepending it with the ".conf" suffix.</li>
+ * <li>The base password file: tpasswd. It contains the related password
+ * entries for all the users with values computed using SRP's default message
+ * digest algorithm: SHA-1 (with 160-bit output block size).</li>
+ * <li>The extended password file: tpasswd2. Its name, by default, is
+ * constructed by adding the suffix "2" to the fully qualified pathname of the
+ * base password file. It contains, in addition to the same fields as the base
+ * password file, albeit with a different verifier value, an extra field
+ * identifying the message digest algorithm used to compute this (verifier)
+ * value.</li>
+ * </ol>
+ * <p>
+ * This implementation assumes the following message digest algorithm codes:
+ * <ul>
+ * <li>0: the default hash algorithm, which is SHA-1 (or its alias SHA-160).</li>
+ * <li>1: MD5.</li>
+ * <li>2: RIPEMD-128.</li>
+ * <li>3: RIPEMD-160.</li>
+ * <li>4: SHA-256.</li>
+ * <li>5: SHA-384.</li>
+ * <li>6: SHA-512.</li>
+ * </ul>
+ * <p>
+ * <b>IMPORTANT:</b> This method computes the verifiers as described in
+ * RFC-2945, which differs from the description given on the web page for SRP-6.
+ * <p>
+ * Reference:
+ * <ol>
+ * <li><a href="http://srp.stanford.edu/design.html">SRP Protocol Design</a><br>
+ * Thomas J. Wu.</li>
+ * </ol>
+ */
+public class PasswordFile
+{
+ // names of property keys used in this class
+ private static final String USER_FIELD = "user";
+ private static final String VERIFIERS_FIELD = "verifier";
+ private static final String SALT_FIELD = "salt";
+ private static final String CONFIG_FIELD = "config";
+ private static String DEFAULT_FILE;
+ static
+ {
+ DEFAULT_FILE = System.getProperty(SRPRegistry.PASSWORD_FILE,
+ SRPRegistry.DEFAULT_PASSWORD_FILE);
+ }
+ /** The SRP algorithm instances used by this object. */
+ private static final HashMap srps;
+ static
+ {
+ final HashMap map = new HashMap(SRPRegistry.SRP_ALGORITHMS.length);
+ // The first entry MUST exist. The others are optional.
+ map.put("0", SRP.instance(SRPRegistry.SRP_ALGORITHMS[0]));
+ for (int i = 1; i < SRPRegistry.SRP_ALGORITHMS.length; i++)
+ {
+ try
+ {
+ map.put(String.valueOf(i),
+ SRP.instance(SRPRegistry.SRP_ALGORITHMS[i]));
+ }
+ catch (Exception x)
+ {
+ System.err.println("Ignored: " + x);
+ x.printStackTrace(System.err);
+ }
+ }
+ srps = map;
+ }
+
+ private String confName, pwName, pw2Name;
+ private File configFile, passwdFile, passwd2File;
+ private long lastmodPasswdFile, lastmodPasswd2File;
+ private HashMap entries = new HashMap();
+ private HashMap configurations = new HashMap();
+ // default N values to use when creating a new password.conf file
+ private static final BigInteger[] Nsrp = new BigInteger[] {
+ SRPAlgorithm.N_2048,
+ SRPAlgorithm.N_1536,
+ SRPAlgorithm.N_1280,
+ SRPAlgorithm.N_1024,
+ SRPAlgorithm.N_768,
+ SRPAlgorithm.N_640,
+ SRPAlgorithm.N_512 };
+
+ public PasswordFile() throws IOException
+ {
+ this(DEFAULT_FILE);
+ }
+
+ public PasswordFile(final File pwFile) throws IOException
+ {
+ this(pwFile.getAbsolutePath());
+ }
+
+ public PasswordFile(final String pwName) throws IOException
+ {
+ this(pwName, pwName + "2", pwName + ".conf");
+ }
+
+ public PasswordFile(final String pwName, final String confName)
+ throws IOException
+ {
+ this(pwName, pwName + "2", confName);
+ }
+
+ public PasswordFile(final String pwName, final String pw2Name,
+ final String confName) throws IOException
+ {
+ super();
+
+ this.pwName = pwName;
+ this.pw2Name = pw2Name;
+ this.confName = confName;
+
+ readOrCreateConf();
+ update();
+ }
+
+ /**
+ * Returns a string representing the decimal value of an integer identifying
+ * the message digest algorithm to use for the SRP computations.
+ *
+ * @param mdName the canonical name of a message digest algorithm.
+ * @return a string representing the decimal value of an ID for that
+ * algorithm.
+ */
+ private static final String nameToID(final String mdName)
+ {
+ if (Registry.SHA_HASH.equalsIgnoreCase(mdName)
+ || Registry.SHA1_HASH.equalsIgnoreCase(mdName)
+ || Registry.SHA160_HASH.equalsIgnoreCase(mdName))
+ return "0";
+ else if (Registry.MD5_HASH.equalsIgnoreCase(mdName))
+ return "1";
+ else if (Registry.RIPEMD128_HASH.equalsIgnoreCase(mdName))
+ return "2";
+ else if (Registry.RIPEMD160_HASH.equalsIgnoreCase(mdName))
+ return "3";
+ else if (Registry.SHA256_HASH.equalsIgnoreCase(mdName))
+ return "4";
+ else if (Registry.SHA384_HASH.equalsIgnoreCase(mdName))
+ return "5";
+ else if (Registry.SHA512_HASH.equalsIgnoreCase(mdName))
+ return "6";
+ return "0";
+ }
+
+ /**
+ * Checks if the current configuration file contains the <N, g> pair for
+ * the designated <code>index</code>.
+ *
+ * @param index a string representing 1-digit identification of an <N, g>
+ * pair used.
+ * @return <code>true</code> if the designated <code>index</code> is that
+ * of a known <N, g> pair, and <code>false</code> otherwise.
+ * @throws IOException if an exception occurs during the process.
+ * @see SRPRegistry#N_2048_BITS
+ * @see SRPRegistry#N_1536_BITS
+ * @see SRPRegistry#N_1280_BITS
+ * @see SRPRegistry#N_1024_BITS
+ * @see SRPRegistry#N_768_BITS
+ * @see SRPRegistry#N_640_BITS
+ * @see SRPRegistry#N_512_BITS
+ */
+ public synchronized boolean containsConfig(final String index)
+ throws IOException
+ {
+ checkCurrent();
+ return configurations.containsKey(index);
+ }
+
+ /**
+ * Returns a pair of strings representing the pair of <code>N</code> and
+ * <code>g</code> MPIs for the designated <code>index</code>.
+ *
+ * @param index a string representing 1-digit identification of an <N, g>
+ * pair to look up.
+ * @return a pair of strings, arranged in an array, where the first (at index
+ * position #0) is the repesentation of the MPI <code>N</code>, and
+ * the second (at index position #1) is the representation of the MPI
+ * <code>g</code>. If the <code>index</code> refers to an unknown
+ * pair, then an empty string array is returned.
+ * @throws IOException if an exception occurs during the process.
+ */
+ public synchronized String[] lookupConfig(final String index)
+ throws IOException
+ {
+ checkCurrent();
+ String[] result = null;
+ if (configurations.containsKey(index))
+ result = (String[]) configurations.get(index);
+ return result;
+ }
+
+ public synchronized boolean contains(final String user) throws IOException
+ {
+ checkCurrent();
+ return entries.containsKey(user);
+ }
+
+ public synchronized void add(final String user, final String passwd,
+ final byte[] salt, final String index)
+ throws IOException
+ {
+ checkCurrent();
+ if (entries.containsKey(user))
+ throw new UserAlreadyExistsException(user);
+ final HashMap fields = new HashMap(4);
+ fields.put(USER_FIELD, user); // 0
+ fields.put(VERIFIERS_FIELD, newVerifiers(user, salt, passwd, index)); // 1
+ fields.put(SALT_FIELD, Util.toBase64(salt)); // 2
+ fields.put(CONFIG_FIELD, index); // 3
+ entries.put(user, fields);
+ savePasswd();
+ }
+
+ public synchronized void changePasswd(final String user, final String passwd)
+ throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ final HashMap fields = (HashMap) entries.get(user);
+ final byte[] salt;
+ try
+ {
+ salt = Util.fromBase64((String) fields.get(SALT_FIELD));
+ }
+ catch (NumberFormatException x)
+ {
+ throw new IOException("Password file corrupt");
+ }
+ final String index = (String) fields.get(CONFIG_FIELD);
+ fields.put(VERIFIERS_FIELD, newVerifiers(user, salt, passwd, index));
+ entries.put(user, fields);
+ savePasswd();
+ }
+
+ public synchronized void savePasswd() throws IOException
+ {
+ final FileOutputStream f1 = new FileOutputStream(passwdFile);
+ final FileOutputStream f2 = new FileOutputStream(passwd2File);
+ PrintWriter pw1 = null;
+ PrintWriter pw2 = null;
+ try
+ {
+ pw1 = new PrintWriter(f1, true);
+ pw2 = new PrintWriter(f2, true);
+ this.writePasswd(pw1, pw2);
+ }
+ finally
+ {
+ if (pw1 != null)
+ try
+ {
+ pw1.flush();
+ }
+ finally
+ {
+ pw1.close();
+ }
+ if (pw2 != null)
+ try
+ {
+ pw2.flush();
+ }
+ finally
+ {
+ pw2.close();
+ }
+ try
+ {
+ f1.close();
+ }
+ catch (IOException ignored)
+ {
+ }
+ try
+ {
+ f2.close();
+ }
+ catch (IOException ignored)
+ {
+ }
+ }
+ lastmodPasswdFile = passwdFile.lastModified();
+ lastmodPasswd2File = passwd2File.lastModified();
+ }
+
+ /**
+ * Returns the triplet: verifier, salt and configuration file index, of a
+ * designated user, and a designated message digest algorithm name, as an
+ * array of strings.
+ *
+ * @param user the username.
+ * @param mdName the canonical name of the SRP's message digest algorithm.
+ * @return a string array containing, in this order, the BASE-64 encodings of
+ * the verifier, the salt and the index in the password configuration
+ * file of the MPIs N and g of the designated user.
+ */
+ public synchronized String[] lookup(final String user, final String mdName)
+ throws IOException
+ {
+ checkCurrent();
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
+ final HashMap fields = (HashMap) entries.get(user);
+ final HashMap verifiers = (HashMap) fields.get(VERIFIERS_FIELD);
+ final String salt = (String) fields.get(SALT_FIELD);
+ final String index = (String) fields.get(CONFIG_FIELD);
+ final String verifier = (String) verifiers.get(nameToID(mdName));
+ return new String[] { verifier, salt, index };
+ }
+
+ private synchronized void readOrCreateConf() throws IOException
+ {
+ configurations.clear();
+ final FileInputStream fis;
+ configFile = new File(confName);
+ try
+ {
+ fis = new FileInputStream(configFile);
+ readConf(fis);
+ }
+ catch (FileNotFoundException x)
+ { // create a default one
+ final String g = Util.toBase64(Util.trim(new BigInteger("2")));
+ String index, N;
+ for (int i = 0; i < Nsrp.length; i++)
+ {
+ index = String.valueOf(i + 1);
+ N = Util.toBase64(Util.trim(Nsrp[i]));
+ configurations.put(index, new String[] { N, g });
+ }
+ FileOutputStream f0 = null;
+ PrintWriter pw0 = null;
+ try
+ {
+ f0 = new FileOutputStream(configFile);
+ pw0 = new PrintWriter(f0, true);
+ this.writeConf(pw0);
+ }
+ finally
+ {
+ if (pw0 != null)
+ pw0.close();
+ else if (f0 != null)
+ f0.close();
+ }
+ }
+ }
+
+ private void readConf(final InputStream in) throws IOException
+ {
+ final BufferedReader din = new BufferedReader(new InputStreamReader(in));
+ String line, index, N, g;
+ StringTokenizer st;
+ while ((line = din.readLine()) != null)
+ {
+ st = new StringTokenizer(line, ":");
+ try
+ {
+ index = st.nextToken();
+ N = st.nextToken();
+ g = st.nextToken();
+ }
+ catch (NoSuchElementException x)
+ {
+ throw new IOException("SRP password configuration file corrupt");
+ }
+ configurations.put(index, new String[] { N, g });
+ }
+ }
+
+ private void writeConf(final PrintWriter pw)
+ {
+ String ndx;
+ String[] mpi;
+ StringBuffer sb;
+ for (Iterator it = configurations.keySet().iterator(); it.hasNext();)
+ {
+ ndx = (String) it.next();
+ mpi = (String[]) configurations.get(ndx);
+ sb = new StringBuffer(ndx)
+ .append(":").append(mpi[0])
+ .append(":").append(mpi[1]);
+ pw.println(sb.toString());
+ }
+ }
+
+ /**
+ * Compute the new verifiers for the designated username and password.
+ * <p>
+ * <b>IMPORTANT:</b> This method computes the verifiers as described in
+ * RFC-2945, which differs from the description given on the web page for
+ * SRP-6.
+ *
+ * @param user the user's name.
+ * @param s the user's salt.
+ * @param password the user's password
+ * @param index the index of the <N, g> pair to use for this user.
+ * @return a {@link java.util.Map} of user verifiers.
+ * @throws UnsupportedEncodingException if the US-ASCII decoder is not
+ * available on this platform.
+ */
+ private HashMap newVerifiers(final String user, final byte[] s,
+ final String password, final String index)
+ throws UnsupportedEncodingException
+ {
+ // to ensure inter-operability with non-java tools
+ final String[] mpi = (String[]) configurations.get(index);
+ final BigInteger N = new BigInteger(1, Util.fromBase64(mpi[0]));
+ final BigInteger g = new BigInteger(1, Util.fromBase64(mpi[1]));
+ final HashMap result = new HashMap(srps.size());
+ BigInteger x, v;
+ SRP srp;
+ for (int i = 0; i < srps.size(); i++)
+ {
+ final String digestID = String.valueOf(i);
+ srp = (SRP) srps.get(digestID);
+ x = new BigInteger(1, srp.computeX(s, user, password));
+ v = g.modPow(x, N);
+ final String verifier = Util.toBase64(v.toByteArray());
+ result.put(digestID, verifier);
+ }
+ return result;
+ }
+
+ private synchronized void update() throws IOException
+ {
+ entries.clear();
+ FileInputStream fis;
+ passwdFile = new File(pwName);
+ lastmodPasswdFile = passwdFile.lastModified();
+ try
+ {
+ fis = new FileInputStream(passwdFile);
+ readPasswd(fis);
+ }
+ catch (FileNotFoundException ignored)
+ {
+ }
+ passwd2File = new File(pw2Name);
+ lastmodPasswd2File = passwd2File.lastModified();
+ try
+ {
+ fis = new FileInputStream(passwd2File);
+ readPasswd2(fis);
+ }
+ catch (FileNotFoundException ignored)
+ {
+ }
+ }
+
+ private void checkCurrent() throws IOException
+ {
+ if (passwdFile.lastModified() > lastmodPasswdFile
+ || passwd2File.lastModified() > lastmodPasswd2File)
+ update();
+ }
+
+ private void readPasswd(final InputStream in) throws IOException
+ {
+ final BufferedReader din = new BufferedReader(new InputStreamReader(in));
+ String line, user, verifier, salt, index;
+ StringTokenizer st;
+ while ((line = din.readLine()) != null)
+ {
+ st = new StringTokenizer(line, ":");
+ try
+ {
+ user = st.nextToken();
+ verifier = st.nextToken();
+ salt = st.nextToken();
+ index = st.nextToken();
+ }
+ catch (NoSuchElementException x)
+ {
+ throw new IOException("SRP base password file corrupt");
+ }
+ final HashMap verifiers = new HashMap(6);
+ verifiers.put("0", verifier);
+ final HashMap fields = new HashMap(4);
+ fields.put(USER_FIELD, user);
+ fields.put(VERIFIERS_FIELD, verifiers);
+ fields.put(SALT_FIELD, salt);
+ fields.put(CONFIG_FIELD, index);
+ entries.put(user, fields);
+ }
+ }
+
+ private void readPasswd2(final InputStream in) throws IOException
+ {
+ final BufferedReader din = new BufferedReader(new InputStreamReader(in));
+ String line, digestID, user, verifier;
+ StringTokenizer st;
+ HashMap fields, verifiers;
+ while ((line = din.readLine()) != null)
+ {
+ st = new StringTokenizer(line, ":");
+ try
+ {
+ digestID = st.nextToken();
+ user = st.nextToken();
+ verifier = st.nextToken();
+ }
+ catch (NoSuchElementException x)
+ {
+ throw new IOException("SRP extended password file corrupt");
+ }
+ fields = (HashMap) entries.get(user);
+ if (fields != null)
+ {
+ verifiers = (HashMap) fields.get(VERIFIERS_FIELD);
+ verifiers.put(digestID, verifier);
+ }
+ }
+ }
+
+ private void writePasswd(final PrintWriter pw1, final PrintWriter pw2)
+ throws IOException
+ {
+ String user, digestID;
+ HashMap fields, verifiers;
+ StringBuffer sb1, sb2;
+ Iterator j;
+ final Iterator i = entries.keySet().iterator();
+ while (i.hasNext())
+ {
+ user = (String) i.next();
+ fields = (HashMap) entries.get(user);
+ if (! user.equals(fields.get(USER_FIELD)))
+ throw new IOException("Inconsistent SRP password data");
+ verifiers = (HashMap) fields.get(VERIFIERS_FIELD);
+ sb1 = new StringBuffer(user)
+ .append(":").append((String) verifiers.get("0"))
+ .append(":").append((String) fields.get(SALT_FIELD))
+ .append(":").append((String) fields.get(CONFIG_FIELD));
+ pw1.println(sb1.toString());
+ // write extended information
+ j = verifiers.keySet().iterator();
+ while (j.hasNext())
+ {
+ digestID = (String) j.next();
+ if (! "0".equals(digestID))
+ {
+ // #0 is the default digest, already present in tpasswd!
+ sb2 = new StringBuffer(digestID)
+ .append(":").append(user)
+ .append(":").append((String) verifiers.get(digestID));
+ pw2.println(sb2.toString());
+ }
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,255 @@
+/* SRP.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.util.Util;
+
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.util.HashMap;
+
+/**
+ * A Factory class that returns SRP Singletons that know all SRP-related
+ * mathematical computations and protocol-related operations for both the
+ * client- and server-sides.
+ */
+public final class SRP
+{
+ /** The map of already instantiated SRP algorithm instances. */
+ private static final HashMap algorithms = new HashMap();
+ private static final byte COLON = (byte) 0x3A;
+ /** The underlying message digest algorithm used for all SRP calculations. */
+ private IMessageDigest mda;
+
+ /** Trivial private constructor to enforce Singleton pattern. */
+ private SRP(final IMessageDigest mda)
+ {
+ super();
+
+ this.mda = mda;
+ }
+
+ /**
+ * Returns an instance of this object that uses the designated message digest
+ * algorithm as its digest function.
+ *
+ * @return an instance of this object for the designated digest name.
+ */
+ public static synchronized SRP instance(String mdName)
+ {
+ if (mdName != null)
+ mdName = mdName.trim().toLowerCase();
+ if (mdName == null || mdName.equals(""))
+ mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME;
+ SRP result = (SRP) algorithms.get(mdName);
+ if (result == null)
+ {
+ final IMessageDigest mda = HashFactory.getInstance(mdName);
+ result = new SRP(mda);
+ algorithms.put(mdName, result);
+ }
+ return result;
+ }
+
+ private static final byte[] xor(final byte[] b1, final byte[] b2,
+ final int length)
+ {
+ final byte[] result = new byte[length];
+ for (int i = 0; i < length; ++i)
+ result[i] = (byte)(b1[i] ^ b2[i]);
+ return result;
+ }
+
+ /** @return the message digest algorithm name used by this instance. */
+ public String getAlgorithm()
+ {
+ return mda.name();
+ }
+
+ /**
+ * Returns a new instance of the SRP message digest algorithm --which is
+ * SHA-160 by default, but could be anything else provided the proper
+ * conditions as specified in the SRP specifications.
+ *
+ * @return a new instance of the underlying SRP message digest algorithm.
+ * @throws RuntimeException if the implementation of the message digest
+ * algorithm does not support cloning.
+ */
+ public IMessageDigest newDigest()
+ {
+ return (IMessageDigest) mda.clone();
+ }
+
+ /**
+ * Convenience method to return the result of digesting the designated input
+ * with a new instance of the SRP message digest algorithm.
+ *
+ * @param src some bytes to digest.
+ * @return the bytes constituting the result of digesting the designated input
+ * with a new instance of the SRP message digest algorithm.
+ */
+ public byte[] digest(final byte[] src)
+ {
+ final IMessageDigest hash = (IMessageDigest) mda.clone();
+ hash.update(src, 0, src.length);
+ return hash.digest();
+ }
+
+ /**
+ * Convenience method to return the result of digesting the designated input
+ * with a new instance of the SRP message digest algorithm.
+ *
+ * @param src a String whose bytes (using US-ASCII encoding) are to be
+ * digested.
+ * @return the bytes constituting the result of digesting the designated input
+ * with a new instance of the SRP message digest algorithm.
+ * @throws UnsupportedEncodingException if US-ASCII charset is not found.
+ */
+ public byte[] digest(final String src) throws UnsupportedEncodingException
+ {
+ return digest(src.getBytes("US-ASCII"));
+ }
+
+ /**
+ * Convenience method to XOR N bytes from two arrays; N being the output size
+ * of the SRP message digest algorithm.
+ *
+ * @param a the first byte array.
+ * @param b the second one.
+ * @return N bytes which are the result of the XOR operations on the first N
+ * bytes from the designated arrays. N is the size of the SRP message
+ * digest algorithm; eg. 20 for SHA-160.
+ */
+ public byte[] xor(final byte[] a, final byte[] b)
+ {
+ return xor(a, b, mda.hashSize());
+ }
+
+ public byte[] generateM1(final BigInteger N, final BigInteger g,
+ final String U, final byte[] s, final BigInteger A,
+ final BigInteger B, final byte[] K, final String I,
+ final String L, final byte[] cn, final byte[] cCB)
+ throws UnsupportedEncodingException
+ {
+ final IMessageDigest hash = (IMessageDigest) mda.clone();
+ byte[] b;
+ b = xor(digest(Util.trim(N)), digest(Util.trim(g)));
+ hash.update(b, 0, b.length);
+ b = digest(U);
+ hash.update(b, 0, b.length);
+ hash.update(s, 0, s.length);
+ b = Util.trim(A);
+ hash.update(b, 0, b.length);
+ b = Util.trim(B);
+ hash.update(b, 0, b.length);
+ hash.update(K, 0, K.length);
+ b = digest(I);
+ hash.update(b, 0, b.length);
+ b = digest(L);
+ hash.update(b, 0, b.length);
+ hash.update(cn, 0, cn.length);
+ hash.update(cCB, 0, cCB.length);
+ return hash.digest();
+ }
+
+ public byte[] generateM2(final BigInteger A, final byte[] M1, final byte[] K,
+ final String U, final String I, final String o,
+ final byte[] sid, final int ttl, final byte[] cIV,
+ final byte[] sIV, final byte[] sCB)
+ throws UnsupportedEncodingException
+ {
+ final IMessageDigest hash = (IMessageDigest) mda.clone();
+ byte[] b;
+ b = Util.trim(A);
+ hash.update(b, 0, b.length);
+ hash.update(M1, 0, M1.length);
+ hash.update(K, 0, K.length);
+ b = digest(U);
+ hash.update(b, 0, b.length);
+ b = digest(I);
+ hash.update(b, 0, b.length);
+ b = digest(o);
+ hash.update(b, 0, b.length);
+ hash.update(sid, 0, sid.length);
+ hash.update((byte)(ttl >>> 24));
+ hash.update((byte)(ttl >>> 16));
+ hash.update((byte)(ttl >>> 8));
+ hash.update((byte) ttl);
+ hash.update(cIV, 0, cIV.length);
+ hash.update(sIV, 0, sIV.length);
+ hash.update(sCB, 0, sCB.length);
+ return hash.digest();
+ }
+
+ public byte[] generateKn(final byte[] K, final byte[] cn, final byte[] sn)
+ {
+ final IMessageDigest hash = (IMessageDigest) mda.clone();
+ hash.update(K, 0, K.length);
+ hash.update(cn, 0, cn.length);
+ hash.update(sn, 0, sn.length);
+ return hash.digest();
+ }
+
+ public byte[] computeX(final byte[] s, final String user,
+ final String password)
+ throws UnsupportedEncodingException
+ {
+ return computeX(s, user.getBytes("US-ASCII"), password.getBytes("US-ASCII"));
+ }
+
+ public byte[] computeX(final byte[] s, final String user, final byte[] p)
+ throws UnsupportedEncodingException
+ {
+ return computeX(s, user.getBytes("US-ASCII"), p);
+ }
+
+ private byte[] computeX(final byte[] s, final byte[] user, final byte[] p)
+ {
+ final IMessageDigest hash = (IMessageDigest) mda.clone();
+ hash.update(user, 0, user.length);
+ hash.update(COLON);
+ hash.update(p, 0, p.length);
+ final byte[] up = hash.digest();
+ hash.update(s, 0, s.length);
+ hash.update(up, 0, up.length);
+ return hash.digest();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,177 @@
+/* SRPAuthInfoProvider.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.sasl.IAuthInfoProvider;
+import gnu.javax.crypto.sasl.NoSuchUserException;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.sasl.AuthenticationException;
+
+/**
+ * The SRP mechanism authentication information provider implementation.
+ */
+public class SRPAuthInfoProvider
+ implements IAuthInfoProvider
+{
+ private PasswordFile passwordFile = null;
+
+ // implicit 0-args constrcutor
+
+ public void activate(Map context) throws AuthenticationException
+ {
+ try
+ {
+ if (context == null)
+ passwordFile = new PasswordFile();
+ else
+ {
+ passwordFile = (PasswordFile) context.get(SRPRegistry.PASSWORD_DB);
+ if (passwordFile == null)
+ {
+ String pfn = (String) context.get(SRPRegistry.PASSWORD_FILE);
+ if (pfn == null)
+ passwordFile = new PasswordFile();
+ else
+ passwordFile = new PasswordFile(pfn);
+ }
+ }
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("activate()", x);
+ }
+ }
+
+ public void passivate() throws AuthenticationException
+ {
+ passwordFile = null;
+ }
+
+ public boolean contains(String userName) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("contains()",
+ new IllegalStateException());
+ boolean result = false;
+ try
+ {
+ result = passwordFile.contains(userName);
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("contains()", x);
+ }
+ return result;
+ }
+
+ public Map lookup(Map userID) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("lookup()", new IllegalStateException());
+ Map result = new HashMap();
+ try
+ {
+ String userName = (String) userID.get(Registry.SASL_USERNAME);
+ if (userName == null)
+ throw new NoSuchUserException("");
+ String mdName = (String) userID.get(SRPRegistry.MD_NAME_FIELD);
+ String[] data = passwordFile.lookup(userName, mdName);
+ result.put(SRPRegistry.USER_VERIFIER_FIELD, data[0]);
+ result.put(SRPRegistry.SALT_FIELD, data[1]);
+ result.put(SRPRegistry.CONFIG_NDX_FIELD, data[2]);
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("lookup()", x);
+ }
+ return result;
+ }
+
+ public void update(Map userCredentials) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("update()", new IllegalStateException());
+ try
+ {
+ String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
+ String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
+ String salt = (String) userCredentials.get(SRPRegistry.SALT_FIELD);
+ String config = (String) userCredentials.get(SRPRegistry.CONFIG_NDX_FIELD);
+ if (salt == null || config == null)
+ passwordFile.changePasswd(userName, password);
+ else
+ passwordFile.add(userName, password, Util.fromBase64(salt), config);
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("update()", x);
+ }
+ }
+
+ public Map getConfiguration(String mode) throws AuthenticationException
+ {
+ if (passwordFile == null)
+ throw new AuthenticationException("getConfiguration()",
+ new IllegalStateException());
+ Map result = new HashMap();
+ try
+ {
+ String[] data = passwordFile.lookupConfig(mode);
+ result.put(SRPRegistry.SHARED_MODULUS, data[0]);
+ result.put(SRPRegistry.FIELD_GENERATOR, data[1]);
+ }
+ catch (Exception x)
+ {
+ if (x instanceof AuthenticationException)
+ throw (AuthenticationException) x;
+ throw new AuthenticationException("getConfiguration()", x);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,952 @@
+/* SRPClient.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.hash.MD5;
+import gnu.java.security.util.PRNG;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.key.IKeyAgreementParty;
+import gnu.javax.crypto.key.IncomingMessage;
+import gnu.javax.crypto.key.KeyAgreementException;
+import gnu.javax.crypto.key.KeyAgreementFactory;
+import gnu.javax.crypto.key.OutgoingMessage;
+import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;
+import gnu.javax.crypto.sasl.ClientMechanism;
+import gnu.javax.crypto.sasl.IllegalMechanismStateException;
+import gnu.javax.crypto.sasl.InputBuffer;
+import gnu.javax.crypto.sasl.IntegrityException;
+import gnu.javax.crypto.sasl.OutputBuffer;
+import gnu.javax.security.auth.Password;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+import java.util.logging.Logger;
+
+import javax.security.auth.DestroyFailedException;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+
+/**
+ * The SASL-SRP client-side mechanism.
+ */
+public class SRPClient
+ extends ClientMechanism
+ implements SaslClient
+{
+ private static final Logger log = Logger.getLogger(SRPClient.class.getName());
+ private String uid; // the unique key for this type of client
+ private String U; // the authentication identity
+ BigInteger N, g, A, B;
+ private Password password; // the authentication credentials
+ private byte[] s; // the user's salt
+ private byte[] cIV, sIV; // client+server IVs, when confidentiality is on
+ private byte[] M1, M2; // client+server evidences
+ private byte[] cn, sn; // client's and server's nonce
+ private SRP srp; // SRP algorithm instance used by this client
+ private byte[] sid; // session ID when re-used
+ private int ttl; // session time-to-live in seconds
+ private byte[] sCB; // the peer's channel binding data
+ private String L; // available options
+ private String o;
+ private String chosenIntegrityAlgorithm;
+ private String chosenConfidentialityAlgorithm;
+ private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;
+ private byte[] K; // shared session key
+ private boolean replayDetection = true; // whether Replay Detection is on
+ private int inCounter = 0; // messages sequence numbers
+ private int outCounter = 0;
+ private IALG inMac, outMac; // if !null, use for integrity
+ private CALG inCipher, outCipher; // if !null, use for confidentiality
+ private IKeyAgreementParty clientHandler =
+ KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA);
+ /** Our default source of randomness. */
+ private PRNG prng = null;
+
+ public SRPClient()
+ {
+ super(Registry.SASL_SRP_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ // we shall keep track of the sid (and the security context of this SRP
+ // client) based on the initialisation parameters of an SRP session.
+ // we shall compute a unique key for those parameters and key the sid
+ // (and the security context) accordingly.
+ // 1. compute the mapping key. use MD5 (the fastest) for this purpose
+ final MD5 md = new MD5();
+ byte[] b;
+ b = authorizationID.getBytes();
+ md.update(b, 0, b.length);
+ b = serverName.getBytes();
+ md.update(b, 0, b.length);
+ b = protocol.getBytes();
+ md.update(b, 0, b.length);
+ if (channelBinding.length > 0)
+ md.update(channelBinding, 0, channelBinding.length);
+
+ uid = Util.toBase64(md.digest());
+ if (ClientStore.instance().isAlive(uid))
+ {
+ final SecurityContext ctx = ClientStore.instance().restoreSession(uid);
+ srp = SRP.instance(ctx.getMdName());
+ sid = ctx.getSID();
+ K = ctx.getK();
+ cIV = ctx.getClientIV();
+ sIV = ctx.getServerIV();
+ replayDetection = ctx.hasReplayDetection();
+ inCounter = ctx.getInCounter();
+ outCounter = ctx.getOutCounter();
+ inMac = ctx.getInMac();
+ outMac = ctx.getOutMac();
+ inCipher = ctx.getInCipher();
+ outCipher = ctx.getOutCipher();
+ }
+ else
+ {
+ sid = new byte[0];
+ ttl = 0;
+ K = null;
+ cIV = null;
+ sIV = null;
+ cn = null;
+ sn = null;
+ }
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ try
+ {
+ password.destroy();
+ }
+ catch (DestroyFailedException dfe)
+ {
+ SaslException se = new SaslException("resetMechanism()");
+ se.initCause(dfe);
+ throw se;
+ }
+ password = null;
+ M1 = null;
+ K = null;
+ cIV = null;
+ sIV = null;
+ inMac = outMac = null;
+ inCipher = outCipher = null;
+ sid = null;
+ ttl = 0;
+ cn = null;
+ sn = null;
+ }
+
+ public boolean hasInitialResponse()
+ {
+ return true;
+ }
+
+ public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
+ {
+ switch (state)
+ {
+ case 0:
+ state++;
+ return sendIdentities();
+ case 1:
+ state++;
+ final byte[] result = sendPublicKey(challenge);
+ try
+ {
+ password.destroy(); //don't need further this session
+ }
+ catch (DestroyFailedException x)
+ {
+ SaslException se = new SaslException("sendPublicKey()");
+ se.initCause(se);
+ throw se;
+ }
+ return result;
+ case 2: // should only occur if session re-use was rejected
+ if (! complete)
+ {
+ state++;
+ return receiveEvidence(challenge);
+ }
+ // else fall through
+ default:
+ throw new IllegalMechanismStateException("evaluateChallenge()");
+ }
+ }
+
+ protected byte[] engineUnwrap(final byte[] incoming, final int offset,
+ final int len) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineUnwrap");
+ if (inMac == null && inCipher == null)
+ throw new IllegalStateException("connection is not protected");
+ // at this point one, or both, of confidentiality and integrity protection
+ // services are active.
+ final byte[] result;
+ try
+ {
+ if (inMac != null)
+ { // integrity bytes are at the end of the stream
+ final int macBytesCount = inMac.length();
+ final int payloadLength = len - macBytesCount;
+ final byte[] received_mac = new byte[macBytesCount];
+ System.arraycopy(incoming, offset + payloadLength, received_mac, 0,
+ macBytesCount);
+ if (Configuration.DEBUG)
+ log.fine("Got C (received MAC): " + Util.dumpString(received_mac));
+ inMac.update(incoming, offset, payloadLength);
+ if (replayDetection)
+ {
+ inCounter++;
+ if (Configuration.DEBUG)
+ log.fine("inCounter=" + inCounter);
+ inMac.update(new byte[] {
+ (byte)(inCounter >>> 24),
+ (byte)(inCounter >>> 16),
+ (byte)(inCounter >>> 8),
+ (byte) inCounter });
+ }
+ final byte[] computed_mac = inMac.doFinal();
+ if (Configuration.DEBUG)
+ log.fine("Computed MAC: " + Util.dumpString(computed_mac));
+ if (! Arrays.equals(received_mac, computed_mac))
+ throw new IntegrityException("engineUnwrap()");
+ // deal with the payload, which can be either plain or encrypted
+ if (inCipher != null)
+ result = inCipher.doFinal(incoming, offset, payloadLength);
+ else
+ {
+ result = new byte[len - macBytesCount];
+ System.arraycopy(incoming, offset, result, 0, result.length);
+ }
+ }
+ else // no integrity protection; just confidentiality
+ result = inCipher.doFinal(incoming, offset, len);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("engineUnwrap()", x);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineUnwrap");
+ return result;
+ }
+
+ protected byte[] engineWrap(final byte[] outgoing, final int offset,
+ final int len) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineWrap");
+ if (outMac == null && outCipher == null)
+ throw new IllegalStateException("connection is not protected");
+ // at this point one, or both, of confidentiality and integrity protection
+ // services are active.
+ byte[] result;
+ try
+ {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ // Process the data
+ if (outCipher != null)
+ {
+ result = outCipher.doFinal(outgoing, offset, len);
+ if (Configuration.DEBUG)
+ log.fine("Encoding c (encrypted plaintext): "
+ + Util.dumpString(result));
+ out.write(result);
+ if (outMac != null)
+ {
+ outMac.update(result);
+ if (replayDetection)
+ {
+ outCounter++;
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] {
+ (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
+ }
+ final byte[] C = outMac.doFinal();
+ out.write(C);
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ // else confidentiality only; do nothing
+ }
+ else // no confidentiality; just integrity [+ replay detection]
+ {
+ if (Configuration.DEBUG)
+ log.fine("Encoding p (plaintext): "
+ + Util.dumpString(outgoing, offset, len));
+ out.write(outgoing, offset, len);
+ outMac.update(outgoing, offset, len);
+ if (replayDetection)
+ {
+ outCounter++;
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] {
+ (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
+ }
+ final byte[] C = outMac.doFinal();
+ out.write(C);
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ result = out.toByteArray();
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("engineWrap()", x);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineWrap");
+ return result;
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ if (inMac != null)
+ {
+ if (inCipher != null)
+ return Registry.QOP_AUTH_CONF;
+ return Registry.QOP_AUTH_INT;
+ }
+ return Registry.QOP_AUTH;
+ }
+
+ protected String getNegotiatedStrength()
+ {
+ if (inMac != null)
+ {
+ if (inCipher != null)
+ return Registry.STRENGTH_HIGH;
+ return Registry.STRENGTH_MEDIUM;
+ }
+ return Registry.STRENGTH_LOW;
+ }
+
+ protected String getNegotiatedRawSendSize()
+ {
+ return String.valueOf(rawSendSize);
+ }
+
+ protected String getReuse()
+ {
+ return Registry.REUSE_TRUE;
+ }
+
+ private byte[] sendIdentities() throws SaslException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "sendIdentities");
+ // If necessary, prompt the client for the username and password
+ getUsernameAndPassword();
+ if (Configuration.DEBUG)
+ {
+ log.fine("Password: \"" + new String(password.getPassword()) + "\"");
+ log.fine("Encoding U (username): \"" + U + "\"");
+ log.fine("Encoding I (userid): \"" + authorizationID + "\"");
+ }
+ // if session re-use generate new 16-byte nonce
+ if (sid.length != 0)
+ {
+ cn = new byte[16];
+ getDefaultPRNG().nextBytes(cn);
+ }
+ else
+ cn = new byte[0];
+ final OutputBuffer frameOut = new OutputBuffer();
+ try
+ {
+ frameOut.setText(U);
+ frameOut.setText(authorizationID);
+ frameOut.setEOS(sid); // session ID to re-use
+ frameOut.setOS(cn); // client nonce
+ frameOut.setEOS(channelBinding);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendIdentities()", x);
+ }
+ final byte[] result = frameOut.encode();
+ if (Configuration.DEBUG)
+ {
+ log.fine("C: " + Util.dumpString(result));
+ log.fine(" U = " + U);
+ log.fine(" I = " + authorizationID);
+ log.fine("sid = " + new String(sid));
+ log.fine(" cn = " + Util.dumpString(cn));
+ log.fine("cCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendIdentities");
+ }
+ return result;
+ }
+
+ private byte[] sendPublicKey(final byte[] input) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendPublicKey");
+ log.fine("S: " + Util.dumpString(input));
+ }
+ // Server sends [00], N, g, s, B, L
+ // or [FF], sn, sCB
+ final InputBuffer frameIn = new InputBuffer(input);
+ final int ack;
+ try
+ {
+ ack = (int) frameIn.getScalar(1);
+ if (ack == 0x00) // new session
+ {
+ N = frameIn.getMPI();
+ if (Configuration.DEBUG)
+ log.fine("Got N (modulus): " + Util.dump(N));
+ g = frameIn.getMPI();
+ if (Configuration.DEBUG)
+ log.fine("Got g (generator): " + Util.dump(g));
+ s = frameIn.getOS();
+ if (Configuration.DEBUG)
+ log.fine("Got s (salt): " + Util.dumpString(s));
+ B = frameIn.getMPI();
+ if (Configuration.DEBUG)
+ log.fine("Got B (server ephermeral public key): " + Util.dump(B));
+ L = frameIn.getText();
+ if (Configuration.DEBUG)
+ log.fine("Got L (available options): \"" + L + "\"");
+ }
+ else if (ack == 0xFF) // session re-use
+ {
+ sn = frameIn.getOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sn (server nonce): " + Util.dumpString(sn));
+ sCB = frameIn.getEOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB));
+ }
+ else // unexpected scalar
+ throw new SaslException("sendPublicKey(): Invalid scalar (" + ack
+ + ") in server's request");
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("sendPublicKey()", x);
+ }
+ if (ack == 0x00)
+ { // new session ---------------------------------------
+ o = createO(L.toLowerCase()); // do this first to initialise the SRP hash
+ final byte[] pBytes; // use ASCII encoding to inter-operate w/ non-java
+ pBytes = password.getBytes();
+ // ----------------------------------------------------------------------
+ final HashMap mapA = new HashMap();
+ mapA.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm());
+ mapA.put(SRP6KeyAgreement.USER_IDENTITY, U);
+ mapA.put(SRP6KeyAgreement.USER_PASSWORD, pBytes);
+ try
+ {
+ clientHandler.init(mapA);
+ clientHandler.processMessage(null);
+ }
+ catch (KeyAgreementException x)
+ {
+ throw new SaslException("sendPublicKey()", x);
+ }
+ // -------------------------------------------------------------------
+ try
+ {
+ OutgoingMessage out = new OutgoingMessage();
+ out.writeMPI(N);
+ out.writeMPI(g);
+ out.writeMPI(new BigInteger(1, s));
+ out.writeMPI(B);
+ IncomingMessage in = new IncomingMessage(out.toByteArray());
+ out = clientHandler.processMessage(in);
+ in = new IncomingMessage(out.toByteArray());
+ A = in.readMPI();
+ K = clientHandler.getSharedSecret();
+ }
+ catch (KeyAgreementException x)
+ {
+ throw new SaslException("sendPublicKey()", x);
+ }
+ // -------------------------------------------------------------------
+ if (Configuration.DEBUG)
+ {
+ log.fine("K: " + Util.dumpString(K));
+ log.fine("Encoding A (client ephemeral public key): " + Util.dump(A));
+ }
+ try
+ {
+ M1 = srp.generateM1(N, g, U, s, A, B, K, authorizationID, L, cn,
+ channelBinding);
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("sendPublicKey()", x);
+ }
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding o (client chosen options): \"" + o + "\"");
+ log.fine("Encoding cIV (client IV): \"" + Util.dumpString(cIV) + "\"");
+ }
+ final OutputBuffer frameOut = new OutputBuffer();
+ try
+ {
+ frameOut.setMPI(A);
+ frameOut.setOS(M1);
+ frameOut.setText(o);
+ frameOut.setOS(cIV);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendPublicKey()", x);
+ }
+ final byte[] result = frameOut.encode();
+ if (Configuration.DEBUG)
+ {
+ log.fine("New session, or session re-use rejected...");
+ log.fine("C: " + Util.dumpString(result));
+ log.fine(" A = 0x" + A.toString(16));
+ log.fine(" M1 = " + Util.dumpString(M1));
+ log.fine(" o = " + o);
+ log.fine("cIV = " + Util.dumpString(cIV));
+ log.exiting(this.getClass().getName(), "sendPublicKey");
+ }
+ return result;
+ }
+ else // session re-use accepted -------------------------------------------
+ {
+ setupSecurityServices(true);
+ if (Configuration.DEBUG)
+ {
+ log.fine("Session re-use accepted...");
+ log.exiting(this.getClass().getName(), "sendPublicKey");
+ }
+ return null;
+ }
+ }
+
+ private byte[] receiveEvidence(byte[] input) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "receiveEvidence");
+ log.fine("S: " + Util.dumpString(input));
+ }
+ // Server send M2, sIV, sCB, sid, ttl
+ final InputBuffer frameIn = new InputBuffer(input);
+ try
+ {
+ M2 = frameIn.getOS();
+ if (Configuration.DEBUG)
+ log.fine("Got M2 (server evidence): " + Util.dumpString(M2));
+ sIV = frameIn.getOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sIV (server IV): " + Util.dumpString(sIV));
+ sid = frameIn.getEOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sid (session ID): " + new String(sid));
+ ttl = (int) frameIn.getScalar(4);
+ if (Configuration.DEBUG)
+ log.fine("Got ttl (session time-to-live): " + ttl + "sec.");
+ sCB = frameIn.getEOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB));
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("receiveEvidence()", x);
+ }
+
+ final byte[] expected;
+ try
+ {
+ expected = srp.generateM2(A, M1, K, U, authorizationID, o, sid, ttl,
+ cIV, sIV, sCB);
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("receiveEvidence()", x);
+ }
+ if (Configuration.DEBUG)
+ log.fine("Expected: " + Util.dumpString(expected));
+ if (! Arrays.equals(M2, expected))
+ throw new AuthenticationException("M2 mismatch");
+ setupSecurityServices(false);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "receiveEvidence");
+ return null;
+ }
+
+ private void getUsernameAndPassword() throws AuthenticationException
+ {
+ try
+ {
+ if ((! properties.containsKey(Registry.SASL_USERNAME))
+ && (! properties.containsKey(Registry.SASL_PASSWORD)))
+ {
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ handler.handle(new Callback[] { nameCB, pwdCB });
+ U = nameCB.getName();
+ password = new Password(pwdCB.getPassword());
+ }
+ else
+ {
+ if (properties.containsKey(Registry.SASL_USERNAME))
+ this.U = (String) properties.get(Registry.SASL_USERNAME);
+ else
+ {
+ final NameCallback nameCB;
+ final String defaultName = System.getProperty("user.name");
+ if (defaultName == null)
+ nameCB = new NameCallback("username: ");
+ else
+ nameCB = new NameCallback("username: ", defaultName);
+ this.handler.handle(new Callback[] { nameCB });
+ this.U = nameCB.getName();
+ }
+
+ if (properties.containsKey(Registry.SASL_PASSWORD))
+ {
+ Object pw = properties.get(Registry.SASL_PASSWORD);
+ if (pw instanceof char[])
+ password = new Password((char[]) pw);
+ else if (pw instanceof Password)
+ password = (Password) pw;
+ else if (pw instanceof String)
+ password = new Password(((String) pw).toCharArray());
+ else
+ throw new IllegalArgumentException(pw.getClass().getName()
+ + "is not a valid password class");
+ }
+ else
+ {
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
+ false);
+ this.handler.handle(new Callback[] { pwdCB });
+ password = new Password(pwdCB.getPassword());
+ }
+ }
+
+ if (U == null)
+ throw new AuthenticationException("null username supplied");
+ if (password == null)
+ throw new AuthenticationException("null password supplied");
+ }
+ catch (UnsupportedCallbackException x)
+ {
+ throw new AuthenticationException("getUsernameAndPassword()", x);
+ }
+ catch (IOException x)
+ {
+ throw new AuthenticationException("getUsernameAndPassword()", x);
+ }
+ }
+
+ // We go through the list of available services and for each available one
+ // we decide whether or not we want it enabled, based on properties passed
+ // to us by the client.
+ private String createO(final String aol) throws AuthenticationException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "createO", aol);
+ boolean replaydetectionAvailable = false;
+ boolean integrityAvailable = false;
+ boolean confidentialityAvailable = false;
+ String option, mandatory = SRPRegistry.DEFAULT_MANDATORY;
+ int i;
+
+ String mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME;
+ final StringTokenizer st = new StringTokenizer(aol, ",");
+ while (st.hasMoreTokens())
+ {
+ option = st.nextToken();
+ if (option.startsWith(SRPRegistry.OPTION_SRP_DIGEST + "="))
+ {
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("mda: <" + option + ">");
+ for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
+ if (SRPRegistry.SRP_ALGORITHMS[i].equals(option))
+ {
+ mdName = option;
+ break;
+ }
+ }
+ else if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
+ replaydetectionAvailable = true;
+ else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "="))
+ {
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("ialg: <" + option + ">");
+ for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
+ if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option))
+ {
+ chosenIntegrityAlgorithm = option;
+ integrityAvailable = true;
+ break;
+ }
+ }
+ else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "="))
+ {
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("calg: <" + option + ">");
+ for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
+ if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option))
+ {
+ chosenConfidentialityAlgorithm = option;
+ confidentialityAvailable = true;
+ break;
+ }
+ }
+ else if (option.startsWith(SRPRegistry.OPTION_MANDATORY + "="))
+ mandatory = option.substring(option.indexOf('=') + 1);
+ else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "="))
+ {
+ final String maxBufferSize = option.substring(option.indexOf('=') + 1);
+ try
+ {
+ rawSendSize = Integer.parseInt(maxBufferSize);
+ if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT
+ || rawSendSize < 1)
+ throw new AuthenticationException(
+ "Illegal value for 'maxbuffersize' option");
+ }
+ catch (NumberFormatException x)
+ {
+ throw new AuthenticationException(
+ SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x);
+ }
+ }
+ }
+ String s;
+ Boolean flag;
+ s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION);
+ flag = Boolean.valueOf(s);
+ replayDetection = replaydetectionAvailable && flag.booleanValue();
+ s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION);
+ flag = Boolean.valueOf(s);
+ boolean integrity = integrityAvailable && flag.booleanValue();
+ s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY);
+ flag = Boolean.valueOf(s);
+ boolean confidentiality = confidentialityAvailable && flag.booleanValue();
+ // make sure we do the right thing
+ if (SRPRegistry.OPTION_REPLAY_DETECTION.equals(mandatory))
+ {
+ replayDetection = true;
+ integrity = true;
+ }
+ else if (SRPRegistry.OPTION_INTEGRITY.equals(mandatory))
+ integrity = true;
+ else if (SRPRegistry.OPTION_CONFIDENTIALITY.equals(mandatory))
+ confidentiality = true;
+
+ if (replayDetection)
+ {
+ if (chosenIntegrityAlgorithm == null)
+ throw new AuthenticationException(
+ "Replay detection is required but no integrity protection "
+ + "algorithm was chosen");
+ }
+ if (integrity)
+ {
+ if (chosenIntegrityAlgorithm == null)
+ throw new AuthenticationException(
+ "Integrity protection is required but no algorithm was chosen");
+ }
+ if (confidentiality)
+ {
+ if (chosenConfidentialityAlgorithm == null)
+ throw new AuthenticationException(
+ "Confidentiality protection is required but no algorithm was chosen");
+ }
+ // 1. check if we'll be using confidentiality; if not set IV to 0-byte
+ if (chosenConfidentialityAlgorithm == null)
+ cIV = new byte[0];
+ else
+ {
+ // 2. get the block size of the cipher
+ final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm);
+ if (cipher == null)
+ throw new AuthenticationException("createO()",
+ new NoSuchAlgorithmException());
+ final int blockSize = cipher.defaultBlockSize();
+ // 3. generate random iv
+ cIV = new byte[blockSize];
+ getDefaultPRNG().nextBytes(cIV);
+ }
+ srp = SRP.instance(mdName);
+ // Now create the options list specifying which of the available options
+ // we have chosen.
+
+ // For now we just select the defaults. Later we need to add support for
+ // properties (perhaps in a file) where a user can specify the list of
+ // algorithms they would prefer to use.
+ final StringBuffer sb = new StringBuffer();
+ sb.append(SRPRegistry.OPTION_SRP_DIGEST)
+ .append("=").append(mdName).append(",");
+ if (replayDetection)
+ sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(",");
+ if (integrity)
+ sb.append(SRPRegistry.OPTION_INTEGRITY)
+ .append("=").append(chosenIntegrityAlgorithm).append(",");
+ if (confidentiality)
+ sb.append(SRPRegistry.OPTION_CONFIDENTIALITY)
+ .append("=").append(chosenConfidentialityAlgorithm).append(",");
+
+ final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE)
+ .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT)
+ .toString();
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "createO", result);
+ return result;
+ }
+
+ private void setupSecurityServices(final boolean sessionReUse)
+ throws SaslException
+ {
+ complete = true; // signal end of authentication phase
+ if (! sessionReUse)
+ {
+ outCounter = inCounter = 0;
+ // instantiate cipher if confidentiality protection filter is active
+ if (chosenConfidentialityAlgorithm != null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Activating confidentiality protection filter");
+ inCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
+ outCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
+ }
+ // instantiate hmacs if integrity protection filter is active
+ if (chosenIntegrityAlgorithm != null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Activating integrity protection filter");
+ inMac = IALG.getInstance(chosenIntegrityAlgorithm);
+ outMac = IALG.getInstance(chosenIntegrityAlgorithm);
+ }
+ }
+ else // same session new Keys
+ K = srp.generateKn(K, cn, sn);
+
+ final KDF kdf = KDF.getInstance(K);
+ // initialise in/out ciphers if confidentiality protection is used
+ if (inCipher != null)
+ {
+ inCipher.init(kdf, sIV, Direction.REVERSED);
+ outCipher.init(kdf, cIV, Direction.FORWARD);
+ }
+ // initialise in/out macs if integrity protection is used
+ if (inMac != null)
+ {
+ inMac.init(kdf);
+ outMac.init(kdf);
+ }
+ if (sid != null && sid.length != 0)
+ { // update the security context and save in map
+ if (Configuration.DEBUG)
+ log.fine("Updating security context for UID = " + uid);
+ ClientStore.instance().cacheSession(uid,
+ ttl,
+ new SecurityContext(srp.getAlgorithm(),
+ sid,
+ K,
+ cIV,
+ sIV,
+ replayDetection,
+ inCounter,
+ outCounter,
+ inMac, outMac,
+ inCipher,
+ outCipher));
+ }
+ }
+
+ private PRNG getDefaultPRNG()
+ {
+ if (prng == null)
+ prng = PRNG.getInstance();
+ return prng;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,165 @@
+/* SRPRegistry.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Registry;
+
+/**
+ * A list of key names designating the values exchanged between the server
+ * and client in an SRP communication authentication phase.
+ */
+public interface SRPRegistry
+{
+ /** Indices of (N, g) parameter values for SRP (.conf) password database. */
+ String N_2048_BITS = "1";
+ String N_1536_BITS = "2";
+ String N_1280_BITS = "3";
+ String N_1024_BITS = "4";
+ String N_768_BITS = "5";
+ String N_640_BITS = "6";
+ String N_512_BITS = "7";
+ /** Available hash algorithms for all SRP calculations. */
+ String[] SRP_ALGORITHMS = {
+ Registry.SHA160_HASH, // the default one
+ Registry.MD5_HASH,
+ Registry.RIPEMD128_HASH,
+ Registry.RIPEMD160_HASH,
+
+ Registry.SHA256_HASH,
+ Registry.SHA384_HASH,
+ Registry.SHA512_HASH };
+ /**
+ * The name of the default message digest algorithm to use when no name is
+ * explicitely given. In this implementation it is the <b>first</b> among
+ * those supported; i.e. the algorithm at index position #0: SHA with
+ * 160-bit output.
+ */
+ String SRP_DEFAULT_DIGEST_NAME = SRP_ALGORITHMS[0];
+ /**
+ * The property name of the message digest algorithm name to use in a given
+ * SRP incarnation.
+ */
+ String SRP_DIGEST_NAME = "srp.digest.name";
+ /** The public shared modulus: n. */
+ String SHARED_MODULUS = "srp.N";
+ /** The GF generator used: g. */
+ String FIELD_GENERATOR = "srp.g";
+ /** The list of server's available security options. */
+ String AVAILABLE_OPTIONS = "srp.L";
+ /** The client's chosen security options. */
+ String CHOSEN_OPTIONS = "srp.o";
+ /** The client's username. */
+ String USER_NAME = "srp.U";
+ /** The client's authorization ID. */
+ String USER_ROLE = "srp.I";
+ /** The user's salt. */
+ String USER_SALT = "srp.s";
+ /** The user's password verifier. */
+ String PASSWORD_VERIFIER = "srp.v";
+ /** The client's public ephemeral exponent: A. */
+ String CLIENT_PUBLIC_KEY = "srp.A";
+ /** The server's public ephemeral exponent: B. */
+ String SERVER_PUBLIC_KEY = "srp.B";
+ /** The client's evidence: M1. */
+ String CLIENT_EVIDENCE = "srp.M1";
+ /** The server's evidence: M2. */
+ String SERVER_EVIDENCE = "srp.M2";
+ /** Name of underlying hash algorithm for use with all SRP calculations. */
+ String SRP_HASH = "gnu.crypto.sasl.srp.hash";
+ /** Name of SRP mandatory service property. */
+ String SRP_MANDATORY = "gnu.crypto.sasl.srp.mandatory";
+ /** Name of SRP replay detection property. */
+ String SRP_REPLAY_DETECTION = "gnu.crypto.sasl.srp.replay.detection";
+ /** Name of SRP integrity protection property. */
+ String SRP_INTEGRITY_PROTECTION = "gnu.crypto.sasl.srp.integrity";
+ /** Name of SRP confidentiality protection property. */
+ String SRP_CONFIDENTIALITY = "gnu.crypto.sasl.srp.confidentiality";
+ /** Name of the main SRP password file pathname property. */
+ String PASSWORD_FILE = "gnu.crypto.sasl.srp.password.file";
+ /**
+ * Name of the SRP password database property --a reference to
+ * {@link PasswordFile} object.
+ */
+ String PASSWORD_DB = "gnu.crypto.sasl.srp.password.db";
+ /** Default fully qualified pathname of the SRP password file. */
+ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd";
+ /** Default value for replay detection security service. */
+ boolean DEFAULT_REPLAY_DETECTION = true;
+ /** Default value for integrity protection security service. */
+ boolean DEFAULT_INTEGRITY = true; // implied by the previous option
+ /** Default value for confidentiality protection security service. */
+ boolean DEFAULT_CONFIDENTIALITY = false;
+ // constants defining HMAC names
+ String HMAC_SHA1 = "hmac-sha1";
+ String HMAC_MD5 = "hmac-md5";
+ String HMAC_RIPEMD_160 = "hmac-ripemd-160";
+ /** Available HMAC algorithms for integrity protection. */
+ String[] INTEGRITY_ALGORITHMS = { HMAC_SHA1, HMAC_MD5, HMAC_RIPEMD_160 };
+ // constants defining Cipher names
+ String AES = "aes";
+ String BLOWFISH = "blowfish";
+ /** Available Cipher algorithms for confidentiality protection. */
+ String[] CONFIDENTIALITY_ALGORITHMS = { AES, BLOWFISH };
+ /** String for mandatory replay detection. */
+ String OPTION_MANDATORY = "mandatory";
+ /** String for mda: the SRP digest algorithm name. */
+ String OPTION_SRP_DIGEST = "mda";
+ /** String for mandatory replay detection. */
+ String OPTION_REPLAY_DETECTION = "replay_detection";
+ /** String for mandatory integrity protection. */
+ String OPTION_INTEGRITY = "integrity";
+ /** String for mandatory confidentiality protection. */
+ String OPTION_CONFIDENTIALITY = "confidentiality";
+ /** String for mandatory replay detection. */
+ String OPTION_MAX_BUFFER_SIZE = "maxbuffersize";
+ /** String for no mandatory security service. */
+ String MANDATORY_NONE = "none";
+ /** Default mandatory security service required. */
+ String DEFAULT_MANDATORY = OPTION_REPLAY_DETECTION;
+ /** Name of the UID field in the plain password file. */
+ String MD_NAME_FIELD = "srp.md.name";
+ /** Name of the GID field in the plain password file. */
+ String USER_VERIFIER_FIELD = "srp.user.verifier";
+ /** Name of the GECOS field in the plain password file. */
+ String SALT_FIELD = "srp.salt";
+ /** Name of the SHELL field in the plain password file. */
+ String CONFIG_NDX_FIELD = "srp.config.ndx";
+ /** Minimum bitlength of the SRP public modulus. */
+ int MINIMUM_MODULUS_BITLENGTH = 512;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,840 @@
+/* SRPServer.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.util.PRNG;
+import gnu.java.security.util.Util;
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.key.IKeyAgreementParty;
+import gnu.javax.crypto.key.IncomingMessage;
+import gnu.javax.crypto.key.KeyAgreementException;
+import gnu.javax.crypto.key.KeyAgreementFactory;
+import gnu.javax.crypto.key.OutgoingMessage;
+import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;
+import gnu.javax.crypto.sasl.IllegalMechanismStateException;
+import gnu.javax.crypto.sasl.InputBuffer;
+import gnu.javax.crypto.sasl.IntegrityException;
+import gnu.javax.crypto.sasl.OutputBuffer;
+import gnu.javax.crypto.sasl.ServerMechanism;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+import java.util.logging.Logger;
+
+import javax.security.sasl.AuthenticationException;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+/**
+ * The SASL-SRP server-side mechanism.
+ */
+public class SRPServer
+ extends ServerMechanism
+ implements SaslServer
+{
+ private static final Logger log = Logger.getLogger(SRPServer.class.getName());
+ private String U = null; // client's username
+ private BigInteger N, g, A, B;
+ private byte[] s; // salt
+ private byte[] cIV, sIV; // client+server IVs, when confidentiality is on
+ private byte[] cn, sn; // client's and server's nonce
+ private SRP srp; // SRP algorithm instance used by this server
+ private byte[] sid; // session ID when re-used
+ private int ttl = 360; // session time-to-live in seconds
+ private byte[] cCB; // peer's channel binding'
+ private String mandatory; // List of available options
+ private String L = null;
+ private String o;
+ private String chosenIntegrityAlgorithm;
+ private String chosenConfidentialityAlgorithm;
+ private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;
+ private byte[] K; // shared session key
+ private boolean replayDetection = true; // whether Replay Detection is on
+ private int inCounter = 0; // messages sequence numbers
+ private int outCounter = 0;
+ private IALG inMac, outMac; // if !null, use for integrity
+ private CALG inCipher, outCipher; // if !null, use for confidentiality
+ private IKeyAgreementParty serverHandler =
+ KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA);
+ /** Our default source of randomness. */
+ private PRNG prng = null;
+
+ public SRPServer()
+ {
+ super(Registry.SASL_SRP_MECHANISM);
+ }
+
+ protected void initMechanism() throws SaslException
+ {
+ // TODO:
+ // we must have a means to map a given username to a preferred
+ // SRP hash algorithm; otherwise we end up using _always_ SHA.
+ // for the time being get it from the mechanism properties map
+ // and apply it for all users.
+ final String mda = (String) properties.get(SRPRegistry.SRP_HASH);
+ srp = SRP.instance(mda == null ? SRPRegistry.SRP_DEFAULT_DIGEST_NAME : mda);
+ }
+
+ protected void resetMechanism() throws SaslException
+ {
+ s = null;
+ A = B = null;
+ K = null;
+ inMac = outMac = null;
+ inCipher = outCipher = null;
+ sid = null;
+ }
+
+ public byte[] evaluateResponse(final byte[] response) throws SaslException
+ {
+ switch (state)
+ {
+ case 0:
+ if (response == null)
+ return null;
+ state++;
+ return sendProtocolElements(response);
+ case 1:
+ if (! complete)
+ {
+ state++;
+ return sendEvidence(response);
+ }
+ // else fall through
+ default:
+ throw new IllegalMechanismStateException("evaluateResponse()");
+ }
+ }
+
+ protected byte[] engineUnwrap(final byte[] incoming, final int offset,
+ final int len) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineUnwrap");
+ if (inMac == null && inCipher == null)
+ throw new IllegalStateException("connection is not protected");
+ if (Configuration.DEBUG)
+ log.fine("Incoming buffer (before security): "
+ + Util.dumpString(incoming, offset, len));
+ // at this point one, or both, of confidentiality and integrity protection
+ // services are active.
+ final byte[] result;
+ try
+ {
+ if (inMac != null)
+ { // integrity bytes are at the end of the stream
+ final int macBytesCount = inMac.length();
+ final int payloadLength = len - macBytesCount;
+ final byte[] received_mac = new byte[macBytesCount];
+ System.arraycopy(incoming, offset + payloadLength, received_mac, 0,
+ macBytesCount);
+ if (Configuration.DEBUG)
+ log.fine("Got C (received MAC): " + Util.dumpString(received_mac));
+ inMac.update(incoming, offset, payloadLength);
+ if (replayDetection)
+ {
+ inCounter++;
+ if (Configuration.DEBUG)
+ log.fine("inCounter=" + String.valueOf(inCounter));
+ inMac.update(new byte[] {
+ (byte)(inCounter >>> 24),
+ (byte)(inCounter >>> 16),
+ (byte)(inCounter >>> 8),
+ (byte) inCounter });
+ }
+ final byte[] computed_mac = inMac.doFinal();
+ if (Configuration.DEBUG)
+ log.fine("Computed MAC: " + Util.dumpString(computed_mac));
+ if (! Arrays.equals(received_mac, computed_mac))
+ throw new IntegrityException("engineUnwrap()");
+ // deal with the payload, which can be either plain or encrypted
+ if (inCipher != null)
+ result = inCipher.doFinal(incoming, offset, payloadLength);
+ else
+ {
+ result = new byte[payloadLength];
+ System.arraycopy(incoming, offset, result, 0, result.length);
+ }
+ }
+ else // no integrity protection; just confidentiality
+ result = inCipher.doFinal(incoming, offset, len);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("engineUnwrap()", x);
+ }
+ if (Configuration.DEBUG)
+ {
+ log.fine("Incoming buffer (after security): " + Util.dumpString(result));
+ log.exiting(this.getClass().getName(), "engineUnwrap");
+ }
+ return result;
+ }
+
+ protected byte[] engineWrap(final byte[] outgoing, final int offset,
+ final int len) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineWrap");
+ if (outMac == null && outCipher == null)
+ throw new IllegalStateException("connection is not protected");
+ if (Configuration.DEBUG)
+ {
+ log.fine("Outgoing buffer (before security) (hex): "
+ + Util.dumpString(outgoing, offset, len));
+ log.fine("Outgoing buffer (before security) (str): \""
+ + new String(outgoing, offset, len) + "\"");
+ }
+ // at this point one, or both, of confidentiality and integrity protection
+ // services are active.
+ byte[] result;
+ try
+ {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ if (outCipher != null)
+ {
+ result = outCipher.doFinal(outgoing, offset, len);
+ if (Configuration.DEBUG)
+ log.fine("Encoding c (encrypted plaintext): "
+ + Util.dumpString(result));
+ out.write(result);
+ if (outMac != null)
+ {
+ outMac.update(result);
+ if (replayDetection)
+ {
+ outCounter++;
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] {
+ (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
+ }
+ final byte[] C = outMac.doFinal();
+ out.write(C);
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ // else ciphertext only; do nothing
+ }
+ else // no confidentiality; just integrity [+ replay detection]
+ {
+ if (Configuration.DEBUG)
+ log.fine("Encoding p (plaintext): "
+ + Util.dumpString(outgoing, offset, len));
+ out.write(outgoing, offset, len);
+ outMac.update(outgoing, offset, len);
+ if (replayDetection)
+ {
+ outCounter++;
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] {
+ (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
+ }
+ final byte[] C = outMac.doFinal();
+ out.write(C);
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ result = out.toByteArray();
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new SaslException("engineWrap()", x);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineWrap");
+ return result;
+ }
+
+ protected String getNegotiatedQOP()
+ {
+ if (inMac != null)
+ {
+ if (inCipher != null)
+ return Registry.QOP_AUTH_CONF;
+ return Registry.QOP_AUTH_INT;
+ }
+ return Registry.QOP_AUTH;
+ }
+
+ protected String getNegotiatedStrength()
+ {
+ if (inMac != null)
+ {
+ if (inCipher != null)
+ return Registry.STRENGTH_HIGH;
+ return Registry.STRENGTH_MEDIUM;
+ }
+ return Registry.STRENGTH_LOW;
+ }
+
+ protected String getNegotiatedRawSendSize()
+ {
+ return String.valueOf(rawSendSize);
+ }
+
+ protected String getReuse()
+ {
+ return Registry.REUSE_TRUE;
+ }
+
+ private byte[] sendProtocolElements(final byte[] input) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendProtocolElements");
+ log.fine("C: " + Util.dumpString(input));
+ }
+ // Client send U, I, sid, cn
+ final InputBuffer frameIn = new InputBuffer(input);
+ try
+ {
+ U = frameIn.getText(); // Extract username
+ if (Configuration.DEBUG)
+ log.fine("Got U (username): \"" + U + "\"");
+ authorizationID = frameIn.getText(); // Extract authorisation ID
+ if (Configuration.DEBUG)
+ log.fine("Got I (userid): \"" + authorizationID + "\"");
+ sid = frameIn.getEOS();
+ if (Configuration.DEBUG)
+ log.fine("Got sid (session ID): " + new String(sid));
+ cn = frameIn.getOS();
+ if (Configuration.DEBUG)
+ log.fine("Got cn (client nonce): " + Util.dumpString(cn));
+ cCB = frameIn.getEOS();
+ if (Configuration.DEBUG)
+ log.fine("Got cCB (client channel binding): " + Util.dumpString(cCB));
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendProtocolElements()", x);
+ }
+ // do/can we re-use?
+ if (ServerStore.instance().isAlive(sid))
+ {
+ final SecurityContext ctx = ServerStore.instance().restoreSession(sid);
+ srp = SRP.instance(ctx.getMdName());
+ K = ctx.getK();
+ cIV = ctx.getClientIV();
+ sIV = ctx.getServerIV();
+ replayDetection = ctx.hasReplayDetection();
+ inCounter = ctx.getInCounter();
+ outCounter = ctx.getOutCounter();
+ inMac = ctx.getInMac();
+ outMac = ctx.getOutMac();
+ inCipher = ctx.getInCipher();
+ outCipher = ctx.getOutCipher();
+ if (sn == null || sn.length != 16)
+ sn = new byte[16];
+ getDefaultPRNG().nextBytes(sn);
+ setupSecurityServices(false);
+ final OutputBuffer frameOut = new OutputBuffer();
+ try
+ {
+ frameOut.setScalar(1, 0xFF);
+ frameOut.setOS(sn);
+ frameOut.setEOS(channelBinding);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendProtocolElements()", x);
+ }
+ final byte[] result = frameOut.encode();
+ if (Configuration.DEBUG)
+ {
+ log.fine("Old session...");
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" sn = " + Util.dumpString(sn));
+ log.fine(" sCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendProtocolElements");
+ }
+ return result;
+ }
+ else
+ { // new session
+ authenticator.activate(properties);
+ // -------------------------------------------------------------------
+ final HashMap mapB = new HashMap();
+ mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm());
+ mapB.put(SRP6KeyAgreement.HOST_PASSWORD_DB, authenticator);
+ try
+ {
+ serverHandler.init(mapB);
+ OutgoingMessage out = new OutgoingMessage();
+ out.writeString(U);
+ IncomingMessage in = new IncomingMessage(out.toByteArray());
+ out = serverHandler.processMessage(in);
+ in = new IncomingMessage(out.toByteArray());
+ N = in.readMPI();
+ g = in.readMPI();
+ s = in.readMPI().toByteArray();
+ B = in.readMPI();
+ }
+ catch (KeyAgreementException x)
+ {
+ throw new SaslException("sendProtocolElements()", x);
+ }
+ // -------------------------------------------------------------------
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding N (modulus): " + Util.dump(N));
+ log.fine("Encoding g (generator): " + Util.dump(g));
+ log.fine("Encoding s (client's salt): " + Util.dumpString(s));
+ log.fine("Encoding B (server ephemeral public key): " + Util.dump(B));
+ }
+ // The server creates an options list (L), which consists of a
+ // comma-separated list of option strings that specify the security
+ // service options the server supports.
+ L = createL();
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding L (available options): \"" + L + "\"");
+ log.fine("Encoding sIV (server IV): " + Util.dumpString(sIV));
+ }
+ final OutputBuffer frameOut = new OutputBuffer();
+ try
+ {
+ frameOut.setScalar(1, 0x00);
+ frameOut.setMPI(N);
+ frameOut.setMPI(g);
+ frameOut.setOS(s);
+ frameOut.setMPI(B);
+ frameOut.setText(L);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendProtocolElements()", x);
+ }
+ final byte[] result = frameOut.encode();
+ if (Configuration.DEBUG)
+ {
+ log.fine("New session...");
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" N = 0x" + N.toString(16));
+ log.fine(" g = 0x" + g.toString(16));
+ log.fine(" s = " + Util.dumpString(s));
+ log.fine(" B = 0x" + B.toString(16));
+ log.fine(" L = " + L);
+ log.exiting(this.getClass().getName(), "sendProtocolElements");
+ }
+ return result;
+ }
+ }
+
+ private byte[] sendEvidence(final byte[] input) throws SaslException
+ {
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendEvidence");
+ log.fine("C: " + Util.dumpString(input));
+ }
+ // Client send A, M1, o, cIV
+ final InputBuffer frameIn = new InputBuffer(input);
+ final byte[] M1;
+ try
+ {
+ A = frameIn.getMPI(); // Extract client's ephemeral public key
+ if (Configuration.DEBUG)
+ log.fine("Got A (client ephemeral public key): " + Util.dump(A));
+ M1 = frameIn.getOS(); // Extract evidence
+ if (Configuration.DEBUG)
+ log.fine("Got M1 (client evidence): " + Util.dumpString(M1));
+ o = frameIn.getText(); // Extract client's options list
+ if (Configuration.DEBUG)
+ log.fine("Got o (client chosen options): \"" + o + "\"");
+ cIV = frameIn.getOS(); // Extract client's IV
+ if (Configuration.DEBUG)
+ log.fine("Got cIV (client IV): " + Util.dumpString(cIV));
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendEvidence()", x);
+ }
+ // Parse client's options and set security layer variables
+ parseO(o);
+ // ----------------------------------------------------------------------
+ try
+ {
+ final OutgoingMessage out = new OutgoingMessage();
+ out.writeMPI(A);
+ final IncomingMessage in = new IncomingMessage(out.toByteArray());
+ serverHandler.processMessage(in);
+ K = serverHandler.getSharedSecret();
+ }
+ catch (KeyAgreementException x)
+ {
+ throw new SaslException("sendEvidence()", x);
+ }
+ // ----------------------------------------------------------------------
+ if (Configuration.DEBUG)
+ log.fine("K: " + Util.dumpString(K));
+ final byte[] expected;
+ try
+ {
+ expected = srp.generateM1(N, g, U, s, A, B, K, authorizationID, L, cn,
+ cCB);
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("sendEvidence()", x);
+ }
+ // Verify client evidence
+ if (! Arrays.equals(M1, expected))
+ throw new AuthenticationException("M1 mismatch");
+ setupSecurityServices(true);
+ final byte[] M2;
+ try
+ {
+ M2 = srp.generateM2(A, M1, K, U, authorizationID, o, sid, ttl, cIV,
+ sIV, channelBinding);
+ }
+ catch (UnsupportedEncodingException x)
+ {
+ throw new AuthenticationException("sendEvidence()", x);
+ }
+ final OutputBuffer frameOut = new OutputBuffer();
+ try
+ {
+ frameOut.setOS(M2);
+ frameOut.setOS(sIV);
+ frameOut.setEOS(sid);
+ frameOut.setScalar(4, ttl);
+ frameOut.setEOS(channelBinding);
+ }
+ catch (IOException x)
+ {
+ if (x instanceof SaslException)
+ throw (SaslException) x;
+ throw new AuthenticationException("sendEvidence()", x);
+ }
+ final byte[] result = frameOut.encode();
+ if (Configuration.DEBUG)
+ {
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" M2 = " + Util.dumpString(M2));
+ log.fine(" sIV = " + Util.dumpString(sIV));
+ log.fine(" sid = " + new String(sid));
+ log.fine(" ttl = " + ttl);
+ log.fine(" sCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendEvidence");
+ }
+ return result;
+ }
+
+ private String createL()
+ {
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "createL()");
+ String s = (String) properties.get(SRPRegistry.SRP_MANDATORY);
+ if (s == null)
+ s = SRPRegistry.DEFAULT_MANDATORY;
+
+ if (! SRPRegistry.MANDATORY_NONE.equals(s)
+ && ! SRPRegistry.OPTION_REPLAY_DETECTION.equals(s)
+ && ! SRPRegistry.OPTION_INTEGRITY.equals(s)
+ && ! SRPRegistry.OPTION_CONFIDENTIALITY.equals(s))
+ {
+ if (Configuration.DEBUG)
+ log.fine("Unrecognised mandatory option (" + s + "). Using default...");
+ s = SRPRegistry.DEFAULT_MANDATORY;
+ }
+ mandatory = s;
+ s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY);
+ final boolean confidentiality = (s == null ? SRPRegistry.DEFAULT_CONFIDENTIALITY
+ : Boolean.valueOf(s).booleanValue());
+ s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION);
+ boolean integrity = (s == null ? SRPRegistry.DEFAULT_INTEGRITY
+ : Boolean.valueOf(s).booleanValue());
+ s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION);
+ final boolean replayDetection = (s == null ? SRPRegistry.DEFAULT_REPLAY_DETECTION
+ : Boolean.valueOf(s).booleanValue());
+ final StringBuffer sb = new StringBuffer();
+ sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=")
+ .append(srp.getAlgorithm()).append(",");
+
+ if (! SRPRegistry.MANDATORY_NONE.equals(mandatory))
+ sb.append(SRPRegistry.OPTION_MANDATORY)
+ .append("=").append(mandatory).append(",");
+
+ if (replayDetection)
+ {
+ sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(",");
+ // if replay detection is on then force integrity protection
+ integrity = true;
+ }
+ int i;
+ if (integrity)
+ {
+ for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
+ sb.append(SRPRegistry.OPTION_INTEGRITY).append("=")
+ .append(SRPRegistry.INTEGRITY_ALGORITHMS[i]).append(",");
+ }
+ if (confidentiality)
+ {
+ IBlockCipher cipher;
+ for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
+ {
+ cipher = CipherFactory.getInstance(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]);
+ if (cipher != null)
+ sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=")
+ .append(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]).append(",");
+ }
+ }
+ final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE)
+ .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT)
+ .toString();
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "createL");
+ return result;
+ }
+
+ // Parse client's options and set security layer variables
+ private void parseO(final String o) throws AuthenticationException
+ {
+ this.replayDetection = false;
+ boolean integrity = false;
+ boolean confidentiality = false;
+ String option;
+ int i;
+
+ final StringTokenizer st = new StringTokenizer(o.toLowerCase(), ",");
+ while (st.hasMoreTokens())
+ {
+ option = st.nextToken();
+ if (Configuration.DEBUG)
+ log.fine("option: <" + option + ">");
+ if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
+ replayDetection = true;
+ else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "="))
+ {
+ if (integrity)
+ throw new AuthenticationException(
+ "Only one integrity algorithm may be chosen");
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("algorithm: <" + option + ">");
+ for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
+ {
+ if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option))
+ {
+ chosenIntegrityAlgorithm = option;
+ integrity = true;
+ break;
+ }
+ }
+ if (! integrity)
+ throw new AuthenticationException("Unknown integrity algorithm: "
+ + option);
+ }
+ else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "="))
+ {
+ if (confidentiality)
+ throw new AuthenticationException(
+ "Only one confidentiality algorithm may be chosen");
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("algorithm: <" + option + ">");
+ for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
+ {
+ if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option))
+ {
+ chosenConfidentialityAlgorithm = option;
+ confidentiality = true;
+ break;
+ }
+ }
+ if (! confidentiality)
+ throw new AuthenticationException("Unknown confidentiality algorithm: "
+ + option);
+ }
+ else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "="))
+ {
+ final String maxBufferSize = option.substring(option.indexOf('=') + 1);
+ try
+ {
+ rawSendSize = Integer.parseInt(maxBufferSize);
+ if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT
+ || rawSendSize < 1)
+ throw new AuthenticationException(
+ "Illegal value for 'maxbuffersize' option");
+ }
+ catch (NumberFormatException x)
+ {
+ throw new AuthenticationException(
+ SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x);
+ }
+ }
+ }
+ // check if client did the right thing
+ if (replayDetection)
+ {
+ if (! integrity)
+ throw new AuthenticationException(
+ "Missing integrity protection algorithm but replay detection is chosen");
+ }
+ if (mandatory.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
+ {
+ if (! replayDetection)
+ throw new AuthenticationException(
+ "Replay detection is mandatory but was not chosen");
+ }
+ if (mandatory.equals(SRPRegistry.OPTION_INTEGRITY))
+ {
+ if (! integrity)
+ throw new AuthenticationException(
+ "Integrity protection is mandatory but was not chosen");
+ }
+ if (mandatory.equals(SRPRegistry.OPTION_CONFIDENTIALITY))
+ {
+ if (! confidentiality)
+ throw new AuthenticationException(
+ "Confidentiality is mandatory but was not chosen");
+ }
+ int blockSize = 0;
+ if (chosenConfidentialityAlgorithm != null)
+ {
+ final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm);
+ if (cipher != null)
+ blockSize = cipher.defaultBlockSize();
+ else // should not happen
+ throw new AuthenticationException("Confidentiality algorithm ("
+ + chosenConfidentialityAlgorithm
+ + ") not available");
+ }
+ sIV = new byte[blockSize];
+ if (blockSize > 0)
+ getDefaultPRNG().nextBytes(sIV);
+ }
+
+ private void setupSecurityServices(final boolean newSession)
+ throws SaslException
+ {
+ complete = true; // signal end of authentication phase
+ if (newSession)
+ {
+ outCounter = inCounter = 0;
+ // instantiate cipher if confidentiality protection filter is active
+ if (chosenConfidentialityAlgorithm != null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Activating confidentiality protection filter");
+ inCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
+ outCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
+ }
+ // instantiate hmacs if integrity protection filter is active
+ if (chosenIntegrityAlgorithm != null)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Activating integrity protection filter");
+ inMac = IALG.getInstance(chosenIntegrityAlgorithm);
+ outMac = IALG.getInstance(chosenIntegrityAlgorithm);
+ }
+ // generate a new sid if at least integrity is used
+ sid = (inMac != null ? ServerStore.getNewSessionID() : new byte[0]);
+ }
+ else // same session new keys
+ K = srp.generateKn(K, cn, sn);
+
+ final KDF kdf = KDF.getInstance(K);
+ // initialise in/out ciphers if confidentaility protection is used
+ if (inCipher != null)
+ {
+ outCipher.init(kdf, sIV, Direction.FORWARD);
+ inCipher.init(kdf, cIV, Direction.REVERSED);
+ }
+ // initialise in/out macs if integrity protection is used
+ if (inMac != null)
+ {
+ outMac.init(kdf);
+ inMac.init(kdf);
+ }
+ if (sid != null && sid.length != 0)
+ { // update the security context and save in map
+ if (Configuration.DEBUG)
+ log.fine("Updating security context for sid = " + new String(sid));
+ ServerStore.instance().cacheSession(ttl,
+ new SecurityContext(srp.getAlgorithm(),
+ sid,
+ K,
+ cIV,
+ sIV,
+ replayDetection,
+ inCounter,
+ outCounter,
+ inMac, outMac,
+ inCipher,
+ outCipher));
+ }
+ }
+
+ private PRNG getDefaultPRNG()
+ {
+ if (prng == null)
+ prng = PRNG.getInstance();
+ return prng;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,140 @@
+/* SecurityContext.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+/**
+ * A package-private placeholder for an SRP security context.
+ */
+class SecurityContext
+{
+ private String mdName;
+ private byte[] sid;
+ private byte[] K;
+ private byte[] cIV;
+ private byte[] sIV;
+ private boolean replayDetection;
+ private int inCounter;
+ private int outCounter;
+ private IALG inMac;
+ private IALG outMac;
+ private CALG inCipher;
+ private CALG outCipher;
+
+ SecurityContext(final String mdName, final byte[] sid, final byte[] K,
+ final byte[] cIV, final byte[] sIV,
+ final boolean replayDetection, final int inCounter,
+ final int outCounter, final IALG inMac, final IALG outMac,
+ final CALG inCipher, final CALG outCipher)
+ {
+ super();
+
+ this.mdName = mdName;
+ this.sid = sid;
+ this.K = K;
+ this.cIV = cIV;
+ this.sIV = sIV;
+ this.replayDetection = replayDetection;
+ this.inCounter = inCounter;
+ this.outCounter = outCounter;
+ this.inMac = inMac;
+ this.outMac = outMac;
+ this.inCipher = inCipher;
+ this.outCipher = outCipher;
+ }
+
+ String getMdName()
+ {
+ return mdName;
+ }
+
+ byte[] getSID()
+ {
+ return sid;
+ }
+
+ byte[] getK()
+ {
+ return K;
+ }
+
+ byte[] getClientIV()
+ {
+ return cIV;
+ }
+
+ byte[] getServerIV()
+ {
+ return sIV;
+ }
+
+ boolean hasReplayDetection()
+ {
+ return replayDetection;
+ }
+
+ int getInCounter()
+ {
+ return inCounter;
+ }
+
+ int getOutCounter()
+ {
+ return outCounter;
+ }
+
+ IALG getInMac()
+ {
+ return inMac;
+ }
+
+ IALG getOutMac()
+ {
+ return outMac;
+ }
+
+ CALG getInCipher()
+ {
+ return inCipher;
+ }
+
+ CALG getOutCipher()
+ {
+ return outCipher;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,175 @@
+/* ServerStore.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+import java.util.HashMap;
+
+/**
+ * The server-side implementation of the SRP security context store.
+ */
+public class ServerStore
+{
+ /** The underlying singleton. */
+ private static ServerStore singleton = null;
+ /** The map of sid --> Security Context record. */
+ private static final HashMap sid2ssc = new HashMap();
+ /** The map of sid --> Session timing record. */
+ private static final HashMap sid2ttl = new HashMap();
+ /** A synchronisation lock. */
+ private static final Object lock = new Object();
+ /** A counter to generate legible SIDs. */
+ private static int counter = 0;
+
+ /** Private constructor to enforce Singleton pattern. */
+ private ServerStore()
+ {
+ super();
+
+ // TODO: add a cleaning timer thread
+ }
+
+ /**
+ * Returns the classloader Singleton.
+ *
+ * @return the classloader Singleton instance.
+ */
+ static synchronized final ServerStore instance()
+ {
+ if (singleton == null)
+ singleton = new ServerStore();
+ return singleton;
+ }
+
+ /**
+ * Returns a legible new session identifier.
+ *
+ * @return a new session identifier.
+ */
+ static synchronized final byte[] getNewSessionID()
+ {
+ final String sid = String.valueOf(++counter);
+ return new StringBuffer("SID-")
+ .append("0000000000".substring(0, 10 - sid.length())).append(sid)
+ .toString().getBytes();
+ }
+
+ /**
+ * Returns a boolean flag indicating if the designated session is still alive
+ * or not.
+ *
+ * @param sid the identifier of the session to check.
+ * @return <code>true</code> if the designated session is still alive.
+ * <code>false</code> otherwise.
+ */
+ boolean isAlive(final byte[] sid)
+ {
+ boolean result = false;
+ if (sid != null && sid.length != 0)
+ {
+ synchronized (lock)
+ {
+ final String key = new String(sid);
+ final StoreEntry ctx = (StoreEntry) sid2ttl.get(key);
+ if (ctx != null)
+ {
+ result = ctx.isAlive();
+ if (! result) // invalidate it en-passant
+ {
+ sid2ssc.remove(key);
+ sid2ttl.remove(key);
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Records a mapping between a session identifier and the Security Context of
+ * the designated SRP server mechanism instance.
+ *
+ * @param ttl the session's Time-To-Live indicator (in seconds).
+ * @param ctx the server's security context.
+ */
+ void cacheSession(final int ttl, final SecurityContext ctx)
+ {
+ synchronized (lock)
+ {
+ final String key = new String(ctx.getSID());
+ sid2ssc.put(key, ctx);
+ sid2ttl.put(key, new StoreEntry(ttl));
+ }
+ }
+
+ /**
+ * Updates the mapping between the designated session identifier and the
+ * designated server's SASL Security Context. In the process, computes and
+ * return the underlying mechanism server's evidence that shall be returned to
+ * the client in a session re-use exchange.
+ *
+ * @param sid the identifier of the session to restore.
+ * @return an SRP server's security context.
+ */
+ SecurityContext restoreSession(final byte[] sid)
+ {
+ final String key = new String(sid);
+ final SecurityContext result;
+ synchronized (lock)
+ {
+ result = (SecurityContext) sid2ssc.remove(key);
+ sid2ttl.remove(key);
+ }
+ return result;
+ }
+
+ /**
+ * Removes all information related to the designated session ID.
+ *
+ * @param sid the identifier of the seesion to invalidate.
+ */
+ void invalidateSession(final byte[] sid)
+ {
+ final String key = new String(sid);
+ synchronized (lock)
+ {
+ sid2ssc.remove(key);
+ sid2ttl.remove(key);
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,75 @@
+/* StoreEntry.java --
+ Copyright (C) 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.javax.crypto.sasl.srp;
+
+/**
+ * A simple timing-related object for use by SRP re-use code.
+ */
+class StoreEntry
+{
+ private boolean perenial;
+ private long timeToDie;
+
+ StoreEntry(int ttl)
+ {
+ super();
+
+ if (ttl == 0)
+ {
+ perenial = true;
+ timeToDie = 0L;
+ }
+ else
+ {
+ perenial = false;
+ timeToDie = System.currentTimeMillis() + (ttl & 0xFFFFFFFFL) * 1000L;
+ }
+ }
+
+ /**
+ * Returns <code>true</code> if the Time-To_live period has not elapsed.
+ *
+ * @return <code>true</code> if the Time-To-Live period (in seconds) has not
+ * elapsed yet; <code>false</code> otherwise.
+ */
+ boolean isAlive()
+ {
+ return (perenial ? true : (System.currentTimeMillis() < timeToDie));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/IIOInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/IIOInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/IIOInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/IIOInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,102 @@
+/* GIFStream.java --
+ 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.javax.imageio;
+
+import java.io.InputStream;
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+
+/**
+ * Implements InputStream on an ImageInputStream
+ * The purpose of this is to avoid IIO dependencies in the various decoders.
+ * (which only use read() anyway).
+ */
+public class IIOInputStream extends InputStream
+{
+ private ImageInputStream is;
+
+ public IIOInputStream( ImageInputStream is )
+ {
+ this.is = is;
+ }
+
+ public int available()
+ {
+ return 0;
+ }
+
+ public void close() throws IOException
+ {
+ is.close();
+ }
+
+ public void mark(int readlimit)
+ {
+ is.mark();
+ }
+
+ public boolean markSupported()
+ {
+ return true;
+ }
+
+ public int read() throws IOException
+ {
+ return is.read();
+ }
+
+ public int read(byte[] b) throws IOException
+ {
+ return is.read(b);
+ }
+
+ public int read(byte[] b, int offset, int length) throws IOException
+ {
+ return is.read(b, offset, length);
+ }
+
+ public void reset() throws IOException
+ {
+ is.reset();
+ }
+
+ public long skip(long n) throws IOException
+ {
+ return is.skipBytes(n);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPDecoder.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPDecoder.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPDecoder.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPDecoder.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,168 @@
+/* BMPDecoder.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.awt.image.IndexColorModel;
+import java.awt.image.BufferedImage;
+
+public abstract class BMPDecoder {
+
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ public BMPDecoder(BMPFileHeader fh, BMPInfoHeader ih){
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * Determines the coding type of the bitmap and returns the corresponding
+ * decoder.
+ */
+ public static BMPDecoder getDecoder(BMPFileHeader fh, BMPInfoHeader ih){
+ switch(ih.getCompression()){
+ case BMPInfoHeader.BI_RGB: // uncompressed RGB
+ switch(ih.getBitCount()){
+ case 32:
+ return new DecodeBF32(fh, ih, true);
+
+ case 24:
+ return new DecodeRGB24(fh, ih);
+
+ case 16:
+ return new DecodeBF16(fh, ih, true);
+
+ case 8:
+ return new DecodeRGB8(fh, ih);
+
+ case 4:
+ return new DecodeRGB4(fh, ih);
+
+ case 1:
+ return new DecodeRGB1(fh, ih);
+
+ default:
+ return null;
+ }
+
+ case BMPInfoHeader.BI_RLE8:
+ return new DecodeRLE8(fh, ih);
+
+ case BMPInfoHeader.BI_RLE4:
+ return new DecodeRLE4(fh, ih);
+
+ case BMPInfoHeader.BI_BITFIELDS:
+ switch(ih.getBitCount()){
+ case 16:
+ return new DecodeBF16(fh, ih, false);
+
+ case 32:
+ return new DecodeBF32(fh, ih, false);
+
+ default:
+ return null;
+ }
+
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * The image decoder.
+ */
+ public abstract BufferedImage decode(ImageInputStream in)
+ throws IOException, BMPException;
+
+ /**
+ * Reads r,g,b bit masks from an inputstream
+ */
+ protected int[] readBitMasks(ImageInputStream in) throws IOException {
+ int[] bitmasks = new int[3];
+ byte[] temp = new byte[12];
+ if(in.read(temp) != 12)
+ throw new IOException("Couldn't read bit masks.");
+ offset += 12;
+
+ ByteBuffer buf = ByteBuffer.wrap(temp);
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ bitmasks[0] = buf.getInt();
+ bitmasks[1] = buf.getInt();
+ bitmasks[2] = buf.getInt();
+ return bitmasks;
+ }
+
+ /**
+ * Reads an N-color palette from an inputstream in RGBQUAD format and
+ * returns an equivalent ColorModel object
+ */
+ protected IndexColorModel readPalette(ImageInputStream in) throws IOException {
+ int N = infoHeader.getNumberOfPaletteEntries();
+ byte[] r = new byte[N];
+ byte[] g = new byte[N];
+ byte[] b = new byte[N];
+ for(int i=0;i<N;i++){
+ byte[] RGBquad = new byte[4];
+ if(in.read(RGBquad) != 4)
+ throw new IOException("Error reading palette information.");
+ // RGBQUAD structure is b,g,r,0
+ r[i] = RGBquad[2];
+ g[i] = RGBquad[1];
+ b[i] = RGBquad[0];
+ }
+
+ offset += 4*N;
+ return new IndexColorModel(8, N, r, g, b);
+ }
+
+ /**
+ * Read bytes to the start of the image data
+ */
+ protected void skipToImage(ImageInputStream in) throws IOException {
+ byte[] d = new byte[1];
+ long n = fileHeader.getOffset() - offset;
+ for(int i=0;i<n;i++)
+ in.read(d);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPEncoder.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPEncoder.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPEncoder.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPEncoder.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,119 @@
+/* BMPEncoder.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public abstract class BMPEncoder
+{
+
+ /**
+ * Constructs a new BMPEncoder.
+ */
+ public BMPEncoder()
+ {
+ // Nothing to do here.
+ }
+
+ /**
+ * Determines the coding type of the bitmap and returns the corresponding
+ * encoder.
+ *
+ * @param fh - the file header
+ * @param ih - the info header
+ * @return the appropriate encoder
+ */
+ public static BMPEncoder getEncoder(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ switch (ih.getCompression())
+ {
+ case BMPInfoHeader.BI_RGB:
+ switch (ih.getBitCount())
+ {
+ case 32:
+ return new EncodeRGB32(fh, ih);
+
+ case 24:
+ return new EncodeRGB24(fh, ih);
+
+ case 16:
+ return new EncodeRGB16(fh, ih);
+
+ case 8:
+ return new EncodeRGB8(fh, ih);
+
+ case 4:
+ return new EncodeRGB4(fh, ih);
+
+ case 1:
+ return new EncodeRGB1(fh, ih);
+
+ default:
+ return null;
+ }
+ case BMPInfoHeader.BI_RLE4:
+ return new EncodeRLE4(fh, ih);
+
+ case BMPInfoHeader.BI_RLE8:
+ return new EncodeRLE8(fh, ih);
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data, metadata and
+ * thumbnails to be written
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public abstract void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param)
+ throws IOException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,47 @@
+/* BMPException.java --
+ 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.javax.imageio.bmp;
+
+import javax.imageio.IIOException;
+
+public class BMPException extends IIOException {
+
+ public BMPException(String message){
+ super(message);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPFileHeader.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPFileHeader.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPFileHeader.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPFileHeader.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,153 @@
+/* BMPFileHeader.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.RenderedImage;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import javax.imageio.IIOImage;
+import javax.imageio.stream.ImageInputStream;
+import javax.imageio.stream.ImageOutputStream;
+
+public class BMPFileHeader {
+ /** Header signature, always 'BM' */
+ private final static short bfType = 0x424d;
+
+ /** Bitmap file size, in bytes. */
+ protected long bfSize;
+
+ /** Offset from the beginning of the file to the bitmap data */
+ protected long bfOffBits;
+
+ /** BITMAPFILEHEADER is 14 bytes */
+ public static final int SIZE = 14;
+ private static final int BITMAPINFOHEADER_SIZE = 40;
+
+ /**
+ * Creates the header from an input stream, which is not closed.
+ *
+ * @throws IOException if an I/O error occured.
+ * @throws BMPException if the header was invalid
+ */
+ public BMPFileHeader(ImageInputStream in) throws IOException, BMPException {
+ byte[] data = new byte[SIZE];
+
+ if (in.read(data) != SIZE)
+ throw new IOException("Couldn't read header.");
+ ByteBuffer buf = ByteBuffer.wrap(data);
+
+ if(buf.getShort(0) != bfType)
+ throw new BMPException("Not a BMP file.");
+
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+
+ // get size (keep unsigned)
+ bfSize = ((long)buf.getInt(2) & (0xFFFFFFFF));
+
+ // Two reserved shorts are here, and should be zero,
+ // perhaps they should be tested to be zero, but I don't
+ // feel this strictness is necessary.
+
+ bfOffBits = ((long)buf.getInt(10) & (0xFFFFFFFF));
+ }
+
+ /**
+ * Creates the header from an output stream, which is not closed.
+ *
+ * @param out - the image output stream
+ * @param im - the image
+ * @throws IOException if an I/O error occured.
+ */
+ public BMPFileHeader(ImageOutputStream out, IIOImage im) throws IOException
+ {
+ RenderedImage img = im.getRenderedImage();
+ int w = img.getWidth();
+ int h = img.getHeight();
+
+ bfOffBits = SIZE + BITMAPINFOHEADER_SIZE;
+ bfSize = ((w * h) * 3) + ((4 - ((w * 3) % 4)) * h) + bfOffBits;
+
+ write(out);
+ }
+
+ /**
+ * Writes the header to an output stream, which is not closed or flushed.
+ *
+ * @throws IOException if an I/O error occured.
+ */
+ public void write(ImageOutputStream out) throws IOException {
+ ByteBuffer buf = ByteBuffer.allocate(SIZE);
+ buf.putShort(0, bfType); // ID
+ buf.putInt(2, (int)(bfSize & (0xFFFFFFFF))); // size
+ buf.putInt(6, 0); // 4 reserved bytes set to zero
+ buf.putInt(7, (int)(bfOffBits & (0xFFFFFFFF))); // size
+ out.write(buf.array());
+ }
+
+ /**
+ * Sets the file size
+ */
+ public void setSize(long size){
+ bfSize = size;
+ }
+
+ /**
+ * Sets the bitmap offset within the file
+ */
+ public void setOffset(long offset){
+ bfOffBits = offset;
+ }
+
+ /**
+ * Gets the file size
+ */
+ public long getSize(){
+ return bfSize;
+ }
+
+ /**
+ * Gets the bitmap offset within the file
+ */
+ public long getOffset(){
+ return bfOffBits;
+ }
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReader.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReader.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReader.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReader.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,151 @@
+/* BMPImageReader.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.*;
+import javax.imageio.spi.*;
+import javax.imageio.metadata.*;
+import javax.imageio.stream.ImageInputStream;
+import java.util.Iterator;
+import java.awt.image.BufferedImage;
+
+public class BMPImageReader extends ImageReader {
+ private BMPInfoHeader infoHeader;
+ private BMPFileHeader fileHeader;
+ private BMPDecoder decoder;
+
+ protected BMPImageReader(ImageReaderSpi originatingProvider){
+ super(originatingProvider);
+ infoHeader = null;
+ fileHeader = null;
+ decoder = null;
+ }
+
+ private void validateIndex(int imageIndex)
+ throws IndexOutOfBoundsException {
+ if (imageIndex != 0)
+ throw new IndexOutOfBoundsException("Invalid image index.");
+ }
+
+ public void setInput(Object input) {
+ super.setInput(input);
+ }
+
+ public void setInput(Object input,
+ boolean seekForwardOnly,
+ boolean ignoreMetadata) {
+ super.setInput(input, seekForwardOnly, ignoreMetadata);
+ }
+
+ public void setInput(Object input, boolean isStreamable) {
+ super.setInput(input, isStreamable);
+
+ if (!(input instanceof ImageInputStream))
+ throw new IllegalArgumentException("Input not an ImageInputStream.");
+ }
+
+ private void checkStream() throws IOException {
+ if (!(input instanceof ImageInputStream))
+ throw new IllegalStateException("Input not an ImageInputStream.");
+ if(input == null)
+ throw new IllegalStateException("No input stream.");
+
+ }
+
+ private void readHeaders() throws IOException, IIOException {
+ if(fileHeader != null)
+ return;
+
+ checkStream();
+
+ fileHeader = new BMPFileHeader((ImageInputStream)input);
+ infoHeader = new BMPInfoHeader((ImageInputStream)input);
+ decoder = BMPDecoder.getDecoder(fileHeader, infoHeader);
+ }
+
+ public int getWidth(int imageIndex) throws IOException {
+ validateIndex(imageIndex);
+ readHeaders();
+ return infoHeader.getWidth();
+ }
+
+ public int getHeight(int imageIndex) throws IOException {
+ validateIndex(imageIndex);
+ readHeaders();
+ return infoHeader.getHeight();
+ }
+
+ public Iterator getImageTypes(int imageIndex){
+ validateIndex(imageIndex);
+ return null;
+ }
+
+ /**
+ * Returns the number of images. BMP files can only contain a single one.
+ */
+ public int getNumImages(boolean allowSearch){
+ return 1;
+ }
+
+
+ // FIXME: Support metadata
+ public IIOMetadata getImageMetadata(int imageIndex){
+ validateIndex(imageIndex);
+ return null;
+ }
+
+ // FIXME: Support metadata
+ public IIOMetadata getStreamMetadata(){
+ return null;
+ }
+
+ /**
+ * Reads the image indexed by imageIndex and returns it as
+ * a complete BufferedImage, using a supplied ImageReadParam.
+ */
+ public BufferedImage read(int imageIndex, ImageReadParam param)
+ throws IOException, IIOException {
+ validateIndex(imageIndex);
+ readHeaders();
+ return decoder.decode((ImageInputStream)input);
+ }
+}
+
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReaderSpi.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReaderSpi.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReaderSpi.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageReaderSpi.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,116 @@
+/* BMPImageReaderSpi.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import java.util.Locale;
+import javax.imageio.ImageReader;
+import javax.imageio.spi.ImageReaderSpi;
+import javax.imageio.stream.ImageInputStream;
+
+public class BMPImageReaderSpi extends ImageReaderSpi {
+
+ static final String vendorName = "GNU";
+ static final String version = "0.1";
+ static final String readerClassName =
+ "gnu.javax.imageio.bmp.BMPImageReader";
+ static final String[] names = { "Microsoft Windows BMP" };
+ static final String[] suffixes = { ".bmp", ".bm" };
+ static final String[] MIMETypes = {
+ "image/bmp",
+ "image/x-windows-bmp"};
+ static final String[] writerSpiNames =
+ { "gnu.javax.imageio.bmp.BMPImageWriterSpi" };
+
+ static final boolean supportsStandardStreamMetadataFormat = false;
+ static final String nativeStreamMetadataFormatName = null;
+ static final String nativeStreamMetadataFormatClassName = null;
+ static final String[] extraStreamMetadataFormatNames = null;
+ static final String[] extraStreamMetadataFormatClassNames = null;
+ static final boolean supportsStandardImageMetadataFormat = false;
+ static final String nativeImageMetadataFormatName = null;
+ static final String nativeImageMetadataFormatClassName = null;
+ static final String[] extraImageMetadataFormatNames = null;
+ static final String[] extraImageMetadataFormatClassNames = null;
+
+ public BMPImageReaderSpi() {
+ super(vendorName, version,
+ names, suffixes, MIMETypes,
+ readerClassName,
+ STANDARD_INPUT_TYPE, // Accept ImageInputStreams
+ writerSpiNames,
+ supportsStandardStreamMetadataFormat,
+ nativeStreamMetadataFormatName,
+ nativeStreamMetadataFormatClassName,
+ extraStreamMetadataFormatNames,
+ extraStreamMetadataFormatClassNames,
+ supportsStandardImageMetadataFormat,
+ nativeImageMetadataFormatName,
+ nativeImageMetadataFormatClassName,
+ extraImageMetadataFormatNames,
+ extraImageMetadataFormatClassNames);
+ }
+
+ public String getDescription(Locale locale) {
+ return "Microsoft BMP v3";
+ }
+
+ public boolean canDecodeInput(Object input)
+ throws IOException {
+ if (!(input instanceof ImageInputStream))
+ return false;
+
+ ImageInputStream in = (ImageInputStream)input;
+ boolean retval;
+
+ in.mark();
+ try {
+ new BMPFileHeader(in);
+ retval = true;
+ } catch(BMPException e){
+ retval = false;
+ }
+ in.reset();
+
+ return retval;
+ }
+
+ public ImageReader createReaderInstance(Object extension) {
+ return new BMPImageReader(this);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriter.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriter.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriter.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriter.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,196 @@
+/* BMPImageWriter.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.spi.ImageWriterSpi;
+import javax.imageio.stream.ImageOutputStream;
+
+public class BMPImageWriter
+ extends ImageWriter
+{
+ protected BMPEncoder encoder;
+ protected BMPFileHeader fileHeader;
+ protected BMPInfoHeader infoHeader;
+
+ /**
+ * Construct an bmp image writer.
+ *
+ * @param originatingProvider - the provider that is constructing this image
+ * writer, or null
+ */
+ protected BMPImageWriter(ImageWriterSpi originatingProvider)
+ {
+ super(originatingProvider);
+ encoder = null;
+ fileHeader = null;
+ infoHeader = null;
+ }
+
+ /**
+ * Convert IIOMetadata from an input reader format, returning an IIOMetadata
+ * suitable for use by an image writer. The ImageTypeSpecifier specifies the
+ * destination image type. An optional ImageWriteParam argument is available
+ * in case the image writing parameters affect the metadata conversion.
+ *
+ * @param inData - the metadata coming from an image reader
+ * @param imageType - the output image type of the writer
+ * @param param - the image writing parameters or null
+ * @return the converted metadata that should be used by the image writer, or
+ * null if this ImageTranscoder has no knowledge of the input metadata
+ * @exception IllegalArgumentException if either inData or imageType is null
+ */
+ public IIOMetadata convertImageMetadata(IIOMetadata inData,
+ ImageTypeSpecifier imageType,
+ ImageWriteParam param)
+ {
+ // FIXME: Support metadata.
+ if (inData == null || imageType == null)
+ throw new IllegalArgumentException("IIOMetadata and ImageTypeSpecifier cannot be null.");
+ return null;
+ }
+
+ /**
+ * Convert IIOMetadata from an input stream format, returning an
+ * IIOMetadata suitable for use by an image writer.
+ *
+ * An optional ImageWriteParam argument is available in case the
+ * image writing parameters affect the metadata conversion.
+ *
+ * @param inData - the metadata coming from an input image stream
+ * @param param - the image writing parameters or null
+ * @return the converted metadata that should be used by the image
+ * writer, or null if this ImageTranscoder has no knowledge of the
+ * input metadata
+ *
+ * @exception IllegalArgumentException if inData is null
+ */
+ public IIOMetadata convertStreamMetadata (IIOMetadata inData,
+ ImageWriteParam param)
+ {
+ // FIXME: Support metadata.
+ if (inData == null)
+ throw new IllegalArgumentException("IIOMetadata cannot be null.");
+ return null;
+ }
+
+ /**
+ * Get a metadata object appropriate for encoding an image specified
+ * by the given image type specifier and optional image write
+ * parameters.
+ *
+ * @param imageType - an image type specifier
+ * @param param - image writing parameters, or null
+ * @return a metadata object appropriate for encoding an image of
+ * the given type with the given parameters
+ */
+ public IIOMetadata getDefaultImageMetadata (ImageTypeSpecifier imageType, ImageWriteParam param)
+ {
+ // FIXME: Support metadata.
+ return null;
+ }
+
+ /**
+ * Get a metadata object appropriate for encoding the default image
+ * type handled by this writer, optionally considering image write
+ * parameters.
+ *
+ * @param param - image writing parameters, or null
+ * @return a metadata object appropriate for encoding an image of
+ * the default type with the given parameters
+ */
+ public IIOMetadata getDefaultStreamMetadata (ImageWriteParam param)
+ {
+ // FIXME: Support metadata.
+ return null;
+ }
+
+ /**
+ * Write an image stream, including thumbnails and metadata to the
+ * output stream. The output must have been set prior to this
+ * method being called. Metadata associated with the stream may be
+ * supplied, or it can be left null. IIOImage may contain raster
+ * data if this writer supports rasters, or it will contain a
+ * rendered image. Thumbnails are resized if need be. Image
+ * writing parameters may be specified to affect writing, or may be
+ * left null.
+ *
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data, metadata and
+ * thumbnails to be written
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ * @throws BMPException if the encoder has not been initialized.
+ */
+ public void write(IIOMetadata streamMetadata, IIOImage image,
+ ImageWriteParam param) throws IOException, BMPException
+ {
+ checkStream();
+ ImageOutputStream out = (ImageOutputStream) output;
+ fileHeader = new BMPFileHeader(out, image);
+ infoHeader = new BMPInfoHeader(out, image, param);
+ encoder = BMPEncoder.getEncoder(fileHeader, infoHeader);
+
+ if (encoder != null)
+ encoder.encode(out, streamMetadata, image, param);
+ else
+ throw new BMPException("Encoder has not been initialized.");
+ out.close();
+ }
+
+ /**
+ * Checks the output stream.
+ *
+ * @throws IOException if there is an error with the output stream
+ */
+ private void checkStream() throws IOException
+ {
+ if (!(output instanceof ImageOutputStream))
+ throw new IllegalStateException("Output not an ImageOutputStream.");
+ if (output == null)
+ throw new IllegalStateException("No output stream.");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriterSpi.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriterSpi.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriterSpi.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPImageWriterSpi.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,148 @@
+/* BMPImageWriterSpi.java --
+ 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.javax.imageio.bmp;
+
+import java.util.Locale;
+
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.ImageWriter;
+import javax.imageio.spi.ImageWriterSpi;
+
+public class BMPImageWriterSpi
+ extends ImageWriterSpi
+{
+
+ static final String vendorName = "GNU";
+ static final String version = "0.1";
+ static final String writerClassName = "gnu.javax.imageio.bmp.BMPImageWriter";
+ static final String[] names = { "Microsoft Windows BMP" };
+ static final String[] suffixes = { ".bmp", ".bm" };
+ static final String[] MIMETypes = { "image/bmp", "image/x-windows-bmp" };
+ static final String[] readerSpiNames = { "gnu.javax.imageio.bmp.BMPImageReaderSpi" };
+
+ static final boolean supportsStandardStreamMetadataFormat = false;
+ static final String nativeStreamMetadataFormatName = null;
+ static final String nativeStreamMetadataFormatClassName = null;
+ static final String[] extraStreamMetadataFormatNames = null;
+ static final String[] extraStreamMetadataFormatClassNames = null;
+ static final boolean supportsStandardImageMetadataFormat = false;
+ static final String nativeImageMetadataFormatName = null;
+ static final String nativeImageMetadataFormatClassName = null;
+ static final String[] extraImageMetadataFormatNames = null;
+ static final String[] extraImageMetadataFormatClassNames = null;
+
+ private BMPImageWriter writerInstance;
+
+ public BMPImageWriterSpi()
+ {
+ super(vendorName, version, names, suffixes, MIMETypes, writerClassName,
+ STANDARD_OUTPUT_TYPE, readerSpiNames, supportsStandardStreamMetadataFormat,
+ nativeStreamMetadataFormatName, nativeStreamMetadataFormatClassName,
+ extraStreamMetadataFormatNames, extraStreamMetadataFormatClassNames,
+ supportsStandardImageMetadataFormat, nativeImageMetadataFormatName,
+ nativeImageMetadataFormatClassName, extraImageMetadataFormatNames,
+ extraImageMetadataFormatClassNames);
+ }
+
+ /**
+ * Returns true if the image can be encoded.
+ *
+ * @param type - the image type specifier.
+ * @return true if image can be encoded, otherwise false.
+ */
+ public boolean canEncodeImage(ImageTypeSpecifier type)
+ {
+ if (type == null)
+ return false;
+
+ BMPInfoHeader ih = writerInstance.infoHeader;
+ if (ih != null)
+ {
+ int compressionType = ih.getCompression();
+ int bytes = type.getColorModel().getPixelSize();
+ if ((compressionType == BMPInfoHeader.BI_RLE4 && (bytes != 4 || bytes != 8))
+ || (compressionType == BMPInfoHeader.BI_RGB && ((bytes != 1
+ || bytes != 4
+ || bytes != 8
+ || bytes != 16
+ || bytes != 24
+ || bytes != 32))))
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Creates an instance of ImageWriter using the given extension.
+ *
+ * @param extension - the provider that is constructing this image writer, or
+ * null
+ */
+ public ImageWriter createWriterInstance(Object extension)
+ {
+ if (extension != null && extension instanceof ImageWriterSpi)
+ writerInstance = new BMPImageWriter((ImageWriterSpi) extension);
+ else
+ writerInstance = new BMPImageWriter(this);
+ return writerInstance;
+ }
+
+ /**
+ * Gets the instance of ImageWriter, if already created.
+ */
+ public BMPImageWriter getWriterInstance()
+ {
+ if (writerInstance != null)
+ return writerInstance;
+ return (BMPImageWriter) createWriterInstance(null);
+ }
+
+ /**
+ * Returns a short description of this service provider that can be
+ * presented to a human user.
+ *
+ * @param locale - the locale for which the description string should
+ * be localized.
+ */
+ public String getDescription(Locale locale)
+ {
+ return "Microsoft BMP v3";
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPInfoHeader.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPInfoHeader.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPInfoHeader.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/BMPInfoHeader.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,317 @@
+/* BMPInfoHeader.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.Dimension;
+import java.awt.image.ColorModel;
+import java.awt.image.RenderedImage;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.stream.ImageInputStream;
+import javax.imageio.stream.ImageOutputStream;
+
+public class BMPInfoHeader
+{
+ /** Size of the bitmap info header */
+ protected int biSize;
+
+ /** Pixel width of the bitmap */
+ protected int biWidth;
+
+ /** Pixel height of the bitmap */
+ protected int biHeight;
+
+ /** Number of bitplanes = 1 */
+ protected short biPlanes;
+
+ /** Number of bpp = 1,4,8,24 */
+ protected short biBitCount;
+
+ /** Compression type, RGB8, RLE8, RLE4, BITFIELDS */
+ protected int biCompression;
+
+ /** Byte size of the uncompressed bitmap, can be 0. */
+ protected int biSizeImage;
+
+ /** X resolution, dots per meter */
+ protected int biXPelsPerMeter;
+
+ /** Y resolution, dots per meter */
+ protected int biYPelsPerMeter;
+
+ /** Number of colors used (palette only, can be 0 for all) */
+ protected int biClrUsed;
+
+ /** Number of 'important' colors, 0 for all */
+ protected int biClrImportant;
+
+ /** BITMAPINFOHEADER is 40 bytes */
+ public static final int SIZE = 40;
+
+ /**
+ * Compression types
+ */
+ public static final int BI_RGB = 0;
+ public static final int BI_RLE8 = 1;
+ public static final int BI_RLE4 = 2;
+ public static final int BI_BITFIELDS = 3;
+
+ /**
+ * Creates the header from an input stream, which is not closed.
+ *
+ * @param in - the image input stream
+ * @throws IOException if an I/O error occured.
+ * @throws BMPException if the header was invalid
+ */
+ public BMPInfoHeader(ImageInputStream in) throws IOException, BMPException
+ {
+ byte[] data = new byte[SIZE];
+
+ if (in.read(data) != SIZE)
+ throw new IOException("Couldn't read header.");
+ ByteBuffer buf = ByteBuffer.wrap(data);
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+
+ int n;
+ if ((n = buf.getInt()) != SIZE)
+ throw new BMPException("Invalid BITMAPINFOHEADER size: " + n);
+
+ biWidth = buf.getInt();
+ biHeight = buf.getInt();
+ biPlanes = buf.getShort();
+ setBitCount(buf.getShort());
+ setCompression(buf.getInt());
+ biSizeImage = buf.getInt();
+ biXPelsPerMeter = buf.getInt();
+ biYPelsPerMeter = buf.getInt();
+ biClrUsed = buf.getInt();
+ biClrImportant = buf.getInt();
+ }
+
+ /**
+ * Creates the info header from an output stream, which is not closed.
+ *
+ * @param out - the image output stream
+ * @param im - the image
+ * @param param - the image write param.
+ * @throws IOException if an I/O error occured.
+ */
+ public BMPInfoHeader(ImageOutputStream out, IIOImage im, ImageWriteParam param) throws IOException
+ {
+ RenderedImage img = im.getRenderedImage();
+ ColorModel cMod = img.getColorModel();
+
+ biSize = SIZE;
+ biWidth = img.getWidth();
+ biHeight = img.getHeight();
+ biPlanes = 1;
+
+ if (param != null && param.canWriteCompressed())
+ {
+ String compType = param.getCompressionType();
+ if (compType.equals("BI_RLE8"))
+ {
+ biCompression = BI_RLE8;
+ biBitCount = 8;
+ }
+ else if (compType.equals("BI_RLE4"))
+ {
+ biCompression = BI_RLE4;
+ biBitCount = 4;
+ }
+ else
+ {
+ biCompression = BI_RGB;
+ biBitCount = (short) cMod.getPixelSize();
+ }
+ }
+ else
+ {
+ biBitCount = (short) cMod.getPixelSize();
+ biCompression = BI_RGB;
+ }
+
+ biXPelsPerMeter = 0x0;
+ biYPelsPerMeter = 0x0;
+ biClrUsed = 0;
+ biClrImportant = 0;
+ biSizeImage = ((biWidth * biHeight) * 3)
+ + ((4 - ((biWidth * 3) % 4)) * biHeight);
+ out.write(intToDWord(biSize));
+ out.write(intToDWord(biWidth));
+ out.write(intToDWord(biHeight));
+ out.write(intToWord(biPlanes));
+ out.write(intToWord(biBitCount));
+ out.write(intToDWord(biCompression));
+ out.write(intToDWord(biSizeImage));
+ out.write(intToDWord(biXPelsPerMeter));
+ out.write(intToDWord(biYPelsPerMeter));
+ out.write(intToDWord(biClrUsed));
+ out.write(intToDWord(biClrImportant));
+ }
+
+ /**
+ * Converts an int to a word, where the return value is stored in a
+ * 2-byte array.
+ *
+ * @param val - the value to convert
+ * @return the array
+ */
+ private byte[] intToWord(int val)
+ {
+ byte b[] = new byte[2];
+ b[0] = (byte) (val & 0x00FF);
+ b[1] = (byte) ((val >> 8) & 0x00FF);
+ return b;
+ }
+
+ /**
+ * Converts an int to a double word, where the return value is
+ * stored in a 4-byte array.
+ *
+ * @param val - the value to convert
+ * @return the array
+ */
+ private byte[] intToDWord(int val)
+ {
+ byte b[] = new byte[4];
+ b[0] = (byte) (val & 0x00FF);
+ b[1] = (byte) ((val >> 8) & 0x000000FF);
+ b[2] = (byte) ((val >> 16) & 0x000000FF);
+ b[3] = (byte) ((val >> 24) & 0x000000FF);
+ return b;
+ }
+
+
+ public void setBitCount(short bitcount) throws BMPException
+ {
+ switch (bitcount)
+ {
+ case 1:
+ case 4:
+ case 8:
+ case 16:
+ case 24:
+ case 32:
+ biBitCount = bitcount;
+ break;
+
+ default:
+ throw new BMPException("Invalid number of bits per pixel: " + bitcount);
+ }
+ }
+
+ public short getBitCount()
+ {
+ return biBitCount;
+ }
+
+ public void setCompression(int compression) throws BMPException
+ {
+ switch (compression)
+ {
+ case BI_RLE8:
+ if (getBitCount() != 8)
+ throw new BMPException("Invalid number of bits per pixel.");
+ biCompression = compression;
+ break;
+ case BI_RLE4:
+ if (getBitCount() != 4)
+ throw new BMPException("Invalid number of bits per pixel.");
+ biCompression = compression;
+ break;
+
+ case BI_RGB:
+ case BI_BITFIELDS:
+ biCompression = compression;
+ break;
+
+ default:
+ throw new BMPException("Unknown bitmap compression type.");
+ }
+ }
+
+ public int getNumberOfPaletteEntries()
+ {
+ if (biClrUsed == 0)
+ switch (biBitCount)
+ {
+ case 1:
+ return 2;
+ case 4:
+ return 16;
+ case 8:
+ return 256;
+
+ default: // should not happen
+ return 0;
+ }
+
+ return biClrUsed;
+ }
+
+ public int getCompression()
+ {
+ return biCompression;
+ }
+
+ public Dimension getSize()
+ {
+ return new Dimension(biWidth, biHeight);
+ }
+
+ public int getWidth()
+ {
+ return biWidth;
+ }
+
+ public int getHeight()
+ {
+ return biHeight;
+ }
+
+ public void setSize(Dimension d)
+ {
+ biWidth = (int) d.getWidth();
+ biHeight = (int) d.getHeight();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF16.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF16.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF16.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF16.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,104 @@
+/* DecodeBF16.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferUShort;
+import java.awt.image.SinglePixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeBF16 extends BMPDecoder {
+ private int[] bitmasks;
+ private boolean useDefaultMasks;
+
+ public DecodeBF16(BMPFileHeader fh, BMPInfoHeader ih,
+ boolean udm){
+ super(fh,ih);
+
+ useDefaultMasks = udm;
+ if(useDefaultMasks) // 5-6-5 mask, B,G,R
+ bitmasks = new int[] { 0x00F800, 0x0007E0, 0x00001F };
+ }
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ if(!useDefaultMasks)
+ bitmasks = readBitMasks(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+
+ // BMP scanlines are padded to dword offsets
+ int scansize = (w + (w&1)) << 1;
+ short[] data = new short[w*h];
+
+ for(int y=h-1;y>=0;y--){
+ byte[] scanline = new byte[scansize];
+ if(in.read(scanline) != scansize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<w;x++)
+ data[x + y*w] = (short)((scanline[x*2] & (0xFF)) |
+ ((scanline[x*2+1] & (0xFF)) << 8));
+ }
+
+ ColorModel cm = new DirectColorModel(16,
+ bitmasks[0], bitmasks[1], bitmasks[2]);
+ SampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_USHORT,
+ w, h,
+ bitmasks);
+ DataBuffer db = new DataBufferUShort(data, w*h, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+ return new BufferedImage(cm, raster, false, null);
+ }
+
+}
+
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF32.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF32.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF32.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeBF32.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,106 @@
+/* DecodeBF32.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferInt;
+import java.awt.image.SinglePixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeBF32 extends BMPDecoder {
+ private int[] bitmasks;
+ private boolean useDefaultMasks;
+
+ public DecodeBF32(BMPFileHeader fh, BMPInfoHeader ih,
+ boolean udm){
+ super(fh,ih);
+
+ useDefaultMasks = udm;
+ if(useDefaultMasks)
+ bitmasks = new int[] { 0x00FF0000, 0x0000FF00, 0x000000FF };
+ }
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ if(!useDefaultMasks)
+ bitmasks = readBitMasks(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+
+ // BMP scanlines are padded to dword offsets
+ int scansize = w << 2;
+ int[] data = new int[w*h];
+
+
+ for(int y=h-1;y>=0;y--){
+ byte[] scanline = new byte[scansize];
+ if(in.read(scanline) != scansize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<w;x++)
+ data[x + y*w] = ((scanline[x<<2] & (0xFF)) |
+ ((scanline[(x<<2)+1] & (0xFF)) << 8) |
+ ((scanline[(x<<2)+2] & (0xFF)) << 16) |
+ ((scanline[(x<<2)+3] & (0xFF)) << 24));
+ }
+
+ ColorModel cm = new DirectColorModel(32,
+ bitmasks[0], bitmasks[1], bitmasks[2]);
+ SampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT,
+ w, h,
+ bitmasks);
+ DataBuffer db = new DataBufferInt(data, w*h);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(cm, raster, false, null);
+ }
+
+}
+
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB1.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB1.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB1.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB1.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,96 @@
+/* DecodeRGB1.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.MultiPixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeRGB1 extends BMPDecoder {
+
+ public DecodeRGB1(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ public BufferedImage decode(ImageInputStream in)
+ throws IOException, BMPException {
+
+ IndexColorModel palette = readPalette(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+ int size = (w*h)>>3;
+
+ int scansize = w>>3;
+ byte[] data = new byte[size];
+
+ for(int y=h-1;y>=0;y--){
+ // Scanlines are padded to dword boundries
+ int readsize = scansize;
+ if((readsize & 3) != 0) readsize += (4 - (scansize & 3));
+
+ byte[] scanline = new byte[readsize];
+ if(in.read(scanline) != readsize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<scansize;x++)
+ data[x + y*scansize] = scanline[x];
+ }
+
+ SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ w, h, 1);
+
+ DataBuffer db = new DataBufferByte(data, size, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(palette, raster, false, null);
+ }
+
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB24.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB24.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB24.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB24.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,77 @@
+/* DecodeRGB24.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.Dimension;
+
+public class DecodeRGB24 extends BMPDecoder {
+
+ public DecodeRGB24(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+ BufferedImage image = new BufferedImage(w, h,
+ BufferedImage.TYPE_INT_RGB);
+ // BMP scanlines are padded to dword offsets
+ int scansize = ((w*3 & 3) != 0)? w*3 + 4 - (w*3 & 3): w*3;
+ int[] data = new int[w*h];
+
+ for(int y=h-1;y>=0;y--){
+ byte[] scanline = new byte[scansize];
+ if(in.read(scanline) != scansize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<w;x++)
+ data[x + y*w] = scanline[x*3] +
+ (scanline[x*3+1] << 8) +
+ (scanline[x*3+2] << 16);
+ }
+ image.setRGB(0, 0, w, h, data, 0, w);
+ return image;
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB4.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB4.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB4.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB4.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,92 @@
+/* DecodeRGB4.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.MultiPixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeRGB4 extends BMPDecoder {
+
+ public DecodeRGB4(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ IndexColorModel palette = readPalette(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+ int size = (w*h) >> 1;
+
+ // Scanline padded to dword offsets
+ int wbytes = (w + (w & 1)) >> 1;
+ int scansize = ((wbytes & 3) != 0)? (wbytes + 4 - (wbytes&3)) : wbytes;
+
+ byte[] data = new byte[wbytes*h];
+
+ for(int y=h-1;y>=0;y--){
+ byte[] scanline = new byte[scansize];
+ if(in.read(scanline) != scansize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<wbytes;x++)
+ data[x + y*wbytes] = scanline[x];
+ }
+ SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ w, h, 4);
+
+ DataBuffer db = new DataBufferByte(data, w*h, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(palette, raster, false, null);
+ }
+
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB8.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB8.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB8.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRGB8.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,90 @@
+/* DecodeRGB8.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.SinglePixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeRGB8 extends BMPDecoder {
+
+ public DecodeRGB8(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ IndexColorModel palette = readPalette(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+
+ // BMP scanlines are padded to dword offsets
+ int scansize = ((w & 3) != 0)? w + 4 - (w & 3): w;
+ byte[] data = new byte[w*h];
+
+ for(int y=h-1;y>=0;y--){
+ byte[] scanline = new byte[scansize];
+ if(in.read(scanline) != scansize)
+ throw new IOException("Couldn't read image data.");
+
+ for(int x=0;x<w;x++)
+ data[x + y*w] = scanline[x];
+ }
+
+ SampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ w, h,
+ new int[] {0xFF});
+ DataBuffer db = new DataBufferByte(data, w*h, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(palette, raster, false, null);
+ }
+
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE4.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE4.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE4.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE4.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,176 @@
+/* DecodeRLE4.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.MultiPixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeRLE4 extends BMPDecoder {
+
+ public DecodeRLE4(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ /**
+ * RLE control codes
+ */
+ private static final byte ESCAPE = (byte)0;
+ private static final byte EOL = (byte)0; // end of line
+ private static final byte EOB = (byte)1; // end of bitmap
+ private static final byte DELTA = (byte)2; // delta
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ IndexColorModel palette = readPalette(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+
+ byte[] data = uncompress(w, h, in);
+ SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ w, h, 4);
+
+ DataBuffer db = new DataBufferByte(data, w*h, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(palette, raster, false, null);
+ }
+
+ private byte[] uncompress(int w, int h, ImageInputStream in)
+ throws BMPException, IOException {
+ byte[] cmd = new byte[2];
+ byte[] data = new byte[w*h>>1];
+ int offIn = 0;
+ int x=0,y=0;
+
+ // width in bytes
+ w += (w&1);
+ w = w >> 1;
+
+ try {
+ while(((x>>1) + y*w) < w*h){
+ if(in.read(cmd) != 2)
+ throw new IOException("Error reading compressed data.");
+
+ if(cmd[0] == ESCAPE){
+ switch(cmd[1]){
+ case EOB: // end of bitmap
+ return data;
+ case EOL: // end of line
+ x = 0;
+ y++;
+ break;
+ case DELTA: // delta
+ if(in.read(cmd) != 2)
+ throw new IOException("Error reading compressed data.");
+ int dx = cmd[0] & (0xFF);
+ int dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+
+ default:
+ // decode a literal run
+ int length = cmd[1] & (0xFF);
+
+ // size of run, which is word aligned.
+ int bytesize = length;
+ bytesize += (bytesize & 1);
+ bytesize >>= 1;
+ bytesize += (bytesize & 1);
+
+ byte[] run = new byte[bytesize];
+ if(in.read(run) != bytesize)
+ throw new IOException("Error reading compressed data.");
+
+ if((x&1) == 0){
+ length += (length&1);
+ length >>= 1;
+ System.arraycopy(run, 0, data, ((x>>1) + w*(h-y-1)),
+ length);
+ } else {
+ for(int i=0;i<length;i++){
+ if((i&1) == 0) // copy high to low
+ data[((x+i)>>1) + w*(h-y-1)]
+ |= ((run[i>>1]&0xF0) >> 4);
+ else // copy low to high
+ data[((x+i)>>1) + w*(h-y-1)]
+ |= ((run[i>>1]&0x0F) << 4);
+ }
+ }
+ x += cmd[1] & (0xFF);
+ break;
+ }
+ } else {
+ // decode a byte run
+ int length = cmd[0] & (0xFF);
+ if((x&1) == 0){
+ length += (length&1);
+ length >>= 1;
+ for(int i=0;i<length;i++)
+ data[(h-y-1)*w + i + (x >> 1)] = cmd[1];
+ } else {
+ for(int i=0;i<length;i++){
+ if((i&1) == 0) // copy high to low
+ data[((x+i)>>1) + w*(h-y-1)]
+ |= ((cmd[1]&0xF0) >> 4);
+ else // copy low to high
+ data[((x+i)>>1) + w*(h-y-1)]
+ |= ((cmd[1]&0x0F) << 4);
+ }
+ }
+ x += cmd[0] & (0xFF);
+ }
+ }
+ return data;
+ } catch(ArrayIndexOutOfBoundsException e){
+ throw new BMPException("Invalid RLE data.");
+ }
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE8.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE8.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE8.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/DecodeRLE8.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,143 @@
+/* DecodeRLE8.java --
+ 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.javax.imageio.bmp;
+
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.SinglePixelPackedSampleModel;
+import java.awt.image.SampleModel;
+import java.awt.Dimension;
+
+public class DecodeRLE8 extends BMPDecoder {
+
+ public DecodeRLE8(BMPFileHeader fh, BMPInfoHeader ih){
+ super(fh, ih);
+ }
+
+ /**
+ * RLE control codes
+ */
+ private static final byte ESCAPE = (byte)0;
+ private static final byte EOL = (byte)0; // end of line
+ private static final byte EOB = (byte)1; // end of bitmap
+ private static final byte DELTA = (byte)2; // delta
+
+ public BufferedImage decode(ImageInputStream in) throws IOException, BMPException {
+ IndexColorModel palette = readPalette(in);
+ skipToImage(in);
+
+ Dimension d = infoHeader.getSize();
+ int h = (int)d.getHeight();
+ int w = (int)d.getWidth();
+
+ byte[] data = uncompress(w, h, in);
+ SampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ w, h,
+ new int[] {0xFF});
+ DataBuffer db = new DataBufferByte(data, w*h, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(palette, raster, false, null);
+ }
+
+ private byte[] uncompress(int w, int h, ImageInputStream in)
+ throws BMPException, IOException {
+ byte[] cmd = new byte[2];
+ byte[] data = new byte[w*h];
+ int offIn = 0;
+ int x=0,y=0;
+
+ try {
+ while((x + y*w) < w*h){
+ if(in.read(cmd) != 2)
+ throw new IOException("Error reading compressed data.");
+
+ if(cmd[0] == ESCAPE){
+ switch(cmd[1]){
+ case EOB: // end of bitmap
+ return data;
+ case EOL: // end of line
+ x = 0;
+ y++;
+ break;
+ case DELTA: // delta
+ if(in.read(cmd) != 2)
+ throw new IOException("Error reading compressed data.");
+ int dx = cmd[0] & (0xFF);
+ int dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+
+ default:
+ // decode a literal run
+ int length = cmd[1] & (0xFF);
+ int copylength = length;
+
+ // absolute mode must be word-aligned
+ length += (length & 1);
+
+ byte[] run = new byte[length];
+ if(in.read(run) != length)
+ throw new IOException("Error reading compressed data.");
+
+ System.arraycopy(run, 0, data, (x+w*(h-y-1)),
+ copylength);
+ x += copylength;
+ break;
+ }
+ } else {
+ // decode a byte run
+ int length = cmd[0] & (0xFF);
+ for(int i=0;i<length;i++)
+ data[(h-y-1)*w + x++] = cmd[1];
+ }
+ }
+ return data;
+ } catch(ArrayIndexOutOfBoundsException e){
+ throw new BMPException("Invalid RLE data.");
+ }
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB1.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB1.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB1.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB1.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* EncodeRGB1.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB1
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB1(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[1];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB16.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB16.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB16.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB16.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,129 @@
+/* EncodeRGB16.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB16
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB16(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[2];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+ rgb[1] = (byte) (value >> 8 & 0xFF);
+
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB24.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB24.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB24.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB24.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,129 @@
+/* EncodeRGB24.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB24
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB24(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[3];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+ rgb[1] = (byte) ((value >> 8) & 0xFF);
+ rgb[2] = (byte) ((value >> 16) & 0xFF);
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB32.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB32.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB32.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB32.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,130 @@
+/* EncodeRGB32.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.Dimension;
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB32
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB32(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[4];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+ rgb[1] = (byte) ((value >> 8) & 0xFF);
+ rgb[2] = (byte) ((value >> 16) & 0xFF);
+ rgb[3] = (byte) ((value >> 24) & 0xFF);
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB4.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB4.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB4.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB4.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* EncodeRGB4.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB4
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB4(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[1];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB8.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB8.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB8.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRGB8.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* EncodeRGB8.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRGB8
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRGB8(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ byte rgb[] = new byte[1];
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+
+ rgb[0] = (byte) (value & 0xFF);
+ o.write(rgb);
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE4.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE4.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE4.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE4.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,269 @@
+/* EncodeRLE4.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRLE4
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * RLE control codes
+ */
+ private static final byte ESCAPE = (byte)0;
+ private static final byte EOL = (byte)0; // end of line
+ private static final byte EOB = (byte)1; // end of bitmap
+ private static final byte DELTA = (byte)2; // delta
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRLE4(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ ByteBuffer buf = ByteBuffer.allocate(size);
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+ buf.put((byte) (value & 0xFF));
+
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+
+ buf.flip();
+ o.write(uncompress(infoHeader.biWidth, infoHeader.biHeight, buf));
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+
+ /**
+ * Uncompresses the image stored in the buffer.
+ *
+ * @param w - the width of the image
+ * @param h - the height of the image
+ * @param buf - the ByteBuffer containing the pixel values.
+ * @return byte array containing the uncompressed image
+ * @throws IOException if an error is encountered while reading
+ * buffer.
+ */
+ private byte[] uncompress(int w, int h, ByteBuffer buf)
+ throws IOException
+ {
+ byte[] cmd = new byte[2];
+ byte[] data = new byte[w * h >> 1];
+ int offIn = 0;
+ int x = 0, y = 0;
+
+ w += (w & 1);
+ w = w >> 1;
+
+ try
+ {
+ while (((x >> 1) + y * w) < w * h)
+ {
+ try
+ {
+ buf.get(cmd);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ if (cmd[0] == ESCAPE)
+ {
+ switch (cmd[1])
+ {
+ case EOB:
+ return data;
+ case EOL:
+ x = 0;
+ y++;
+ break;
+ case DELTA:
+ try
+ {
+ buf.get(cmd);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ int dx = cmd[0] & (0xFF);
+ int dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+
+ default:
+ int length = cmd[1] & (0xFF);
+
+ int bytesize = length;
+ bytesize += (bytesize & 1);
+ bytesize >>= 1;
+ bytesize += (bytesize & 1);
+
+ byte[] run = new byte[bytesize];
+ try
+ {
+ buf.get(run);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ if ((x & 1) == 0)
+ {
+ length += (length & 1);
+ length >>= 1;
+ System.arraycopy(run, 0, data,
+ ((x >> 1) + w * (h - y - 1)), length);
+ }
+ else
+ {
+ for (int i = 0; i < length; i++)
+ {
+ if ((i & 1) == 0)
+ data[((x + i) >> 1) + w * (h - y - 1)] |= ((run[i >> 1] & 0xF0) >> 4);
+ else
+ data[((x + i) >> 1) + w * (h - y - 1)] |= ((run[i >> 1] & 0x0F) << 4);
+ }
+ }
+ x += cmd[1] & (0xFF);
+ break;
+ }
+ }
+ else
+ {
+ int length = cmd[0] & (0xFF);
+ if ((x & 1) == 0)
+ {
+ length += (length & 1);
+ length >>= 1;
+ for (int i = 0; i < length; i++)
+ data[(h - y - 1) * w + i + (x >> 1)] = cmd[1];
+ }
+ else
+ {
+ for (int i = 0; i < length; i++)
+ {
+ if ((i & 1) == 0)
+ data[((x + i) >> 1) + w * (h - y - 1)] |= ((cmd[1] & 0xF0) >> 4);
+ else
+ data[((x + i) >> 1) + w * (h - y - 1)] |= ((cmd[1] & 0x0F) << 4);
+ }
+ }
+ x += cmd[0] & (0xFF);
+ }
+ }
+ return data;
+ }
+ catch (ArrayIndexOutOfBoundsException e)
+ {
+ throw new BMPException("Invalid RLE data.");
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE8.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE8.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE8.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/imageio/bmp/EncodeRLE8.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,234 @@
+/* EncodeRGB32.java --
+ 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.javax.imageio.bmp;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.PixelGrabber;
+import java.io.IOException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeRLE8
+ extends BMPEncoder
+{
+ protected BMPInfoHeader infoHeader;
+ protected BMPFileHeader fileHeader;
+ protected long offset;
+
+ /**
+ * RLE control codes
+ */
+ private static final byte ESCAPE = (byte)0;
+ private static final byte EOL = (byte)0; // end of line
+ private static final byte EOB = (byte)1; // end of bitmap
+ private static final byte DELTA = (byte)2; // delta
+
+ /**
+ * Constructs an instance of this class.
+ *
+ * @param fh - the file header to use.
+ * @param ih - the info header to use.
+ */
+ public EncodeRLE8(BMPFileHeader fh, BMPInfoHeader ih)
+ {
+ super();
+ fileHeader = fh;
+ infoHeader = ih;
+ offset = BMPFileHeader.SIZE + BMPInfoHeader.SIZE;
+ }
+
+ /**
+ * The image encoder.
+ *
+ * @param o - the image output stream
+ * @param streamMetadata - metadata associated with this stream, or
+ * null
+ * @param image - an IIOImage containing image data.
+ * @param param - image writing parameters, or null
+ * @exception IOException if a write error occurs
+ */
+ public void encode(ImageOutputStream o, IIOMetadata streamMetadata,
+ IIOImage image, ImageWriteParam param) throws IOException
+ {
+ int size;
+ int value;
+ int j;
+ int rowCount;
+ int rowIndex;
+ int lastRowIndex;
+ int[] bitmap;
+ size = (infoHeader.biWidth * infoHeader.biHeight) - 1;
+ rowCount = 1;
+ rowIndex = size - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ ByteBuffer buf = ByteBuffer.allocate(size);
+ try
+ {
+ bitmap = new int[infoHeader.biWidth * infoHeader.biHeight];
+ PixelGrabber pg = new PixelGrabber((BufferedImage) image.getRenderedImage(),
+ 0, 0, infoHeader.biWidth,
+ infoHeader.biHeight, bitmap, 0,
+ infoHeader.biWidth);
+ pg.grabPixels();
+
+ for (j = 0; j < size; j++)
+ {
+ value = bitmap[rowIndex];
+ buf.put((byte) (value & 0xFF));
+
+ if (rowCount == infoHeader.biWidth)
+ {
+ rowCount = 1;
+ rowIndex = lastRowIndex - infoHeader.biWidth;
+ lastRowIndex = rowIndex;
+ }
+ else
+ rowCount++;
+ rowIndex++;
+ }
+
+ buf.flip();
+ o.write(uncompress(infoHeader.biWidth, infoHeader.biHeight, buf));
+ }
+ catch (Exception wb)
+ {
+ wb.printStackTrace();
+ }
+ }
+
+
+ /**
+ * Uncompresses the image stored in the buffer.
+ *
+ * @param w - the width of the image
+ * @param h - the height of the image
+ * @param buf - the ByteBuffer containing the pixel values.
+ * @return byte array containing the uncompressed image
+ * @throws IOException if an error is encountered while reading
+ * buffer.
+ */
+ private byte[] uncompress(int w, int h, ByteBuffer buf) throws IOException
+ {
+ byte[] cmd = new byte[2];
+ byte[] data = new byte[w * h];
+ int offIn = 0;
+ int x = 0, y = 0;
+
+ try
+ {
+ while ((x + y * w) < w * h)
+ {
+ try
+ {
+ buf.get(cmd);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ if (cmd[0] == ESCAPE)
+ {
+ switch (cmd[1])
+ {
+ case EOB:
+ return data;
+ case EOL:
+ x = 0;
+ y++;
+ break;
+ case DELTA:
+ try
+ {
+ buf.get(cmd);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ int dx = cmd[0] & (0xFF);
+ int dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+
+ default:
+ int length = cmd[1] & (0xFF);
+ int copylength = length;
+
+ length += (length & 1);
+
+ byte[] run = new byte[length];
+
+ try
+ {
+ buf.get(run);
+ }
+ catch (BufferUnderflowException e)
+ {
+ throw new IOException("Error reading compressed data.");
+ }
+
+ System.arraycopy(run, 0, data, (x + w * (h - y - 1)),
+ copylength);
+ x += copylength;
+ break;
+ }
+ }
+ else
+ {
+ int length = cmd[0] & (0xFF);
+ for (int i = 0; i < length; i++)
+ data[(h - y - 1) * w + x++] = cmd[1];
+ }
+ }
+ return data;
+ }
+ catch (ArrayIndexOutOfBoundsException e)
+ {
+ throw new BMPException("Invalid RLE data.");
+ }
+ }
+}
More information about the llvm-commits
mailing list