V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xgfan
V2EX  ›  问与答

RSA 如何通过 p,q,dp,dq 计算出 e,d ?

  •  
  •   xgfan · 2017-08-03 00:31:29 +08:00 · 6257 次点击
    这是一个创建于 2462 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这两天在弄 chinapay 的接口,文档也不全。其中的签名方法用用到 rsa 相关的内容。

    现在是能获取到 rsa 的 p,q,dp,dq四个值,以及衍生的其他值,需要何获取ed

    这是我已经实现的一个计算 e 的方法

    ed ≡ 1 (mod φ(n))

    φ (n) ≡ (p-1) * (q-1)

    dp ≡ d mod (p-1)

    dq ≡ d mod (q-1)

        public static BigInteger calcE(BigInteger p, BigInteger q, BigInteger dp, BigInteger dq) {
            BigInteger e = BigInteger.ONE;
            BigInteger p_1 = p.subtract(BigInteger.ONE);
            BigInteger q_1 = q.subtract(BigInteger.ONE);
            BigInteger phiN = p_1.multiply(q_1);
            while (true) {
                BigInteger d = e.modInverse(phiN);
                try {
                    if (d.mod(p_1).equals(dp) && d.mod(q_1).equals(dq)) {
                        break;
                    }
                } catch (Exception ignored) { }
                e = e.add(BigInteger.ONE);
            }
            return e;
        }
    

    但是感觉这样遍历不太妥当,虽然我手上这个的e是常见的 65537,计算起来也不算慢……

    总结一下问题

    1. 有没有其他好的方法通过p,q,dp,dq计算ed

    2. 或者有没有什么算法简化上面的过程,即

      x mod m = a

      x mod n = b

      m,n,a,b 均为已知值,求最小 x 值

    8 条回复    2017-08-03 16:06:00 +08:00
    yangff
        1
    yangff  
       2017-08-03 01:35:41 +08:00 via Android   ❤️ 1
    中国剩余定理
    Kilerd
        3
    Kilerd  
       2017-08-03 02:25:45 +08:00 via iPhone
    通常为了加快计算速度,会把 e 设为定值,也就是你说的 65537,然后用 EGCD 算 d。
    当然啦,你也可以随机一个素数 e 出来,再用 EGCD 算 d
    xgfan
        4
    xgfan  
    OP
       2017-08-03 02:32:54 +08:00
    @yangff 感谢。这个方法应该是很合理的了。
    唉,数学不好是硬伤啊。

    @SoloCompany 这个默认用的是 RSAKeyGenParameterSpec.F4,也是 65537,
    或者是传入的 AlgorithmParameterSpec 里定义好的 F4。
    xgfan
        5
    xgfan  
    OP
       2017-08-03 02:36:31 +08:00
    @Kilerd 哈哈,是的。但是我这边需要得到 e,d 两个值,要不然我这边签名出来,chinapay 那边就不认了。
    geelaw
        6
    geelaw  
       2017-08-03 03:05:41 +08:00
    这个计算方法简直吓尿,把多项式问题变成指数问题了……

    d=((p-1).modInverse(q-1)*(p-1)*dq+(q-1).modInverse(p-1)*(q-1)*dp)%((p-1)*(q-1))
    yinheli
        7
    yinheli  
       2017-08-03 14:30:01 +08:00   ❤️ 1
    Kilerd
        8
    Kilerd  
       2017-08-03 16:06:00 +08:00 via iPhone   ❤️ 1
    @xgfan 看看 EGCD 啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5297 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 08:13 · PVG 16:13 · LAX 01:13 · JFK 04:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.