From 124636f5202a41c8feb46330f3c8fcd9f4eed9e8 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sun, 16 Oct 2022 23:40:14 -0700 Subject: [PATCH 09/10] Improve randomness of server.el * lisp/server.el (server-generate-key): Generate from system entropy, rather than from (random) which is lower quality. --- lisp/server.el | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/lisp/server.el b/lisp/server.el index 90d97c1538..b2bc245c02 100644 --- a/lisp/server.el +++ b/lisp/server.el @@ -590,10 +590,25 @@ server-generate-key The key is a 64-byte string of random chars in the range `!'..`~'. If called interactively, also inserts it into current buffer." (interactive) - (let ((auth-key - (cl-loop repeat 64 - collect (+ 33 (random 94)) into auth - finally return (concat auth)))) + (let* ((base 94) (auth-key-len 64) + (auth-key (make-string auth-key-len 0)) + ;; 1+ because we divide by BASE first, before taking the remainder. + ;; The division is first because if we took the remainder first + ;; the first remainder would not be entirely random. + (nonce-length (1+ (ceiling (logb (expt base auth-key-len)) 8)))) + ;; Use make-nonce with a function arg, to clear the nonce. + ;; auth-key and the bignum n still have the nonce's info, though. + (make-nonce + nonce-length + #'(lambda (nonce) + (let ((n 0)) + ;; Set N to be all the nonce's bits, concatenated. + (cl-loop for i below nonce-length + do (setq n (+ (* 256 n) (aref nonce i)))) + ;; Repeatedly divide and remainder to compute each byte. + (cl-loop for i below auth-key-len + do (setq n (/ n base)) + (aset auth-key i (+ 33 (% n base))))))) (if (called-interactively-p 'interactive) (insert auth-key)) auth-key)) -- 2.34.1