It sounds a lot like you're trying to implement some basic authentication. Something to try (in pseudo-code; I'm not great with Java on the web):
random_number = rand(1000000, 9999999);
secret = "Some random text here";
timestamp = unix_timestamp(); // Get a UNIX timestamp
user_ip = users_ip(); // Get the user's IP
setcookie("random_number", random_number); // Save the random number
setcookie("timestamp", timestamp);
setcookie("token", sha256(random_number + secret + timestamp + ip)); // Concat and hash everything to form a token
When you want to check if the random number is valid, just pull all the pieces back together and compare it to the token:
random_number = getcookie("random_number");
secret = "Some random text here";
timestamp = int(getcookie("timestamp"));
user_ip = users_ip(); // Get the user's IP
token = sha256(random_number + secret + timestamp + ip);
if(unix_timestamp() - timestamp < 0 || unix_timestamp() - timestamp > timeout) {
// The token is more than an hour old; it might have been stolen.
}
if(token == getcookie("token")) {
// The user is valid
} else {
// The user is invalid
}
This code will block someone from spoofing the random number by making sure it comes from the same IP. You can also use the timestamp stuff to make sure that the user's session expires over time. This'll keep hackers from simply generating a good number and using it forever.
As for the secret, that's a random text chunk. It should be completely random and never be shared. It basically makes your tokens virtually impossible to reverse engineer (otherwise, it's a matter of trying combinations like "number timestamp ip", "ip number timestamp", etc.).
It should also be noted that something like this could be better accomplished with HMAC, but that could be somewhat overkill for what you're looking to do. This solution will do a damn good job as-is.
Hope this helps.
EDIT
It should be noted that your secrets need to be the same for the verification to work.