about summary refs log tree commit diff
path: root/usth/ICT3.4/rsa.lsp
blob: 0461ea3d35edb02211e0d76f095177ce766a2279 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(defun square (x) (* x x))

(defun modexpt (x e m)
  (cond ((= e 0) 1)
        ((= e 1) (mod x m))
        ((evenp e) (mod (square (modexpt x (/ e 2) m)) m))
        (t (mod (* (square (modexpt x (floor e 2) m)) x) m))))

(defun modinv (x m &optional (b m) (a 0) (u 1))
  (if (= x 0)
      (when (= b 1) (mod a m))
      (modinv (mod b x) m x u (- a (* u (floor b x))))))

(defun rsa (p q &optional e d m c)
  (let ((n (* p q))
        (l (* (1- p) (1- q))))
    (cond ((not e) (rsa p q (modinv d l) d m c))
          ((not d) (rsa p q e (modinv e l) m c))
          ((not m) (modexpt c d n))
          ((not c) (modexpt m e n)))))