I\'m trying to generate a random string using a range of acceptable characters. I have a working implementation, which is included below, but I wanted to know if the logic of co
The additional information is helpful. I presume that you never send the token in the clear and never send it to an untrusted party.
To answer the question that was actually asked: yes, your code correctly generates a 40 character random string containing 240 bits of randomness. I note that of course you consume 320 bits of randomness to do so, but, whatever, bits are cheap.
Presumably the number of tokens thus generated is a very small fraction of 2240, and therefore it will be hard for an attacker to guess at a valid token. If tokens have a short lifespan -- if they are only in the database while the transaction is happening, and then go away a short time later -- that's even better. Defense in depth.
Note that a software RNG takes information from its environment as the seed entropy. If malware can be running on the machine doing the generation then it could be attempting to manipulate that environment, and thereby deduce part of the entropy. But if you have malware running on that machine, odds are good that you already have far larger problems.
I note also that the garbage collector does not make any guarantees about how long those strings and arrays containing the token hang around in memory. Again, if you have malware with admin privileges on your machine that starts up a debugger and interrogates memory, it can discover the keys. Of course that presumes that the bad actors are already on the wrong side of the airtight hatchway, as Raymond Chen says. Memory scanning by malware with admin privileges is the least of your worries!