#2 - Added test to test the cypto library

This commit is contained in:
Isaac Parenteau
2019-09-30 15:40:29 -05:00
parent 91f9f5a71e
commit f717d42ea8
8 changed files with 426 additions and 12 deletions

View File

@@ -0,0 +1,78 @@
package net.locusworks.crypto.utils;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.Random;
public class RandomString {
public static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
public static final String UPPER = LOWER.toUpperCase();
public static final String DIGITS = "0123456789";
public static final String ALPHA_NUMERIC = LOWER + UPPER + DIGITS;
private Random random;
private char[] symbols;
private int length;
private static RandomString instance;
private RandomString(Integer length) {
this(length, new SecureRandom());
}
private RandomString(Integer length, Random random) {
this(length, random, ALPHA_NUMERIC);
}
private RandomString(Integer length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException("Length has to be greater than 1");
if (symbols.length() < 2) throw new IllegalArgumentException("Symbols need to be greater than 2");
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
}
private synchronized final void setRandom(Random random) {
this.random = random;
}
private synchronized final void setLength(int length) {
this.length = length;
}
public String nextString() {
char[] buffer = new char[length];
for (int index = 0; index < buffer.length; index++) {
buffer[index] = symbols[random.nextInt(symbols.length)];
}
return new String(buffer);
}
public static String getString(Integer length) {
if (instance == null) {
instance = new RandomString(length);
}
instance.setLength(length);
return instance.nextString();
}
public static String getString(Integer length, Random random) {
if (instance == null) {
instance = new RandomString(length);
}
instance.setLength(length);
instance.setRandom(random);
return instance.nextString();
}
public static byte[] getBytes(Integer length) {
return getString(length).getBytes(StandardCharsets.UTF_8);
}
public static byte[] getBytes(Integer length, Random random) {
return getString(length, random).getBytes(StandardCharsets.UTF_8);
}
}