0

我需要 Diffie Hellman 协议来创建函数 XpowYmodN。我在网上找到了以下功能:

    public long XpowYmodN(long x, long y, long N) {
    long result = 1;
    final long oneShift63 = ((long) 1) << 63;

    for (int i = 0; i < 64; y <<= 1, i++) {
        result = result * result % N;
        if ((y & oneShift63) != 0)
            result = result * x % N;
    }
    return result;
}

对于这个例子:XpowYmodN(29,83,53) 结果是 43。根据设备制造商的计算结果应该是 50。谁能指出我做错了什么?对于这个例子,我已经尝试过 Math.pow(X,Y) % N,我得到了结果 28。我很困惑,想要一些关于如何修复它的提示。谢谢你。

4

3 回答 3

0

你的答案是正确的。但计算器提供的值不是计算,而是交换的密钥。你的答案是指发送者或接收者看到的公共价值

于 2013-07-05T10:48:41.100 回答
0

我在该函数中测试了各种数字,效果很好。然后,我根据 Uwe Plonus 的回答创建了一个使用以下代码的重复函数:

public long XpowYmodN(long x, long y, long N) {
    return BigInteger.valueOf(x).modPow(BigInteger.valueOf(y), BigInteger.valueOf(N)).longValue();
}

我测试了你的数字,得到了 43,就像那个函数一样;因此该功能似乎运行良好。发布 29,83,53 数字结果为 50 的人似乎是错误的。29、83、53 的正确答案是 43。

这是我使用的完整代码:

public class Main {
    public static long XpowYmodN_(long x, long y, long N) {
        long result = 1;
        final long oneShift63 = ((long) 1) << 63;

        for (int i = 0; i < 64; y <<= 1, i++) {
            result = result * result % N;
            if ((y & oneShift63) != 0)
                result = result * x % N;
        }
        return result;
    }

    public static long XpowYmodN(long x, long y, long N) {
        return BigInteger.valueOf(x).modPow(BigInteger.valueOf(y), BigInteger.valueOf(N)).longValue();
    }

    public static void main(String[] args)
    {
        System.out.println("BEGIN main");


        System.out.println(Main.XpowYmodN_(29,83,53));
        System.out.println(Main.XpowYmodN(29,83,53));
    }
}

它给出了以下输出:

开始主要
43
43
于 2013-07-06T15:41:06.857 回答
0

你为什么不使用类java.math.BigInteger?此类有一个名为的方法modPow(),该方法专为密码学使用而设计。

用法是

BigInteger result = BigInteger.valueOf(x).modPow(BigInteger.valueof(y), BigInteger.valueOf(n));

顺便说一下变量 a 用小写字母命名(n在我的例子中)。

于 2013-07-05T10:45:47.190 回答