reuse SecureRandom instances

Initializing a new SecureRandom can block while waiting for entropy.
Reuse existing instances instead, which will never block for the default
provider (NativePRNG).

SecureRandom is threadsafe, and no two threads will see the same state.
This commit is contained in:
Niklas Fiekas 2018-05-08 02:24:27 +02:00
parent 89ee6cbb8f
commit f705721a6e
3 changed files with 12 additions and 25 deletions

View file

@ -54,14 +54,14 @@ private final class PasswordHasher(
import org.mindrot.BCrypt
import User.ClearPassword
private val prng = new SecureRandom()
private val aes = new Aes(secret)
private def bHash(salt: Array[Byte], p: ClearPassword) =
hashTimer(BCrypt.hashpwRaw(p.value.sha512, 'a', logRounds, salt))
def hash(p: ClearPassword): HashedPassword = {
val salt = new Array[Byte](16)
new SecureRandom().nextBytes(salt)
prng.nextBytes(salt)
HashedPassword(salt ++ aes.encrypt(Aes.iv(salt), bHash(salt, p)))
}

View file

@ -45,11 +45,13 @@ object TotpSecret {
// number of digits in token
private val digits = 6
private val secureRandom = new SecureRandom()
def apply(base32: String) = new TotpSecret(new Base32().decode(base32))
def random: TotpSecret = {
val secret = new Array[Byte](10)
new SecureRandom().nextBytes(secret)
secureRandom.nextBytes(secret)
apply(secret)
}

View file

@ -66,6 +66,8 @@ import java.util.Arrays;
* @version 0.4
*/
public final class BCrypt {
private static final SecureRandom PRNG = new SecureRandom();
// BCrypt parameters
private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private static final int BCRYPT_SALT_LEN = 16;
@ -724,12 +726,11 @@ public final class BCrypt {
* @param log_rounds the log2 of the number of rounds of
* hashing to apply - the work factor therefore increases as
* 2**log_rounds.
* @param random an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
public static String gensalt(int log_rounds) {
StringBuilder rs = new StringBuilder();
byte rnd[] = gensaltRaw(random);
byte rnd[] = gensaltRaw();
rs.append("$" + LATEST_VERSION + "$");
if (log_rounds < 10)
@ -744,26 +745,10 @@ public final class BCrypt {
return rs.toString();
}
public static byte[] gensaltRaw(SecureRandom random) {
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
return rnd;
}
public static byte[] gensaltRaw() {
return gensaltRaw(new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of
* hashing to apply - the work factor therefore increases as
* 2**log_rounds.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
return gensalt(log_rounds, new SecureRandom());
byte rnd[] = new byte[BCRYPT_SALT_LEN];
PRNG.nextBytes(rnd);
return rnd;
}
/**