0

This is a repeat of this question: Calculate primes p and q from private exponent (d), public exponent (e) and the modulus (n)

I'm just explicitly stating the problem and asking for a solution - hopefully in clojure:

public key (n):    

8251765078168273332294927113607583143463818063169334570141974734622347615608759376136539680924724436167734207457819985975399290886224386172465730576481018297063

private key (d):

3208816897586377860956958931447720469523710321495803767643746679156057326148423456475670861779003305999429436586281847824835615918694834568426186408938023979073

exponent (e): 65537

and I want to get the seeds: p and q

p: 87270901711217520502010198833502882703085386146216514793775433152756453168234183

q: 87270901711217520502010198833502882703085386146216514793775433152756453168234183

To get n and d in the first place is not too hard:

(defn egcd [a b]
  (if (= a 0)
    [b, 0, 1]
    (let [[g y x] (egcd (mod b a) a)]
      [g (- x (* y (quot b a))) y])))

(defn modinv [a m]
  (let [[g y x] (egcd a m)]
    (if (not= 1 g)
      (throw (Exception. "Modular Inverse Does Not Exist"))
      y)))

(def n (* p q))
(def d (modinv e (* (dec p) (dec q)))

Now I require a reverse transform.

Community
  • 1
  • 1
zcaudate
  • 13,998
  • 7
  • 64
  • 124

1 Answers1

1

The algorithm Thomas Pornin posted in response to the question you link to works perfectly. Transcribed into Clojure, it looks like this:

;; using math.numeric-tower 0.0.4
(require '[clojure.math.numeric-tower :as num])

(defn find-ks [e d n]
  (let [m (num/round (/ (*' e d) n))]
    ((juxt dec' identity inc') m)))

(defn phi-of-n [e d k]
  (/ (dec' (*' e d)) k))

(defn p-and-q [p+q pq]
  [(/ (+' p+q (num/sqrt (-' (*' p+q p+q) (*' 4 pq)))) 2)
   (/ (-' p+q (num/sqrt (-' (*' p+q p+q) (*' 4 pq)))) 2)])

(defn verify [n p q]
  (== n (*' p q)))

(defn solve [e d n]
  (first
   (for [k (find-ks e d n)
         :let [phi (phi-of-n e d k)
               p+q (inc' (-' n phi))
               [p q] (p-and-q p+q n)]
               :when (verify n p q)]
     [p q])))

Applying this to your e, d and n we get

(solve 65537N 3208816897586377860956958931447720469523710321495803767643746679156057326148423456475670861779003305999429436586281847824835615918694834568426186408938023979073N 8251765078168273332294927113607583143463818063169334570141974734622347615608759376136539680924724436167734207457819985975399290886224386172465730576481018297063N)
;= [94553452712951836476229946322137980113539561829760409872047377997530344849179361N
    87270901711217520502010198833502882703085386146216514793775433152756453168234183N]

You posted the same number as p and q, by the way -- the second one in the result vector above -- but it's easy to verify that these are the correct numbers by using the pair to rederive n and d.

Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212