How to: Generate cryptographically secure Random data of size quarter MB for a crypto application

StackOverflow https://stackoverflow.com/questions/15796229

  •  01-04-2022
  •  | 
  •  

Question

I need to generate cryptographically secure random data file of size quarter MB. Any ideas how I can do this. Any libraries/ API's available. Please guide as I am a newbie in Cryto.

This data (gen) has to be an inut to a C program which has the following usage comments on the header:

crypto_prg g gfile sfile pfile mfile < gen: generates a code determined by gen. writes code to gfile (7k), sfile (53k), pfile (4k), mfile (82k). takes some time. encoding needs mfile. decoding needs gfile sfile pfile. gen should be roughly a quarter megabyte of random data. gen without enough random data may fail to generate a code. crypto_prg will warn you in that case.

I need to generate the 'gen' in this case. How can I do that. Please advise as I am a newbie.

Thanks!

Was it helpful?

Solution

In Java, you can use a SecureRandom to generate cryptographically secure data. If you only need to generate the data one time, then it would be simple enough to use the following:

RandomDataGenerator.java

public static void main(String args[]) {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[262144]; // Number of bytes in 0.25MB
    random.nextBytes(bytes);

    try {
        FileOutputStream fos = new FileOutputStream("random.data");
        fos.write(myByteArray);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Let me know if you have any problems getting this to work.

OTHER TIPS

If you are doing this on a *NIX based system (Linux, OSX, Android) you can simply read as many bytes as you need from the special file /dev/urandom.

See: https://security.stackexchange.com/questions/3936/is-a-rand-from-dev-urandom-secure-for-a-login-key

From a *NIX, you should rather use /dev/random than /dev/urandom, for random is slower but more secure.

Still on linux APG should be installed by default. Try something like :

apg -a 1 -n 12 -m 16 -x 20 -M sncl

Finally you can use PWGen (not installed by default):

Cdt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top