Skip to content

Commit

Permalink
Fix lots of typos and minor bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickfav committed Mar 11, 2023
1 parent 3eac4df commit 2f3438b
Show file tree
Hide file tree
Showing 21 changed files with 103 additions and 108 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* update various dependencies
* update to github actions & sonaqube
* add OWASP dependency checker
* fix lots of typos and minor bugs

## v1.6.0
* use better implementations of Base64 and Hex encoder
Expand Down
106 changes: 53 additions & 53 deletions README.md

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions src/main/java/at/favre/tools/dice/RndTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ static void execute(Arg arguments) throws AppException {
throw new AppException("Count parameter must be greater than 0", 402);
}

if ((arguments.count() != null && (arguments.count() * (long) arguments.length() > MAX_BYTE_PER_CALL))
|| (long) arguments.length() > MAX_BYTE_PER_CALL) {
if ((arguments.count() != null && (arguments.count() * (long) arguments.length() > MAX_BYTE_PER_CALL))) {
throw new AppException("This PRNG can only generate " + MAX_BYTE_PER_CALL + " bytes at once.", 403);
} else {
arguments.length();
}

if (arguments.outFile() != null && arguments.outFile().getParentFile() != null
Expand Down Expand Up @@ -131,7 +132,7 @@ private static byte[] parseSeed(String seed) {
}
}

private static void wrapInErrorHandling(Arg arguments, Callable r) {
private static <T> void wrapInErrorHandling(Arg arguments, Callable<T> r) {
try {
r.call();
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,19 @@

package at.favre.tools.dice.rnd;

import org.jetbrains.annotations.Nullable;

/**
* A Deterministic Random Bit Generator as defined by NIST, will output
* pseudo random data depending on a given seed.
*/
public interface DeterministicRandomBitGenerator {

/**
* Requests a reseed of this DRBG. Uses the internal entropy sources,
* Requests a re-seed of this DRBG. Uses the internal entropy sources,
* provided through {@link DrbgParameter}
*
* @param additionalInfo optional parameter to increase the security cushion see NIST SP 800-90Ar1 Section 8.7.2
*/
void requestReseed(@Nullable byte[] additionalInfo);
void requestReseed(byte[] additionalInfo);

/**
* Get the next pseudo random data
Expand All @@ -47,5 +45,5 @@ public interface DeterministicRandomBitGenerator {
* @param additionalInfo can be null, additional information that is used to increase the security cushion,
* see NIST SP 800-90Ar1 Section 8.7.2
*/
void nextBytes(byte[] out, @Nullable byte[] additionalInfo);
void nextBytes(byte[] out, byte[] additionalInfo);
}
6 changes: 1 addition & 5 deletions src/main/java/at/favre/tools/dice/rnd/DrbgParameter.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package at.favre.tools.dice.rnd;

public class DrbgParameter {
private static final int MAX_BYTES_PER_SEED = 1024 * 1024 * 1024; //1 MiB - increasing this value wont't enhance bandwidth
private static final int MAX_BYTES_PER_SEED = 1024 * 1024 * 1024; //1 MiB - increasing this value won't enhance bandwidth

public final MacFactory macFactory;
public final int securityStrengthBit;
Expand All @@ -37,10 +37,6 @@ public DrbgParameter(MacFactory macFactory, ExpandableEntropySource entropySourc
this.reseedIntervalByte = reseedIntervalByte;
}

public DrbgParameter(MacFactory macFactory, ExpandableEntropySource entropySource, ExpandableEntropySource nonceSource, byte[] personalizationString, boolean reseedAllowed) {
this(macFactory, entropySource, nonceSource, personalizationString, reseedAllowed, MAX_BYTES_PER_SEED);
}

public DrbgParameter(MacFactory macFactory, ExpandableEntropySource entropySource, ExpandableEntropySource nonceSource, byte[] personalizationString) {
this(macFactory, entropySource, nonceSource, personalizationString, true, MAX_BYTES_PER_SEED);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/at/favre/tools/dice/rnd/EntropyPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public interface EntropyPool extends ExpandableEntropySource {
/**
* Add new entropy source to the pool
*
* @param source
* @param source to add
*/
void add(ExpandableEntropySource source);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package at.favre.tools.dice.rnd;

/**
* Interface for a entropy source with arbitrary length
* Interface for an entropy source with arbitrary length
*/
public interface ExpandableEntropySource {

Expand Down
29 changes: 14 additions & 15 deletions src/main/java/at/favre/tools/dice/rnd/HmacDrbg.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package at.favre.tools.dice.rnd;

import at.favre.lib.bytes.Bytes;
import org.jetbrains.annotations.Nullable;

import javax.crypto.Mac;
import java.util.Arrays;
Expand All @@ -26,21 +25,21 @@
* Deterministic Random Bit Generator based on any HMAC implementation available to {@link Mac}
* <p>
* Also known as: HMAC_DRBG.
* See http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf for thorough specification.
* See <a href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">NIST.SP.800-90Ar1</a> for thorough specification.
* <p>
* Reseeding and additional info is supported.
* <p>
* See http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf Section 8.6.8.
* See <a href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">NIST.SP.800-90Ar1</a> Section 8.6.8.
*/
public final class HmacDrbg implements DeterministicRandomBitGenerator {

// floor(7500/8); see: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf D.2 #5.
private static final int MAX_BYTES_PER_REQUEST = 937;
private static final byte[] BYTE_ARRAY_0 = {0};
private static final byte[] BYTE_ARRAY_1 = {1};
private final DrbgParameter paramter;
private final DrbgParameter parameter;

// "V" from the the spec.
// "V" from the spec.
private byte[] value;
// An instance of HMAC configured with "Key" from the spec.
private Mac hmac;
Expand All @@ -59,7 +58,7 @@ public final class HmacDrbg implements DeterministicRandomBitGenerator {
* @param drbgParameter parameter defining this DRBG
*/
public HmacDrbg(DrbgParameter drbgParameter) {
this.paramter = drbgParameter;
this.parameter = drbgParameter;

// HMAC_DRBG Instantiate Process
// See: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf 10.1.1.2
Expand Down Expand Up @@ -87,16 +86,16 @@ private byte[] generateSeedMaterial() {
// Note: We are using the 8.6.7 interpretation, where the entropy_input and
// nonce are acquired at the same time from the same source.
return Bytes.from(
paramter.entropySource.generateEntropy(getSecurityStrengthBytes()),
paramter.nonceSource.generateEntropy(getSecurityStrengthBytes() / 2),
paramter.personalizationString == null ? new byte[0] : paramter.personalizationString).array();
parameter.entropySource.generateEntropy(getSecurityStrengthBytes()),
parameter.nonceSource.generateEntropy(getSecurityStrengthBytes() / 2),
parameter.personalizationString == null ? new byte[0] : parameter.personalizationString).array();
}

/**
* Set's the "Key" state from the spec.
*/
private void initHmac(byte[] key) {
hmac = paramter.macFactory.create(key);
hmac = parameter.macFactory.create(key);
}

/**
Expand Down Expand Up @@ -125,8 +124,8 @@ private void hmacDrbgUpdate(byte[] providedData) {
* This uses the provided entropy sources as well as an optional additionalInfo
*/
@Override
public void requestReseed(@Nullable byte[] additionalInfo) {
hmacDrbgReseed(paramter.entropySource.generateEntropy(getSecurityStrengthBytes()), paramter.nonceSource.generateEntropy(getSecurityStrengthBytes() / 2), additionalInfo);
public void requestReseed(byte[] additionalInfo) {
hmacDrbgReseed(parameter.entropySource.generateEntropy(getSecurityStrengthBytes()), parameter.nonceSource.generateEntropy(getSecurityStrengthBytes() / 2), additionalInfo);
}

/**
Expand Down Expand Up @@ -180,10 +179,10 @@ private void hmacDrbgGenerate(byte[] out, int start, int count, byte[] additiona
/**
* Security Strength in Bits; depending on the used HMAC hash
*
* @return bit length
* @return a bit length
*/
private int getSecurityStrengthBytes() {
return paramter.securityStrengthBit / 8;
return parameter.securityStrengthBit / 8;
}

/**
Expand Down Expand Up @@ -220,7 +219,7 @@ private void generateBytesProcess(byte[] out, int start, int count, byte[] addit
hmacDrbgUpdate(additionalInput);
}

if (paramter.reseedAllowed && bytesGenerated + count > paramter.reseedIntervalByte) {
if (parameter.reseedAllowed && bytesGenerated + count > parameter.reseedIntervalByte) {
requestReseed(null);
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/at/favre/tools/dice/rnd/MacFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static MacFactory hmacSha512() {
* Creates a factory creating HMAC with SHA-1
*
* @return factory
* @deprecated sha1 with HMAC should be fine, but not recommended for new protocols; see https://crypto.stackexchange.com/questions/26510/why-is-hmac-sha1-still-considered-secure
* @deprecated sha1 with HMAC should be fine, but not recommended for new protocols; see <a href="https://crypto.stackexchange.com/questions/26510/why-is-hmac-sha1-still-considered-secure">why-is-hmac-sha1-still-considered-secure</a>
*/
@Deprecated
public static MacFactory hmacSha1() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

/**
* Threaded Seed Generator based on the one found in Bouncy Castle implementation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@

/**
* Used with external seeds that are estimated to be strong. The strong seed will
* used in quasi directly (only HKDF after each call will be preformed additional to
* adding an monotonic counter, to generate different outputs each call)
* be used in quasi directly (only HKDF after each call will be preformed additional to
* adding a monotonic counter, to generate different outputs each call)
*/
public final class ExternalStrongSeedEntropySource implements ExpandableEntropySource {
private static final byte[] SALT = new byte[]{0x57, 0x58, 0x6E, (byte) 0x9A, 0x7C, (byte) 0xE4, 0x2E, 0x57, 0x61, 0x07, 0x18, (byte) 0xD9, (byte) 0x90, (byte) 0xFE,
Expand All @@ -43,7 +43,7 @@ public ExternalStrongSeedEntropySource(byte[] seed) {
}

private void regenerateInternalSeed(byte[] seed) {
if (counter >= Long.MAX_VALUE) {
if (counter == Long.MAX_VALUE) {
throw new IllegalStateException("counter reached max value (2^64)");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

/**
* This is a port of the Thread Seed Generator in SUN's SeedGenerator class.
* It use some faster timings which may make it less secure but the original
* It uses some faster timings which may make it less secure but the original
* implementation is awfully slow (min 250 ms per byte).
* <p>
* This is the fallback if neither the personalization nor the secureRandom
Expand Down Expand Up @@ -58,7 +58,7 @@ private static class ThreadedSeedGenerator implements Runnable {
// data and using it to mix the trivial permutation.
// It should be evenly distributed. The specific values
// are not crucial to the security of this class.
private static byte[] rndTab = {
private static final byte[] rndTab = {
56, 30, -107, -6, -86, 25, -83, 75, -12, -64,
5, -128, 78, 21, 16, 32, 70, -81, 37, -51,
-43, -46, -108, 87, 29, 17, -55, 22, -11, -111,
Expand Down Expand Up @@ -89,7 +89,7 @@ private static class ThreadedSeedGenerator implements Runnable {
// Thread group for our threads
ThreadGroup seedGroup;
// Queue is used to collect seed bytes
private byte[] pool;
private final byte[] pool;
private int start, end, count;

/**
Expand Down Expand Up @@ -190,7 +190,7 @@ void getSeedBytes(byte[] result) {
}

byte getSeedByte() {
byte b = 0;
byte b;

try {
// Wait for it...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@

/**
* Nonce generate as described in SP800-90Ar1. This implementation uses a monotonic sequence number
* starting with the VM uptime time in millis and the current nano second timestamp
* starting with the VM uptime time in millis and the current nanosecond timestamp
* <p>
* See http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf Section 8.6.7.
* See <a href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">NIST.SP.800-90Ar1</a> Section 8.6.7.
*/
public final class NonceEntropySource implements ExpandableEntropySource {
private static final byte[] SALT = new byte[]{0x48, (byte) 0xB8, (byte) 0x96, (byte) 0xC6, (byte) 0x87, 0x5C, (byte) 0xD0, (byte) 0xF9, (byte) 0x9D,
Expand All @@ -44,7 +44,7 @@ public NonceEntropySource() {

@Override
public byte[] generateEntropy(int lengthByte) {
if (sequenceCounter >= Long.MAX_VALUE) {
if (sequenceCounter == Long.MAX_VALUE) {
throw new IllegalStateException("sequence counter reached max value (2^64)");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ private byte[] readTempDirContent() {

try (DirectoryStream<Path> stream = Files.newDirectoryStream(f.toPath())) {
// We use a Random object to choose what file names
// should be used. Otherwise on a machine with too
// should be used. Otherwise, on a machine with too
// many files, the same first 1024 files always get
// used. Any, We make sure the first 512 files are
// used. Anyway,we make sure the first 512 files are
// always used.
Random r = new Random();
for (Path entry : stream) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public interface ServiceHandler<T> {
Single<Result<T>> asObservable();

/**
* Get the user friendly and readable name for this service
* Get the user-friendly and readable name for this service
*
* @return name
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
* ANU Quantum Random Numbers Server
* Quantum true random number generator from Australian university
* <p>
* See https://qrng.anu.edu.au/
* See <a href="https://qrng.anu.edu.au/">qrng.anu.edu.au</a>
*/
public final class AnuQuantumServiceHandler extends AServiceHandler {
static final int ENTROPY_SEED_LENGTH_BYTE = 24;
Expand All @@ -58,7 +58,7 @@ public Result<AnuQuantumResponse> getRandom() {

try {
Response<AnuQuantumResponse> response = service.getRandom(createHeaderMap(), ENTROPY_SEED_LENGTH_BYTE).execute();
if (response != null && response.isSuccessful() && response.body() != null) {
if (response.isSuccessful() && response.body() != null) {
byte[] rawResponse = Bytes.parseHex(response.body().data.get(0)).array();
return new Result<>(getName(), rawResponse, response.body(), Duration.between(startTime, Instant.now()).toNanos());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public Result<RandomOrgBlobResponse> getRandom() {
final RandomOrgBlobRequest randomOrgBlobRequest = new RandomOrgBlobRequest(new RandomOrgBlobRequest.Params(k, 1, ENTROPY_SEED_LENGTH_BIT));

Response<String> response = service.getRandom(createHeaderMap(), randomOrgBlobRequest).execute();
if (response != null && response.isSuccessful() && response.body() != null) {
if (response.isSuccessful() && response.body() != null) {
String rawResponse = response.body();
RandomOrgBlobResponse orgBlobResponse = new Gson().fromJson(rawResponse, RandomOrgBlobResponse.class);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
/**
* Util for verifying the signature format of random.org's signed request
* <p>
* See https://api.random.org/verify/manual
* See <a href="https://api.random.org/verify/manual">api.random.org</a>
*/
final class RandomOrgUtil {
static final String RANDOM_ORG_PUB_KEY =
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/at/favre/tools/dice/ui/CLIParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private static Options setupOptions() {
Options options = new Options();

Option count = Option.builder(ARG_COUNT).longOpt("count").argName("number").desc("How many randoms should be generated. Automatically chosen if this argument is omitted.").hasArgs().build();
Option encodeing = Option.builder(ARG_ENCODING).longOpt("encoding").argName("string").hasArgs().desc("Output byte-to-text encoding. Available encodings include:\n" + new EncoderHandler().getSupportedEncodingList()).build();
Option encoding = Option.builder(ARG_ENCODING).longOpt("encoding").argName("string").hasArgs().desc("Output byte-to-text encoding. Available encodings include:\n" + new EncoderHandler().getSupportedEncodingList()).build();
Option seed = Option.builder(ARG_SEED).longOpt("seed").argName("string|number").hasArgs().desc("Uses either the 64-bit integer interpretation or the utf-8 byte representation of given parameter to seed the internal random generator. Warns if entropy is low.").build();
Option debugOpt = Option.builder(ARG_DEBUG).longOpt("debug").hasArg(false).desc("Prints additional info for debugging.").build();
Option onlineOpt = Option.builder(ARG_ONLINE).longOpt("offline").hasArg(false).desc("Skips request to external random generators (random.org) for seeding (use when offline).").build();
Expand All @@ -136,7 +136,7 @@ private static Options setupOptions() {
OptionGroup mainArgs = new OptionGroup();

options.addOptionGroup(mainArgs);
options.addOption(count).addOption(encodeing)
options.addOption(count).addOption(encoding)
.addOption(seed).addOption(onlineOpt)
.addOption(anuQuantumOpt)
.addOption(urlencodeOpt).addOption(paddingOpt)
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/at/favre/tools/dice/ui/ColumnRenderer.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ColumnRenderer(EncoderFormat encoderFormat, RandomGenerator randomGenerat
/**
* Will take a list and a target count and tries to create even columns
*
* @param targetCount approximate count you want to render (may be filled by the auto algorithm)
* @param targetCount approximate count you want to render (maybe filled by the auto algorithm)
* @param outStream to write the output to
* @return the actual used count
*/
Expand Down Expand Up @@ -128,7 +128,7 @@ public long render(long count, PrintStream outStream, boolean toFile) {
}

} else {
outStream.write(encoderFormat.asBytes(toFile ? encoderFormat.separatorFile() : encoderFormat.separatorFile()));
outStream.write(encoderFormat.asBytes(encoderFormat.separatorFile()));
}
} catch (Exception e) {
throw new IllegalStateException("could not write random to output stream", e);
Expand Down
Loading

0 comments on commit 2f3438b

Please sign in to comment.