Wednesday, November 4, 2009

Getting Started


















































Getting Started



This chapter extends the Utils class so that it also includes an implementation of SecureRandom,
which will produce predictable output. Although this sounds insane from
a cryptographic point of view, it will make it a lot easier for me to
talk about the examples that use it, as you will be able to reproduce
the output exactly.


Here is the class:



package chapter4;

import java.security.MessageDigest;
import java.security.SecureRandom;

/**
* Utility class for chapter 4 examples
*/
public class Utils
extends chapter3.Utils
{
private static class FixedRand extends SecureRandom
{
MessageDigest sha;
byte[] state;

FixedRand()
{
try
{
this.sha = MessageDigest.getInstance("SHA-1", "BC");
this.state = sha.digest();
}
catch (Exception e)
{
throw new RuntimeException("can't find SHA-1!");
}
}

public void nextBytes(
byte[] bytes)
{
int off = 0;

sha.update(state);

while (off < bytes.length)
{
state = sha.digest();

if (bytes.length - off > state.length)
{
System.arraycopy(state, 0, bytes, off, state.length);
}
else
{

System.arraycopy(state, 0, bytes, off, bytes.length - off);
}

off += state.length;

sha.update(state);
}
}
}

/**
* Return a SecureRandom which produces the same value.
* <b>This is for testing only!</b>
* @return a fixed random
*/
public static SecureRandom createFixedRandom()
{
return new FixedRand();
}
}


As you can see, it just builds on the idea of using a message digest to generate a pseudorandom stream of bytes. Type the new Utils class in to start off the chapter4 package and you are ready to begin.








































No comments:

Post a Comment