如果我有rsa密钥的公钥和私钥,我该如何计算种子p和q?

时间:2014-02-21 01:07:10

标签: clojure rsa

这是此问题的重复:Calculate primes p and q from private exponent (d), public exponent (e) and the modulus (n)

我只是明确地陈述问题并寻求解决方案 - 希望在clojure:

public key (n):    

8251765078168273332294927113607583143463818063169334570141974734622347615608759376136539680924724436167734207457819985975399290886224386172465730576481018297063

private key (d):

3208816897586377860956958931447720469523710321495803767643746679156057326148423456475670861779003305999429436586281847824835615918694834568426186408938023979073

exponent (e): 65537

我希望得到种子:p和q

p: 87270901711217520502010198833502882703085386146216514793775433152756453168234183

q: 87270901711217520502010198833502882703085386146216514793775433152756453168234183

首先获得n和d并不太难:

(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)))

现在我需要一个反向变换。

1 个答案:

答案 0 :(得分:1)

Thomas Pornin在回答您链接的问题时发布的算法完美无缺。转录成Clojure,它看起来像这样:

;; 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])))

将此应用于edn我们

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

顺便说一句,你发布了与pq相同的数字 - 上面结果向量中的第二个 - 但是通过使用它可以很容易地验证这些是正确的数字配对以重新nd