actions
[jcryptoboard.git] / jcryptoboard-crypto / src / main / java / jcryptoboard / actions / rng / Random.java
blob5e24f035aa5f30b5d44f527f969ac1e9d3f32157
1 package jcryptoboard.actions.rng;
3 import java.security.NoSuchAlgorithmException;
4 import java.security.SecureRandom;
5 import jcryptoboard.api.model.AbstractAction;
6 import jcryptoboard.api.model.ActionResult;
7 import org.apache.commons.lang.mutable.MutableInt;
9 /**
10 * Created with IntelliJ IDEA.
11 * User: lhl
12 * Date: 18.10.12
13 * Time: 17:37
14 * To change this template use File | Settings | File Templates.
16 public class Random extends AbstractAction {
18 private java.util.Random rnd = new java.util.Random();
20 public void setSecure(String algo) {
21 try {
22 rnd = SecureRandom.getInstance(algo);
23 } catch (NoSuchAlgorithmException e) {
24 throw new IllegalArgumentException("Invalid SecureRandom algorithm: " + algo);
26 recompute();
29 private void recompute()
31 integer.setValue(rnd.nextInt());
32 rnd.nextBytes(array);
35 /**
36 * Updates buffers with new random values.
37 * @return
39 public ActionResult execute() throws Exception {
40 recompute();
41 return nextAction.execute();
44 private byte[] array = new byte[8];
45 private MutableInt integer = new MutableInt(0);
47 public Random() {
48 recompute();
52 /** Returns random integer */
53 public void setInteger(MutableInt integer) {
54 this.integer = integer;
57 /** Returns random integer */
58 public MutableInt getInteger() {
59 return integer;
62 /**
63 * Instructs action to provide array of random bytes of given length.
64 * @param length
66 public void setProvideArray(int length)
68 array = new byte[length];
71 public void setArray(byte[] array) {
72 if (array == null) {
73 throw new NullPointerException("Array buffer for Random must not be null.");
75 this.array = array;
78 /**
79 * Returns random bytes in array.
80 * By default 8 bytes are provided. This can by changed by calling setArray or setProvideArray.
82 public byte[] getArray() {
83 return array;
86 public String getName() {
87 return "Random";