|
From: Lars R. N. <lar...@gm...> - 2009-07-09 18:16:38
|
On Thu, 2009-07-09 at 10:50 -0600, Carlos Konstanski wrote:
> I have a need for better randomness. The situation: I have an
> araneida web server. I use the following function to generate a
> session id cookie:
>
> (defun generate-sessionid ()
> "Generates a unique, random string to use as the value in a
> LISPSESSIONID cookie. The string is comprised of 16 octets in hex,
> just like a PHP sessionid."
> (let ((sessionid nil))
> (dotimes (i 16)
> (let ((octet (random 256)))
> (if (< octet 16)
> (setf octet (format nil "0~x" octet))
> (setf octet (format nil "~x" octet)))
> (setf sessionid (concatenate 'string sessionid octet))))
> sessionid))
>
> As one might expect, if I call this function x number of times, I
> always get the same x session id strings because of how (random)
> works.
Hi,
I'm no expert at this stuff, but /dev/urandom (Linux; see `man 4
urandom') has some true randomness to it and this has never caused
session clashes for me:
CL-USER> (defun generate-random-cookie-value (&optional (size 50))
(with-open-file (s "/dev/urandom" :direction :input :element-type '(unsigned-byte 8))
(with-output-to-string (ss)
(loop :repeat size
:do (write (read-byte s) :stream ss :pretty nil :base 36)))))
GENERATE-RANDOM-COOKIE-VALUE
CL-USER> (generate-random-cookie-value)
"VJU526B1X713H1GW3P2O224RL1S5J3K4E5D6P2U6Z5J2O461W6O1NI3C2B5M4W3G2H3H3O4G6JH37655Z323K626W463E"
CL-USER> (generate-random-cookie-value)
"4U171V59155K1Y3T47N6P2S3O5L6V5W5D2MM6C2S3B6I2P222Y622T11586K4O3V5VB5L2ALL6D24YY4C6L66Q5IP47"
CL-USER>
I actually pass 1 required argument to this function, `server', and do a
gethash+loop&return-from to check and make 100% sure a session with that
ID does not exist even though that is quite unlikely to ever happen.
|