Example: Obfuscating data

This example demonstrates a technique for obfuscating data in a database. The purpose of obfuscation is to make the data unrecognizable if it was simply displayed; it is not the same as encryption, which also has the property that there is a fair chance that the data cannot be decrypted, even when sophisticated tools are employed.

 To run the Obfuscate.java example
  1. Change to the following directory: samples-dir\UltraLiteJ.

    For information about the default location of samples-dir, see Samples directory.

  2. Run the following command (the command is case sensitive):

    rundemo Obfuscate


// *****************************************************
// Copyright (c) 2006-2010 iAnywhere Solutions, Inc.
// Portions copyright (c) 2006-2010 Sybase, Inc.
// All rights reserved. All unpublished rights reserved.
// *****************************************************
// This sample code is provided AS IS, without warranty or liability
// of any kind.
//
// You may use, reproduce, modify and distribute this sample code
// without limitation, on the condition that you retain the foregoing
// copyright notice and disclaimer as to the original iAnywhere code.
//
// *********************************************************************
package com.ianywhere.ultralitej.demo;

import com.ianywhere.ultralitej12.*;

/**
 * Obfuscate -- sample program to a possible obfuscation of the database.
 *
 * Obfuscation is not very good encryption.  It merely makes the data unreadable
 * with a file dumping program.  The original data can be probably recovered by
 * someone with knowledge of the algorithms used.
 */
public class Obfuscate
{
    /** Create the database.
     * @return connection for a new database
     */
    private static Connection createDatabase()
    	throws ULjException
    {
	ConfigPersistent config = DatabaseManager.createConfigurationFile( "Obfuscate.ulj" );
	config.setEncryption( new Obfuscator() );
	Connection conn = DatabaseManager.createDatabase( config );

	PreparedStatement ps = conn.prepareStatement(
		"CREATE TABLE Product" +
		"( prod_no INT NOT NULL PRIMARY KEY" +
		", prod_name VARCHAR(32)" +
		", price NUMERIC(9,2)" +
		")"
		);
	ps.execute();
	ps.close();

	return conn;
    }

    /** Add a product row.
     * @param ri PreparedStatement for the Product table
     * @param prod_no product number
     * @param prod_name product name
     * @param price selling price
     */
    private static void addProduct( PreparedStatement ri, int prod_no, String prod_name, String price )
    	throws ULjException
    {
	ri.set( "prod_no", prod_no );
	ri.set( "prod_name", prod_name );
	ri.set( "price", price );
	ri.execute();
    }

    /** Populate the database.
     * @param conn connection to database
     */
    private static void populate( Connection conn )
    	throws ULjException
    {
	PreparedStatement ri = conn.prepareStatement(
		"INSERT INTO Product( prod_no, prod_name, price )"
		+ " VALUES( :prod_no, :prod_name, :price )"
	    );
	addProduct( ri, 2001, "blue screw", ".03" );
	addProduct( ri, 2002, "red screw", ".09" );
	addProduct( ri, 2004, "hammer", "23.99" );
	addProduct( ri, 2005, "vise", "39.99" );
	ri.close();
	conn.commit();
    }

    /** Display contents of Product table.
     * @param conn connection to database
     */
    private static void displayProducts( Connection conn )
    	throws ULjException
    {
	PreparedStatement stmt = conn.prepareStatement(
		"SELECT prod_no, prod_name, price FROM Product"
		+ " ORDER BY prod_no"
	    );
	ResultSet cursor = stmt.executeQuery();
	for( ; cursor.next(); ) {
	    String prod_no = cursor.getString( 1 /* "prod_no" */ );
	    String prod_name = cursor.getString( "prod_name" );
	    String price = cursor.getString( 3 /* "price" */ );
	    Demo.display( prod_no + " " + prod_name + " " + price );
	}
	cursor.close();
	stmt.close();
    }

    /** mainline for program.
     * @param args command-line arguments (not used)
     */
    public static void main
	( String[] args )
    {
	try {
	    Connection conn = createDatabase();
	    populate( conn );
	    displayProducts( conn );
	    conn.release();
	} catch( ULjException exc ) {
	    Demo.displayException( exc );
	}
    }

    /** Class to implement encryption/decryption of the database.
     */
    static class Obfuscator
    	implements EncryptionControl
    {
	/** seed for obfuscator		*/	private int _seed;

	/** (un)Obfuscate a page.
	 * @param page_no the number of the page being encrypted
	 * @param src the encrypted source page which was read from the database
	 * @param tgt the unencrypted page (filled in by method)
	 * @param num_bytes The number of bytes to decrypt.  This is always
	 *          either the page size or 128.
	 */
	private void transform( int page_no, byte[] src, byte[] tgt, int num_bytes )
	{
	    int seed = ( _seed + page_no ) % 256;
	    for( int i = 0; i < num_bytes; ++i ) {
		tgt[ i ] = (byte)( seed ^ src[ i ] );
		seed = ( seed + 93 ) % 256;
	    }
	}
	
	/** Encrypt a page stored in the database.
	 * @param page_no the number of the page being encrypted
	 * @param src the encrypted source page which was read from the database
	 * @param tgt the unencrypted page (filled in by method)
	 * @param num_bytes The number of bytes to decrypt.  This is always
	 *          either the page size or 128.
	 */
	public void decrypt( int page_no, byte[] src, byte[] tgt, int num_bytes )
	    throws ULjException
	{
	    transform( page_no, src, tgt, num_bytes );
	}
    
	/** Encrypt a page stored in the database.
	 * @param page_no the number of the page being encrypted
	 * @param src the unencrypted source
	 * @param tgt the encrypted target page which will be written to the database (filled in by method)
	 */
	public void encrypt( int page_no, byte[] src, byte[] tgt )
	    throws ULjException
	{
	    transform( page_no, src, tgt, tgt.length );
	}
    
	/** Initialize the encryption control with a password.
	 * @param password the password
	 */
	public void initialize( String password )
	    throws ULjException
	{
	    byte[] bytes = null;
	    try {
		bytes = password.getBytes( "UTF8" );
	    } catch( Exception e ) {
		Demo.display( "Encryption initialization failure" );
		throw new ObfuscationError();
	    }
	    _seed = 0;
	    for( int i = bytes.length; i > 0; ) {
		_seed ^= bytes[ --i ];
	    }
	}
    }

    /** Error class for encryption errors.
     */
    static class ObfuscationError
    	extends ULjException
    {
	/** Constructor.
	 */
	ObfuscationError()
	{
	    super( "Obfuscation Error" );
	}

	/**
	 * Get the error code, associated with this exception.
	 * @return the error code (from the list at the top of this class) associated
	 *  with this exception
	 */
	public int getErrorCode()
	{
	    return ULjException.SQLE_ERROR;
	}
    
	/** Get exception causing this exception, if it exists.
	 * @return null, if there exists no causing exception; otherwise, the exception causing this exception
	 */
	public ULjException getCausingException()
	{
	    return null;
	}

	/** Get offset of error within a SQL string.
	 * @return (-1) when there is no SQL string associated with the error message; otherwise,
	 * the (base 0) offset within that string where the error occurred.
	 */
	public int getSqlOffset()
	{
	    return -1;
	}
    }
}