Skip to content

Commit 7f41404

Browse files
committed
Improve the secure random function and fix issue #12
1 parent e77097b commit 7f41404

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

common/src/main/java/me/alexdevs/classicPeripherals/core/Crypto.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,20 @@ public static double secureRandom() {
114114
return random.nextDouble();
115115
}
116116

117+
public static double secureRandom(double max) {
118+
var random = new SecureRandom();
119+
if (max == 0d) {
120+
// mimics the behavior of the Lua random function
121+
return random.nextDouble(Long.MIN_VALUE, Long.MAX_VALUE);
122+
}
123+
return random.nextDouble(max);
124+
}
125+
126+
public static double secureRandom(double min, double max) {
127+
var random = new SecureRandom();
128+
return random.nextDouble(min, max);
129+
}
130+
117131
public static byte[] secureRandomBuffer(int length) {
118132
var random = new SecureRandom();
119133
var bytes = new byte[length];

common/src/main/java/me/alexdevs/classicPeripherals/peripherals/crypto/AbstractCryptographicAcceleratorPeripheral.java

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import dan200.computercraft.api.lua.IArguments;
44
import dan200.computercraft.api.lua.LuaException;
55
import dan200.computercraft.api.lua.LuaFunction;
6+
import dan200.computercraft.api.lua.LuaValues;
67
import dan200.computercraft.api.peripheral.IPeripheral;
78
import me.alexdevs.classicPeripherals.core.Crypto;
89
import me.alexdevs.classicPeripherals.utils.CryptoUtils;
@@ -62,17 +63,25 @@ public final String hmacSha512(String key, String data, Optional<Boolean> hex) {
6263

6364
@LuaFunction
6465
public final double random(IArguments args) throws LuaException {
65-
var value = Crypto.secureRandom();
66-
6766
if (args.count() == 0) { // 0.0 - 1.0
68-
return value;
67+
return Crypto.secureRandom();
6968
} else if (args.count() == 1) { // 0.0 - max
70-
var max = args.getInt(0);
71-
return Math.floor(value * max);
69+
var max = args.getFiniteDouble(0);
70+
71+
if (max < 0) {
72+
throw new LuaException("bad argument #1 (interval is empty)");
73+
}
74+
75+
return Crypto.secureRandom(max);
7276
} else { // min - max
73-
var min = args.getInt(0);
74-
var max = args.getInt(1);
75-
return Math.floor(value * max) + min;
77+
var min = args.getFiniteDouble(0);
78+
var max = args.getFiniteDouble(1);
79+
80+
if (max - min <= 0) {
81+
throw new LuaException("bad argument #1 (interval is empty)");
82+
}
83+
84+
return Crypto.secureRandom(min, max);
7685
}
7786
}
7887

0 commit comments

Comments
 (0)