Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Security

Encrypted Preferences in Java


Delegation

DelegatedPreferences is a class that implements each of the nine SPI methods by calling that same method on another AbstractPreferences object. That is, it delegates the implementation to another object. This is necessary to our encryption system because we want our encryption system to make use of a regular AbstractPreferences object. The advantage of this is that it only has to worry about the encryption— it delegates the rest of the work to another object. This greatly reduces the complexity of the EncryptionPreferences object. The DelegationPreferences object can be used in any other system that required this kind of limited modification to the preferences functionality. You'll find the source code to DelegatedPreferences in Listing Five.

Listing Five: The source for DelegatedPreferences, which is responsible for delegating SPI method calls to another Preferences object.
// $Id$

package ep;

import java.util.prefs.*;

public class DelegatedPreferences extends AbstractPreferences
{
  private AbstractPreferences target;
  static private final boolean verbose = false;

  protected DelegatedPreferences( AbstractPreferences parent, String name,
      AbstractPreferences target ) {
    super( parent, name );
    this.target = target;
  }

  protected String getSpi( String key ) {
    if (verbose) {
      System.out.println( "DP["+target+"]:getSpi( "+key+" )" );
    }

    return target.get( key, null );
  }

  protected void putSpi( String key, String value ) {
    if (verbose) {
      System.out.println( "DP["+target+"]:putSpi( "+key+", "+value+" )" );
    }

    target.put( key, value );
  }

  protected void removeSpi( String key ) {
    if (verbose) {
      System.out.println( "DP["+target+"]:removeSpi( "+key+" )" );
    }

    target.remove( key );
  }

  protected AbstractPreferences childSpi( String name ) {
    if (verbose) {
      System.out.println( "DP["+target+"]:chlidSpi( "+name+" )" );
    }

    return (AbstractPreferences)target.node( name );
  }

  protected void removeNodeSpi() throws BackingStoreException {
    if (verbose) {
      System.out.println( "DP["+target+"]:removeNode()" );
    }

    target.removeNode();
  }

  protected String[] keysSpi() throws BackingStoreException {
    if (verbose) {
      System.out.println( "DP["+target+"]:keysSpi()" );
    }

    return target.keys();
  }

  protected String[] childrenNamesSpi() throws BackingStoreException {
    if (verbose) {
      System.out.println( "DP["+target+"]:childrenNamesSpi()" );
    }

    return target.childrenNames();
  }

  protected void syncSpi() throws BackingStoreException {
    if (verbose) {
      System.out.println( "DP["+target+"]:sync()" );
    }

    target.sync();
  }


  protected void flushSpi() throws BackingStoreException {
    if (verbose) {
      System.out.println( "DP["+target+"]:flush()" );
    }

    target.flush();
  }
}
Wrapping

Wrapping is what ensures that a subnode of a DelegatingPreferences object is also a DelegatingPreferences object. For our purposes, this means that a subnode of an EncryptedPreferences object will also be an EncryptedPreferences object. "Wrapping" a preferences node really means creating a new node that delegates to it.

When the childSpi() method is called, it is responsible for finding and returning the child, or subnode, of the given node. In WrappedPreferences, childSpi() gets the new node, but before returning it, wraps it in another node. It does this by calling wrapChild().

If you look ahead to the source for EncryptedPreferences in Listing Eight, you'll see that it has the required implementation of wrapChild(), excerpted here:

public WrappedPreferences wrapChild(
    WrappedPreferences parent,
    String name,
    AbstractPreferences child ) {

  EncryptedPreferences ep =
    new EncryptedPreferences(
      parent,
      name,
      child );

  ep.setStuff( stuff );

  return ep;
}

Wrapping, of course, isn't just useful for the approaches used in this article— it can be used for any specialized Prefefences object that wants to be applied uniformly both to its own data and to the data of its subnodes. You'll find the source code to WrappedPreferences in Listing Six.

Listing Six: The source for WrappedPreferences, which is responsible for delegating SPI method calls to another Preferences object.
// $Id$

package ep;

import java.util.prefs.*;

abstract public class WrappedPreferences extends DelegatedPreferences
{
  protected WrappedPreferences( AbstractPreferences parent, String name,
      AbstractPreferences target ) {
    super( parent, name, target );
  }

  protected AbstractPreferences childSpi( String name ) {
    return wrapChild( this, name,
                      (AbstractPreferences)super.childSpi( name ) );
  }

  public WrappedPreferences wrapChild( WrappedPreferences parent,
                                              String name,
                                              AbstractPreferences child ) {
    throw new UnsupportedOperationException(
      "You must override WrappedPreferences.wrapChild()" );
  }
}
Obfuscation

Obfuscation is defined here as the process of modifying keys and values before storing them to the preferences database, and of unmodifying them when reading them back. To create an obfuscating preferences object, simply subclass ObfuscatedPreferences, and implement the following two methods:

public String obfuscateString( String string );
public String deObfuscateString( String string );

obfuscateString() alters a string so that its meaning is in some way hidden, and deObfuscatedString() reverses this process. It's crucial that deObfuscateString() knows how to reverse the obfuscation process on its own.

(Note that we don't obfuscate the names of subnodes. This is because node names are usually based on package names, and we want the preferences system to be able to find the nodes for our packages properly.)

Obfuscation doesn't have to be encryption— it could replace the string with some other value that may or may not be secret; it can translate to another language; reverse the characters; or anything, as long as its reversible. You'll find the source code to ObfuscatedPreferences in Listing Seven.

Listing Seven: The source for ObfuscatedPreferences, which modifies keys and values before writing them to the preferences database.
// $Id$

package ep;

import java.util.prefs.*;

public abstract class ObfuscatedPreferences extends WrappedPreferences
{
  protected ObfuscatedPreferences( AbstractPreferences parent, String name,
      AbstractPreferences target ) {
    super( parent, name, target );
  }

  protected String getSpi( String key ) {
    return deObfuscateString( super.getSpi( obfuscateString( key ) ) );
  }

  protected void putSpi( String key, String value ) {
    super.putSpi( obfuscateString( key ), obfuscateString( value ) );
  }

  protected void removeSpi( String key ) {
    super.removeSpi( obfuscateString( key ) );
  }

  protected String[] keysSpi() throws BackingStoreException {
    String keys[] = super.keysSpi();
    String dkeys[] = (String[])keys.clone();
    for (int i=0; i<dkeys.length; ++i) {
      dkeys[i] = deObfuscateString( dkeys[i] );
    }
    return dkeys;
  }

  abstract public String obfuscateString( String string );
  abstract public String deObfuscateString( String string );
}


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.