I know that if we declare:
SecureRandom random=new SecureRandom();
It initializes the default algorithm to generate random number is NativePRNG which reads /dev/random to generate the truly random seed. Now we have truly random seed which is 160 bit size, but i am confused what happens when we call random.nextBytes(bytes);. How it generates bytes from the seed,does it again read the /dev/random or something else.
Thanks.
N.B.: i am looking for default behavior in java 7 in linux/MAC box.
From the Java API docs:
Many SecureRandom implementations are in the form of a pseudo-random
number generator (PRNG), which means they use a deterministic
algorithm to produce a pseudo-random sequence from a true random seed.
Other implementations may produce true random numbers, and yet others
may use a combination of both techniques.
So whether nextBytes(bytes) returns true random bytes from /dev/random or whether it returns pseudo-random numbers generated from the true random seed depends. The second case means that using the initially random seed, a deterministic but seemingly random (and hence, pseudo-random) number sequence is generated by any calls to the SecureRandom.
Java 7 allows for a configurable PRNG source to be specified, but on Linux the default one is NativePRNG and on Windows SHA1PRNG. You can also specify SHA1PRNG on Linux, but the default option of NativePRNG is better. The SHA1PRNG generates PRNG bits and bytes through the use of SHA1. On Linux (and possibly other Unixes, where the mechanism is "NativePRNG"), the algorithm reads from /dev/random and /dev/urandom, so as long as there is enough entropy available through either of those. For the sake of completeness, from the Linux man page on random:
A read from the /dev/urandom device will not block waiting for more
entropy. As a result, if there is not sufficient entropy in the
entropy pool, the returned values are theoretically vulnerable to a
cryptographic attack on the algorithms used by the driver.
Therefore, on Linux at least, your SecureRandom will have a certain amount of true random output until /dev/random blocks due to a shortage of entropy, however if you request too many random bits, they will eventually start being generated by the underlying /dev/urandom machinery, which may use SHA1 or some other cryptographic hashing algorithm in a PRNG.
It's best to create a SecureRandom without specifying any explicit seed yourself, as it will seed itself (by default via /dev/random and /dev/urandom for the NativePRNG on Linux) with a good seed. Calling nextBytes(bytes) every few minutes, even for a large amount of bytes, is not bound to be an issue in almost any circumstance. Even if you are using the NativePRNG and it resorts to getting pseudo-random bytes from /dev/urandom via something like SHA-1, the output of this will still be extremely difficult to predict.
If you are asking for gigabytes of randomness, it might be good to re-seed, either using some output from the SecureRandom itself or by providing your own seed. Note that it should be safe providing any kind of seed to setSeed(), as SecureRandom internally augments the current seed by feeding the seed you provide and the previous seed to something like SHA-1 or another cryptographic hashing algorithm. However, it is still best to create the initial SecureRandom without giving your own seed.
Related
I have written a code that is able to generate 2048 bit prime p & q's and use that to encrypt messages in RSA. The way I generate these numbers is by using the java.math.BigInteger package's probablePrime() function. My question is how strong of an encryption these function generated prime numbers are in terms of encryption.
Here is my code for generating these numbers, isPrime is just a boolean function I wrote to check if the number is prime.
BigInteger definitePrime(int bits, Random rnd) {
BigInteger prime = new BigInteger("4");
while (!isPrime (prime)) {
prime = BigInteger.probablePrime(bits, rnd);
}
return prime;
}
As Stephen C points out in his answer, the primes are probably ok for RSA encryption.
Cryptographic randomness
I would add, that you shouldn't actually use any Random instance, but only your systems best SecureRandom implementation.
new Random() is not a cryptographic randomness source, whereas new SecureRandom() should be. If the random numbers that are used for prime generation are not cryptographically secure, then an attacker may have a chance to simply recreate those based on other information (such as time or previous outputs of the weak randomness source).
No Textbook RSA
You're doing "everything" yourself and it seems that you actually want to use this for serious encryption. If you are, you're missing something crucial and that is the padding scheme.
It is easy to use the BigInteger methods to implement RSA so that it works, but it's not enough to make it secure. You need to use a padding scheme like PKCS#1 v1.5 (not recommended anymore) or PKCS#1 v2 OAEP (recommended).
Use existing implementations
Instead of implementing those padding schemes for your "handmade" RSA, use Java's Cipher instance which provides RSA with those padding schemes:
RSA/ECB/PKCS1Padding
RSA/ECB/OAEPWithSHA-256AndMGF1Padding
The javadoc for BigInteger.probablePrime() says:
Returns a positive BigInteger that is probably prime, with the specified bitLength. The probability that a BigInteger returned by this method is composite does not exceed 2-100.
2-100 means one chance in 1,267,650,600,228,229,401,496,703,205,376; i.e. 1 chance in ~1.267 * 1030
Since you are trying to generating 2 primes, that means that you have 2 chances in roughly 1030 of generating a weak RSA key pair.
I'd have thought that that was good enough, but if you don't think so then you could use BigInteger.isProbablePrime(certainty) to test your prime candidates to an even higher level of certainty.
My question is how strong of an encryption these function generated prime numbers are in terms of encryption.
I don't know if there is a mathematically rigorous way to quantify the strength of an encryption algorithm. But the above analysis tells you the probability that a given generated key-pair will be weak / easy to crack.
The generated primes are not secure if you use something like java.util.Random instead of an instance of SecureRandom. Your code snippet does not tell us what you are using, hence it is not possible to validate your code. Of course, you probably should just use JCE to generate new RSA keys.
I have read that, generally, some implementations of SecureRandom may produce true random numbers.
In particular, the Android docs say
instances of this class will generate an initial seed using an internal entropy source, such as /dev/urandom
but does that mean it will produce true random numbers (i.e., rather than pseudo-random numbers)?
And if I use SecureRandom in Android in this manner...
SecureRandom sr = new SecureRandom();
...will I get a truly random output whenever I call sr.nextBoolean()?
Or is the output likely to be more (or less?) random if I, instead, obtain output by doing this each time:
new SecureRandom().nextBoolean()?
"True" and "pseudorandom" random numbers mean a lot of different things to different people. It's best to avoid those.
/dev/urandom got a bad rep because people do not understand the differences between it and /dev/random (much, much less difference than you would expect).
If you're asking whether seeding by /dev/urandom might compromise the fitness of SecureRandom to use it for cryptographic purposes, the answer is a resounding "no".
If you've got some time you might want to read my essay about the whole issue.
According to the Android Developer Docs:
(SecureRandom) complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1
However, the same caveats apply to Android as to Java:
Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.
So, the short answer is: it depends on the implementation, but if you're ok with FIPS 140-2, then SecureRandom is legally sufficient for your purposes.
The key answer is that /dev/urandom, as defined by the linux kernel, is guaranteed not to block. The emphasis being upon not stalling the user while sufficient entropy is generated. If the android docs say they are using /dev/urandom to initialize, AND there is insufficient entropy in the kernel to supply random numbers, the kernel will fall back to a pseudo-random algorithm.
Per the kernel documentation, /dev/urandom is considered sufficient for almost all purposes except "long lived [encryption] keys". Given the description of your intended use, I suspect android SecureRandom will prove to be random enough for your purposes.
While doing a beginner's crypto course I'm trying to get to grips with Java's SecureRandom object. What I think I understand is that:
a) No matter how long a sequence of random numbers you know, there is no way of predicting the next random number in the sequence.
b) No matter how long a sequence of random numbers you know, there is no way of knowing which seed was used to start them off, other than brute force guesswork.
c) You can request secure random numbers of various sizes.
d) You can seed a newly-created SRNG with various different-sized values. Every newly-created SRNG you create and seed with the same value will produce the same sequence of random numbers.
I should add that I'm assuming that this code is used on Windows:
Random sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
Is my basic understanding correct? Thanks in advance.
I have some further questions for anyone who's reasonably expert in crypto. They relate to seeding a SRNG as opposed to letting it seed itself on first use.
e) What difference, if any, does it make to the random numbers generated, if you seed a SRNG with a long integer as opposed to an array of 8 bytes?
f) If I seed a SRNG with, say, 256 bytes is there any other seed that can produce the same sequence of random numbers?
g) Is there some kind of optimum seed size? It seems to me that this might be a meaningless question.
h) If I encrypt a plaintext by seeding a SRNG with, say, 256 bytes then getting it to generate random bytes to XOR with the bytes in the plaintext, how easy would it be for an eavesdropper to decrypt the resulting ciphertext? How long might it take? Am I right in thinking that the eavesdropper would have to know, guess, or calculate the 256-byte seed?
I've looked at previous questions about SecureRandom and none seem to answer my particular concerns.
If any of these questions seem overly stupid, I'd like to reiterate that I'm very much a beginner in studying this field. I'd be very grateful for any input as I want to understand how Java SecureRandom objects might be used in cryptography.
d) This is true for a PRNG. It is not always true for a CSRNG. Read the Javadoc for SecureRandom.setSeed(): "The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness."
Any reasonable CSRNG will have "invisible" sources of entropy that you cannot explicitly control, often various internal parameters taken from the Operating System level. Hence there is more seeding than any number you explicitly pass to the RNG.
OK, in order:
a) correct
b) correct
c) correct, you can even request a number in a range [0, n) using nextInt(n)
d) as good as correct: the implementation of SHA1PRNG is not publicly defined by any algorithm and there are indications that the implementation has changed in time, so this is only true for the Sun provider, and then only for a specific runtime configuration
e) as the API clearly indicates that all the bytes within the long are used ("using the eight bytes contained in the given long seed") there should not be any difference regarding the amount of entropy added to the state
Note that a quick check shows that setSeed(long) behaves entirely different from setSeed(byte[]) with the main difference that the seed of the long value is always mixed in with randomness retrieved from the system, even if it is the first call after the SecureRandom instance is constructed.
f) yes - an infinite number of seeds generate the same stream; since a hash function is used, it will be impossible to find one though
g) if you mix in additional entropy, then the more entropy the better, but there is no minimum; if you use it as the only seed then you should not start off with less than 20 bytes of seed, that is: if you want to keep the seed to the same security constraints as the inner state of the PRNG
And I would add that if you use less than 64 bytes of entropy you are in the danger zone for sure. Note that 1 bit of entropy does not always mean 1 bit in a byte. A byte array of size 8 may have 64 bits of entropy or less.
h) that's basically a hash based stream cipher; it's secure, so an attacker has little to no chance (given you don't reuse the seed) but it is a horribly unreliable (see answer d) and slow stream cipher, so please never ever do this - use a Cipher with "AES/CTR/NoPadding" or "AES/GCM/NoPadding" instead
e) I don't think that it makes a difference. Assuming that the long and the 8-byte array contain the same data.
f) In principle, yes. If your seed is larger than the internal state of the RNG, then there may exist some other seed that will result in the same internal state. If the seed is smaller than the state, then there shouldn't be. I don't know what SecureRandom's internal state looks like.
g) It's not the size of the seed that matters; it's the amount of entropy in it. You need there to be at least as much entropy in your seed as the security you expect out of the RNG; I'm not quite sure what best practices are here.
h) I'm not sure how easy it would be to break the RNG-based stream cipher that you propose. But I would recommend against using it in practice, because it's not a standard cryptographic construction that has been reviewed by experts and has reasonable security proofs. Remember the Rules of Crypto:
Never design your own crypto.
Never implement your own crypto.
Anyone can design crypto that they can't break themselves.
SecureRandom internally makes use of other algorithms , like in case of Linux , makes use of NativePRNG which in turn makes use of /dev/urandom . But /dev/urandom is actually using interrupts events etc to generate entropy which is similar to a True Random Number Generator (TRNG) . So why is SecureRandom called PseudoRandom Number Generator , although it is dependent on the implementation of the algorithm it is using ?
Thanks
I expect it has to do with guarantees. The guarantee of /dev/urandom is that it will use random data if available, filling in with pseudo-random data if necessary to avoid blocking. So if you're using /dev/urandom, you can't claim true randomness, even if sometimes you're getting it.
In the documentation for SecureRandom it says:
Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.
Thus, the guarantee of SecureRandom can only ever be that it works pseudo-randomly, if any implementations are allowed to do so. It may be able to do better, but that's not the contract.
Not all operating systems implement the same functionality for /dev/random, and there is no guarantee that it will be anything other than an algorithm (though most modern systems do use interrupts, etc). That is why Java refers to it as a PRNG.
/dev/random on Linux is a TRNG.
I'm in the rough stages of creating a Spades game and I'm having a hard time thinking up a cryptographically-secure way to shuffle the cards. So far, I have this:
Grab 32-bit system time before calling Random
Grab 32 bits from Random
Grab 32-bit system time after calling Random
Multiply the system times together bitwise and xor the two halves together
xor the 32 bits from Random with the value from the first xor, and call this the seed
Create a new Random using the seed
And basically from here I both save the 32-bit result from each Random instance and use it to seed the next instance until I get my desired amount of entropy. From here I create an alternating-step generator to produce the final 48-bit seed value I use for my final Random instance to shuffle the cards.
My question pertains to the portion before the alternating-step generator, but if not, since I'll be using a CSPRNG anyway would this algorithm be good enough?
Alternatively, would the final Random instance be absolutely necessary? Could I get away with grabbing six bits at a time off the ASG and taking the value mod 52?
No, it may be secure enough for your purposes, but it is certainly not cryptographically secure. On a fast system you may have two identical system times. On top of that, the multiplication will only remove entropy.
If you wan't, you can download the FIPS tests for RNG's and input a load of data using your RNG, then test it. Note that even I have trouble actually reading the documentation on the RNG tests, so be prepared to do some math.
All this while the Java platform already contains a secure PRNG (which is based on SHA1 and uses the RNG of the operating system as seed). The operating system almost certainly uses some time based information as seed, no need to input it yourself (of course you may always seed the system time if you really want to).
Sometimes the easy answer is the best one:
List<Card> deck; // Get this from whereever.
SecureRandom rnd = new SecureRandom();
java.util.Collections.shuffle(deck, rnd);
// deck is now securely shuffled!
You need a good shuffling algorithm and a way of gathering enough entropy to feed it so that it can theoretically cover all possible permutations for a deck of cards. See this earlier question: Commercial-grade randomization for Poker game