hello all,

the attached patch --already committed-- fixes some bugs in the 
gnu.javax.crypto.keyring package and adds trace/debugging statements to 
some of its classes.  a Mauve testlet has been checked-in to validate 
these changes:

gnu.testlet.gnu.javax.crypto.keyring.TestOfGnuPrivateKeyring


2006-05-20  Raif S. Naffah  <[EMAIL PROTECTED]>

        * gnu/javax/crypto/keyring/PrivateKeyEntry.java: Formatting.
        (toString): New method.
        * gnu/javax/crypto/keyring/PasswordEncryptedEntry.java (decrypt):
        Do not trace/log passwords.
        Set masked to false before decoding envelope.
        Do not set payload to null.
        (encrypt): Set masked to true.
        * gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java (verify):
        Do not trace/log passwords.
        Set masked to false before decoding envelope.
        Do not set payload to null.
        Added trace/debug statements.
        (authenticate): Do not trace/log passwords.
        Set masked to true.
        Added trace/debug statements.
        (getMac): Added trace/debug statements.
        * gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java
        (remove(String)): Changed the signature to return a boolean.
        (toString): New method.
        * gnu/javax/crypto/keyring/GnuPublicKeyring.java (containsCertificate):
        Formatting
        (getCertificate): Likewise.
        (putCertificate): Likewise.
        (load): Likewise.
        Do not trace/log passwords.
        (store): Likewise.
        * gnu/javax/crypto/keyring/GnuPrivateKeyring.java (getPrivateKey):
        Do not trace/log passwords.
        Added more trace/logging statements.
        (putPrivateKey): Do not trace/log passwords.
        Trace only key's class name.
        Formatting.
        (containsPublicKey): Formatting.
        (getPublicKey): Likewise.
        Trace only key's class name.
        (putPublicKey): Trace only key's class name.
        (containsCertPath): Formatting.
        (getCertPath): Likewise.
        (putCertPath): Likewise.
        (load): Do not trace/log passwords.
        Formatting.
        (store): Likewise.
        * gnu/javax/crypto/keyring/EnvelopeEntry.java (log): New field.
        (add): Do not set payload to null.
        Added trace/debug statements.
        (containsAlias): Added trace/debug statements.
        (get): Likewise.
        (remove(Entry)): Likewise.
        (remove(String)): Likewise.
        Changed the signature to return a boolean.
        Do not set payload to null unless really removed.
        (toString): New method.
        (decodeEnvelope): Clear entries before proceeding.
        (makeAliasList): Added trace/debug statements.
        Ensure only non-null aliases and alias-lists are added.
        * gnu/javax/crypto/keyring/Entry.java (log): New field.
        (TYPES): New constant.
        (toString): New method.
        (defaultDecode): Add trace/debug statement.


cheers;
rsn
Index: Entry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/Entry.java,v
retrieving revision 1.1
diff -u -r1.1 Entry.java
--- Entry.java	26 Jan 2006 02:25:09 -0000	1.1
+++ Entry.java	20 May 2006 01:51:35 -0000
@@ -41,16 +41,23 @@
 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
 {
-
   // Fields.
   // ------------------------------------------------------------------------

+  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;

@@ -145,6 +152,17 @@
     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.
@@ -161,6 +179,7 @@
       {
         throw new IOException("corrupt length");
       }
+    log.finest("About to instantiate new payload byte array for " + this);
     payload = new byte[len];
     in.readFully(payload);
   }
Index: EnvelopeEntry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/EnvelopeEntry.java,v
retrieving revision 1.1
diff -u -r1.1 EnvelopeEntry.java
--- EnvelopeEntry.java	26 Jan 2006 02:25:09 -0000	1.1
+++ EnvelopeEntry.java	20 May 2006 01:52:16 -0000
@@ -42,13 +42,12 @@
 import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
-
 import java.util.ArrayList;
-import java.util.Date;
 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
@@ -56,10 +55,10 @@
  */
 public abstract class EnvelopeEntry extends Entry
 {
-
   // Fields.
   // ------------------------------------------------------------------------

+  private static final Logger log = Logger.getLogger(EnvelopeEntry.class.getName());
   /** The envelope that contains this one (if any). */
   protected EnvelopeEntry containingEnvelope;

@@ -95,16 +94,17 @@
    */
   public void add(Entry entry)
   {
-    if (!containsEntry(entry))
+    log.entering(this.getClass().getName(), "add", entry);
+    if (! containsEntry(entry))
       {
         if (entry instanceof EnvelopeEntry)
-          {
-            ((EnvelopeEntry) entry).setContainingEnvelope(this);
-          }
+          ((EnvelopeEntry) entry).setContainingEnvelope(this);
+
         entries.add(entry);
-        payload = null;
+        log.finest("Payload is " + (payload == null ? "" : "not ") + "null");
         makeAliasList();
       }
+    log.exiting(this.getClass().getName(), "add");
   }

   /**
@@ -117,20 +117,22 @@
    */
   public boolean containsAlias(String alias)
   {
+    log.entering(this.getClass().getName(), "containsAlias", alias);
     String aliases = getAliasList();
-    if (aliases == null)
-      {
-        return false;
-      }
-    StringTokenizer tok = new StringTokenizer(aliases, ";");
-    while (tok.hasMoreTokens())
-      {
-        if (tok.nextToken().equals(alias))
-          {
-            return true;
-          }
+    log.finest("aliases = [" + aliases + "]");
+    boolean result = false;
+    if (aliases != null)
+      {
+        StringTokenizer tok = new StringTokenizer(aliases, ";");
+        while (tok.hasMoreTokens())
+          if (tok.nextToken().equals(alias))
+            {
+              result = true;
+              break;
+            }
       }
-    return false;
+    log.exiting(this.getClass().getName(), "containsAlias", Boolean.valueOf(result));
+    return result;
   }

   /**
@@ -180,34 +182,41 @@
    */
   public List get(String alias)
   {
+    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)
           {
-            if (!((EnvelopeEntry) e).containsAlias(alias))
-              {
-                continue;
-              }
-            if (e instanceof MaskableEnvelopeEntry)
+            EnvelopeEntry ee = (EnvelopeEntry) e;
+            if (! ee.containsAlias(alias))
+              continue;
+
+            if (ee instanceof MaskableEnvelopeEntry)
               {
-                if (((MaskableEnvelopeEntry) e).isMasked())
+                MaskableEnvelopeEntry mee = (MaskableEnvelopeEntry) ee;
+                if (mee.isMasked())
                   {
-                    result.add(e);
+                    log.finer("Processing masked entry: " + mee);
+                    result.add(mee);
                     continue;
                   }
               }
-            result.addAll(((EnvelopeEntry) e).get(alias));
+
+            log.finer("Processing unmasked entry: " + ee);
+            result.addAll(ee.get(alias));
           }
         else if (e instanceof PrimitiveEntry)
           {
-            if (((PrimitiveEntry) e).getAlias().equals(alias))
-              {
-                result.add(e);
-              }
+            PrimitiveEntry pe = (PrimitiveEntry) e;
+            if (pe.getAlias().equals(alias))
+              result.add(e);
           }
       }
+
+    log.exiting(this.getClass().getName(), "get", result);
     return result;
   }

@@ -238,6 +247,7 @@
    */
   public boolean remove(Entry entry)
   {
+    log.entering(this.getClass().getName(), "remove", entry);
     boolean ret = false;
     for (Iterator it = entries.iterator(); it.hasNext();)
       {
@@ -268,36 +278,63 @@
       }
     if (ret)
       {
+        log.finest("State before: " + this);
         payload = null;
         makeAliasList();
+        log.finest("State after: " + this);
       }
+    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 void remove(String alias)
+  public boolean remove(String alias)
   {
+    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) e).remove(alias);
+            EnvelopeEntry ee = (EnvelopeEntry) e;
+            result = ee.remove(alias) || result;
           }
         else if (e instanceof PrimitiveEntry)
           {
-            if (((PrimitiveEntry) e).getAlias().equals(alias))
+            PrimitiveEntry pe = (PrimitiveEntry) e;
+            if (pe.getAlias().equals(alias))
               {
                 it.remove();
+                result = true;
               }
           }
       }
-    payload = null;
-    makeAliasList();
+    if (result)
+      {
+        log.finest("State before: " + this);
+        payload = null;
+        makeAliasList();
+        log.finest("State after: " + this);
+      }
+    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.
@@ -324,6 +361,7 @@

   protected void decodeEnvelope(DataInputStream in) throws IOException
   {
+    this.entries.clear();
     while (true)
       {
         int type = in.read();
@@ -372,27 +410,39 @@

   private void makeAliasList()
   {
-    if (entries.isEmpty())
-      return;
-    StringBuffer buf = new StringBuffer();
-    for (Iterator it = entries.iterator(); it.hasNext();)
+    log.entering(this.getClass().getName(), "makeAliasList");
+    if (! entries.isEmpty())
       {
-        Entry entry = (Entry) it.next();
-        if (entry instanceof EnvelopeEntry)
-          {
-            buf.append(((EnvelopeEntry) entry).getAliasList());
-          }
-        else if (entry instanceof PrimitiveEntry)
+        StringBuilder buf = new StringBuilder();
+        String aliasOrList;
+        for (Iterator it = entries.iterator(); it.hasNext();)
           {
-            buf.append(((PrimitiveEntry) entry).getAlias());
+            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
+              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(';');
+                }
+              }
           }
-        if (it.hasNext())
-          buf.append(';');
-      }
-    properties.put("alias-list", buf.toString());
-    if (containingEnvelope != null)
-      {
-        containingEnvelope.makeAliasList();
+        String aliasList = buf.toString();
+        properties.put("alias-list", aliasList);
+        log.finer("alias-list=[" + aliasList + "]");
+        if (containingEnvelope != null)
+          containingEnvelope.makeAliasList();
       }
+    log.exiting(this.getClass().getName(), "makeAliasList");
   }
 }
Index: GnuPrivateKeyring.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java,v
retrieving revision 1.2
diff -u -r1.2 GnuPrivateKeyring.java
--- GnuPrivateKeyring.java	3 May 2006 12:24:31 -0000	1.2
+++ GnuPrivateKeyring.java	20 May 2006 01:53:00 -0000
@@ -106,7 +106,6 @@
   public boolean containsPrivateKey(String alias)
   {
     log.entering(this.getClass().getName(), "containsPrivateKey", alias);
-
     boolean result = false;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -115,7 +114,6 @@
             result = true;
             break;
           }
-
     log.exiting(this.getClass().getName(), "containsPrivateKey",
                 Boolean.valueOf(result));
     return result;
@@ -124,17 +122,15 @@
   public Key getPrivateKey(String alias, char[] password)
       throws UnrecoverableKeyException
   {
-    log.entering(this.getClass().getName(), "getPrivateKey",
-                 new Object[] { alias, String.valueOf(password) });
-
+    log.entering(this.getClass().getName(), "getPrivateKey", alias);
     Key result = null;
     if (containsAlias(alias))
       {
         PasswordAuthenticatedEntry e1 = null;
-        PasswordEncryptedEntry e2 = null;
         for (Iterator it = get(alias).iterator(); it.hasNext();)
           {
             Entry e = (Entry) it.next();
+            log.finest("Entry: " + e);
             if (e instanceof PasswordAuthenticatedEntry)
               {
                 e1 = (PasswordAuthenticatedEntry) e;
@@ -142,6 +138,7 @@
               }
           }

+        log.finest("e1 = " + e1);
         if (e1 != null)
           {
             try
@@ -150,9 +147,11 @@
               }
             catch (Exception e)
               {
+                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();
@@ -171,6 +170,7 @@
                   }
                 catch (Exception e)
                   {
+                    log.throwing(this.getClass().getName(), "getPrivateKey", e);
                     throw new UnrecoverableKeyException("decryption failed");
                   }

@@ -186,31 +186,26 @@
               }
           }
       }
-
-    log.exiting(this.getClass().getName(), "getPrivateKey", result);
+    log.exiting(this.getClass().getName(), "getPrivateKey",
+                result == null ? "null" : result.getClass().getName());
     return result;
   }

   public void putPrivateKey(String alias, Key key, char[] password)
   {
     log.entering(this.getClass().getName(), "putPrivateKey",
-                 new Object[] { alias, key, String.valueOf(password) });
-
+                 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);
+
+        log.finest("About to encrypt the key...");
         PasswordEncryptedEntry enc;
         enc = new PasswordEncryptedEntry(cipher, mode, keylen, new Properties());
         enc.add(pke);
-
-        PasswordAuthenticatedEntry auth;
-        auth = new PasswordAuthenticatedEntry(mac, maclen, new Properties());
-        auth.add(enc);
-
-        log.finest("About to encrypt the key...");
         try
           {
             enc.encode(null, password);
@@ -218,11 +213,14 @@
         catch (IOException x)
           {
             log.log(Level.FINER, "Exception while encrypting the key. "
-                    + "Rethrow as IllegalArgumentException", x);
+                                 + "Rethrow as IllegalArgumentException", x);
             throw new IllegalArgumentException(x.toString());
           }

         log.finest("About to authenticate the encrypted key...");
+        PasswordAuthenticatedEntry auth;
+        auth = new PasswordAuthenticatedEntry(mac, maclen, new Properties());
+        auth.add(enc);
         try
           {
             auth.encode(null, password);
@@ -230,7 +228,7 @@
         catch (IOException x)
           {
             log.log(Level.FINER, "Exception while authenticating the encrypted "
-                    + "key. Rethrow as IllegalArgumentException", x);
+                                 + "key. Rethrow as IllegalArgumentException", x);
             throw new IllegalArgumentException(x.toString());
           }

@@ -245,7 +243,6 @@
   public boolean containsPublicKey(String alias)
   {
     log.entering(this.getClass().getName(), "containsPublicKey", alias);
-
     boolean result = false;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -254,7 +251,6 @@
             result = true;
             break;
           }
-
     log.exiting(this.getClass().getName(), "containsPublicKey",
                 Boolean.valueOf(result));
     return result;
@@ -263,7 +259,6 @@
   public PublicKey getPublicKey(String alias)
   {
     log.entering(this.getClass().getName(), "getPublicKey", alias);
-
     PublicKey result = null;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -275,16 +270,15 @@
               break;
             }
         }
-
-    log.exiting(this.getClass().getName(), "getPublicKey", result);
+    log.exiting(this.getClass().getName(), "getPublicKey",
+                result == null ? "null" : result.getClass().getName());
     return result;
   }

   public void putPublicKey(String alias, PublicKey key)
   {
     log.entering(this.getClass().getName(), "putPublicKey",
-                 new Object[] { alias, key });
-
+                 new Object[] { alias, key.getClass().getName() });
     if (! containsPublicKey(alias))
       {
         Properties p = new Properties();
@@ -300,7 +294,6 @@
   public boolean containsCertPath(String alias)
   {
     log.entering(this.getClass().getName(), "containsCertPath", alias);
-
     boolean result = false;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -309,7 +302,6 @@
             result = true;
             break;
           }
-
     log.exiting(this.getClass().getName(), "containsCertPath",
                 Boolean.valueOf(result));
     return result;
@@ -318,7 +310,6 @@
   public Certificate[] getCertPath(String alias)
   {
     log.entering(this.getClass().getName(), "getCertPath", alias);
-
     Certificate[] result = null;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -330,7 +321,6 @@
               break;
             }
         }
-
     log.exiting(this.getClass().getName(), "getCertPath", result);
     return result;
   }
@@ -339,7 +329,6 @@
   {
     log.entering(this.getClass().getName(), "putCertPath",
                  new Object[] { alias, path });
-
     if (! containsCertPath(alias))
       {
         Properties p = new Properties();
@@ -354,28 +343,23 @@

   protected void load(InputStream in, char[] password) throws IOException
   {
-    log.entering(this.getClass().getName(), "load",
-                 new Object[] { in, String.valueOf(password) });
-
+    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);
-
+    keyring = PasswordAuthenticatedEntry.decode(new DataInputStream(in),
+                                                password);
     log.exiting(this.getClass().getName(), "load");
   }

   protected void store(OutputStream out, char[] password) throws IOException
   {
-    log.entering(this.getClass().getName(), "store",
-                 new Object[] { out, String.valueOf(password) });
-
+    log.entering(this.getClass().getName(), "store");
     out.write(USAGE);
     keyring.encode(new DataOutputStream(out), password);
-
     log.exiting(this.getClass().getName(), "store");
   }
 }
Index: GnuPublicKeyring.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/GnuPublicKeyring.java,v
retrieving revision 1.2
diff -u -r1.2 GnuPublicKeyring.java
--- GnuPublicKeyring.java	3 May 2006 12:24:31 -0000	1.2
+++ GnuPublicKeyring.java	20 May 2006 01:53:46 -0000
@@ -78,7 +78,6 @@
   public boolean containsCertificate(String alias)
   {
     log.entering(this.getClass().getName(), "containsCertificate", alias);
-
     boolean result = false;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -87,7 +86,6 @@
             result = true;
             break;
           }
-
     log.exiting(this.getClass().getName(), "containsCertificate",
                 Boolean.valueOf(result));
     return result;
@@ -96,7 +94,6 @@
   public Certificate getCertificate(String alias)
   {
     log.entering(this.getClass().getName(), "getCertificate", alias);
-
     Certificate result = null;
     if (containsAlias(alias))
       for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -108,7 +105,6 @@
               break;
             }
         }
-
     log.exiting(this.getClass().getName(), "getCertificate", result);
     return result;
   }
@@ -117,7 +113,6 @@
   {
     log.entering(this.getClass().getName(), "putCertificate",
                  new Object[] { alias, cert });
-
     if (! containsCertificate(alias))
       {
         Properties p = new Properties();
@@ -132,9 +127,7 @@

   protected void load(InputStream in, char[] password) throws IOException
   {
-    log.entering(this.getClass().getName(), "load",
-                 new Object[] { in, String.valueOf(password) });
-
+    log.entering(this.getClass().getName(), "load");
     if (in.read() != USAGE)
       throw new MalformedKeyringException("incompatible keyring usage");

@@ -143,18 +136,14 @@

     DataInputStream dis = new DataInputStream(in);
     keyring = PasswordAuthenticatedEntry.decode(dis, password);
-
     log.exiting(this.getClass().getName(), "load");
   }

   protected void store(OutputStream out, char[] password) throws IOException
   {
-    log.entering(this.getClass().getName(), "store",
-                 new Object[] { out, String.valueOf(password) });
-
+    log.entering(this.getClass().getName(), "store");
     out.write(USAGE);
     keyring.encode(new DataOutputStream(out), password);
-
     log.exiting(this.getClass().getName(), "store");
   }
 }
Index: MaskableEnvelopeEntry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java,v
retrieving revision 1.1
diff -u -r1.1 MaskableEnvelopeEntry.java
--- MaskableEnvelopeEntry.java	26 Jan 2006 02:25:09 -0000	1.1
+++ MaskableEnvelopeEntry.java	20 May 2006 01:54:07 -0000
@@ -48,7 +48,6 @@
  */
 public abstract class MaskableEnvelopeEntry extends EnvelopeEntry
 {
-
   // Fields.
   // ------------------------------------------------------------------------

@@ -137,12 +136,19 @@
     return super.remove(entry);
   }

-  public void remove(String alias)
+  public boolean remove(String alias)
   {
     if (isMasked())
-      {
-        throw new IllegalStateException("masked envelope");
-      }
-    super.remove(alias);
+      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();
   }
 }
Index: PasswordAuthenticatedEntry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java,v
retrieving revision 1.2
diff -u -r1.2 PasswordAuthenticatedEntry.java
--- PasswordAuthenticatedEntry.java	7 May 2006 10:16:02 -0000	1.2
+++ PasswordAuthenticatedEntry.java	20 May 2006 02:26:13 -0000
@@ -146,11 +146,11 @@

   public void verify(char[] password)
   {
-    log.entering(this.getClass().getName(), "verify", String.valueOf(password));
-    long tt = - System.currentTimeMillis();
-
+    log.entering(this.getClass().getName(), "verify");
     if (isMasked() && payload != null)
       {
+        log.finest("payload to verify: " + Util.dumpString(payload));
+        long tt = - System.currentTimeMillis();
         IMac m = null;
         try
           {
@@ -169,6 +169,8 @@
         if (! Arrays.equals(macValue, m.digest()))
           throw new IllegalArgumentException("MAC verification failed");

+        setMasked(false);
+
         ByteArrayInputStream bais;
         try
           {
@@ -180,19 +182,18 @@
           {
             throw new IllegalArgumentException("malformed keyring fragment");
           }
-        setMasked(false);
-        payload = null;
-      }

-    tt += System.currentTimeMillis();
-    log.finer("Verified in " + tt + "ms.");
+        tt += System.currentTimeMillis();
+        log.finer("Verified in " + tt + "ms.");
+      }
+    else
+      log.finer("Skip verification; " + (isMasked() ? "null payload" : "unmasked"));
     log.exiting(this.getClass().getName(), "verify");
   }

   public void authenticate(char[] password) throws IOException
   {
-    log.entering(this.getClass().getName(), "authenticate",
-                 String.valueOf(password));
+    log.entering(this.getClass().getName(), "authenticate");
     long tt = - System.currentTimeMillis();
     long t1 = - System.currentTimeMillis();

@@ -218,7 +219,10 @@
         log.finer("-- Authenticated an Entry in " + t1 + "ms.");
       }
     bout.write(m.digest());
+
     payload = bout.toByteArray();
+    log.finest("authenticated payload: " + Util.dumpString(payload));
+    setMasked(true);

     tt += System.currentTimeMillis();
     log.finer("Authenticated in " + tt + "ms.");
@@ -235,6 +239,7 @@
   {
     if (payload == null)
       {
+        log.fine("Null payload: " + this);
         throw new IllegalStateException("mac not computed");
       }
   }
@@ -244,26 +249,25 @@

   private IMac getMac(char[] password) throws MalformedKeyringException
   {
-    if (!properties.containsKey("salt"))
-      {
-        throw new MalformedKeyringException("no salt");
-      }
-    byte[] salt = Util.toBytesFromString(properties.get("salt"));
-    IMac mac = MacFactory.getInstance(properties.get("mac"));
+    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: "
-                                            + properties.get("mac"));
-      }
-    int keylen = mac.macSize();
-    int maclen = 0;
-    if (!properties.containsKey("maclen"))
-      {
-        throw new MalformedKeyringException("no MAC length");
-      }
+      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(properties.get("maclen"));
+        maclen = Integer.parseInt(macLenString);
       }
     catch (NumberFormatException nfe)
       {
@@ -277,6 +281,7 @@
     IRandom kdf = PRNGFactory.getInstance("PBKDF2-HMAC-SHA");
     kdf.init(pbAttr);

+    int keylen = mac.macSize();
     byte[] dk = new byte[keylen];
     try
       {
@@ -298,6 +303,7 @@
       {
         throw new Error(shouldNotHappen.toString());
       }
+    log.exiting(this.getClass().getName(), "getMac");
     return mac;
   }
 }
Index: PasswordEncryptedEntry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java,v
retrieving revision 1.2
diff -u -r1.2 PasswordEncryptedEntry.java
--- PasswordEncryptedEntry.java	7 May 2006 10:16:03 -0000	1.2
+++ PasswordEncryptedEntry.java	20 May 2006 01:54:52 -0000
@@ -132,39 +132,40 @@
   public void decrypt(char[] password) throws IllegalArgumentException,
       WrongPaddingException
   {
-    log.entering(this.getClass().getName(), "decrypt", String.valueOf(password));
-    long tt = - System.currentTimeMillis();
+    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);

-    if (!isMasked() || payload == null)
-      return;
+        setMasked(false);

-    IMode mode = getMode(password, IMode.DECRYPTION);
-    IPad 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);
-    ByteArrayInputStream baos = new ByteArrayInputStream(buf, 0,
-                                                         buf.length - padlen);
-    DataInputStream in = new DataInputStream(baos);
-    try
-      {
-        decodeEnvelope(in);
-      }
-    catch (IOException ioe)
-      {
-        throw new IllegalArgumentException("decryption failed");
+        ByteArrayInputStream baos = new ByteArrayInputStream(buf, 0,
+                                                             buf.length - padlen);
+        DataInputStream in = new DataInputStream(baos);
+        try
+          {
+            decodeEnvelope(in);
+          }
+        catch (IOException ioe)
+          {
+            throw new IllegalArgumentException("decryption failed");
+          }
+        tt += System.currentTimeMillis();
+        log.finer("Decrypted in " + tt + "ms.");
       }
-    setMasked(false);
-    payload = null;
-
-    tt += System.currentTimeMillis();
-    log.finer("Decrypted in " + tt + "ms.");
+    else
+      log.finer("Skip decryption; " + (isMasked() ? "null payload" : "unmasked"));
     log.exiting(this.getClass().getName(), "decrypt");
   }

@@ -208,6 +209,8 @@
       }
     mode.update(lastBlock, 0, payload, count);

+    setMasked(true);
+
     tt += System.currentTimeMillis();
     log.finer("Encrypted in " + tt + "ms.");
     log.exiting(this.getClass().getName(), "encrypt");
@@ -223,6 +226,7 @@
   {
     if (payload == null)
       {
+        log.fine("Null payload: " + this);
         throw new IllegalStateException("not encrypted");
       }
   }
Index: PrivateKeyEntry.java
===================================================================
RCS file: /cvsroot/classpath/classpath/gnu/javax/crypto/keyring/PrivateKeyEntry.java,v
retrieving revision 1.2
diff -u -r1.2 PrivateKeyEntry.java
--- PrivateKeyEntry.java	13 Apr 2006 21:07:02 -0000	1.2
+++ PrivateKeyEntry.java	20 May 2006 01:55:16 -0000
@@ -42,12 +42,10 @@
 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.DataOutputStream;
 import java.io.IOException;
 import java.security.Key;
 import java.security.KeyFactory;
@@ -56,11 +54,11 @@
 import java.util.Date;

 /**
- * <p>An immutable class representing a private or secret key entry.</p>
+ * An immutable class representing a private or secret key entry.
  */
-public final class PrivateKeyEntry extends PrimitiveEntry
+public final class PrivateKeyEntry
+    extends PrimitiveEntry
 {
-
   // Constants and variables
   // -------------------------------------------------------------------------

@@ -73,7 +71,7 @@
   // -------------------------------------------------------------------------

   /**
-   * <p>Creates a new key entry.</p>
+   * Creates a new key entry.
    *
    * @param key The key.
    * @param creationDate The entry creation date.
@@ -85,13 +83,11 @@
     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");
-      }
+      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;
   }

@@ -109,9 +105,8 @@
     entry.defaultDecode(in);
     String type = entry.properties.get("type");
     if (type == null)
-      {
-        throw new MalformedKeyringException("no key type");
-      }
+      throw new MalformedKeyringException("no key type");
+
     if (type.equalsIgnoreCase("RAW-DSS"))
       {
         IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
@@ -128,42 +123,38 @@
         entry.key = coder.decodePrivateKey(entry.payload);
       }
     else if (type.equalsIgnoreCase("RAW"))
-      {
-        entry.key = new GnuSecretKey(entry.payload, null);
-      }
+      entry.key = new GnuSecretKey(entry.payload, null);
     else if (type.equalsIgnoreCase("PKCS8"))
       {
         try
           {
             KeyFactory kf = KeyFactory.getInstance("RSA");
-            entry.key = kf.generatePrivate(new PKCS8EncodedKeySpec(
-                                                                   entry.payload));
+            PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(entry.payload);
+            entry.key = kf.generatePrivate(ks);
           }
-        catch (Exception x)
+        catch (Exception ignored)
           {
           }
+
         if (entry.key == null)
           {
             try
               {
                 KeyFactory kf = KeyFactory.getInstance("DSA");
-                entry.key = kf.generatePrivate(new PKCS8EncodedKeySpec(
-                                                                       entry.payload));
+                PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(entry.payload);
+                entry.key = kf.generatePrivate(ks);
               }
-            catch (Exception x)
+            catch (Exception ignored)
               {
               }
+
             if (entry.key == null)
-              {
-                throw new MalformedKeyringException(
-                                                    "could not decode PKCS#8 key");
-              }
+              throw new MalformedKeyringException("could not decode PKCS#8 key");
           }
       }
     else
-      {
-        throw new MalformedKeyringException("unsupported key type " + type);
-      }
+      throw new MalformedKeyringException("unsupported key type " + type);
+
     return entry;
   }

@@ -171,7 +162,7 @@
   // -------------------------------------------------------------------------

   /**
-   * <p>Returns this entry's key.</p>
+   * Returns this entry's key.
    *
    * @return The key.
    */
@@ -212,8 +203,12 @@
         payload = key.getEncoded();
       }
     else
-      {
-        throw new IllegalArgumentException("unsupported private key");
-      }
+      throw new IllegalArgumentException("unsupported private key");
+  }
+
+  public String toString()
+  {
+    return "PrivateKeyEntry{key="
+        + (key == null ? "-" : key.getClass().getName()) + "}";
   }
 }

Attachment: pgpYkam9LwlQJ.pgp
Description: PGP signature

Reply via email to