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

2

5

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?

Cade answered 10/3, 2010 at 3:5 Comment(0)
F
7

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.

Flax answered 10/3, 2010 at 3:27 Comment(0)
L
2

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.

Leanoraleant answered 10/3, 2010 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.