Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a nonce and print it on client side in Android? [closed]

I am now working on a program for Android which is something related to IMS. I want the server to send back a nonce to the client as a string and print it on the client-side.

Part of my code, from Generating a Secure Random Number:

public static String generateNonce() { 
  try {
   // Create a secure random number generator
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

   // Get 1024 random bits
   byte[] bytes = new byte[1024/8];
   sr.nextBytes(bytes);

   // Create two secure number generators with the same seed
   int seedByteCount = 10;
   byte[] seed = sr.generateSeed(seedByteCount);

   sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(seed);
   SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");
   sr2.setSeed(seed);
   } catch (NoSuchAlgorithmException e) {
  }
  //return NONCE;
  return null;
 }

I declared NONCE = generateNonce(); in the beginning. But the problem is instead of getting a nonce value, it prints null on the client-side. When I tried to print it on the server-side, it also appears to be null.

Can someone enlighten me on the error in my code or help me with better or more suitable coding?

like image 659
sebby_zml Avatar asked Jan 23 '23 11:01

sebby_zml


2 Answers

You need to add the return statement to the value you'd like to return, as of now your code generates (or seems to generate) the NONCE but you return null so the String NONCE is given a value of null.

You should also remove the return null statement. If you leave it in and it's the last return statement, your code will generate a valid NONCE but will return null.

like image 177
Anthony Forloney Avatar answered Feb 03 '23 08:02

Anthony Forloney


Well, I'd sort out the format of your code first as it is pretty unreadable.

Then I would remove the second SecureRandom instance.

Then I would remove the return null; statement at the end.

Then I would rewrite the function to return a random integer like this:

 return sr.next(32);

Also making sure that the function is declared to return an integer rather than a string.

like image 29
Cetra Avatar answered Feb 03 '23 08:02

Cetra