2013-07-05 38 views
0

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

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.我进行了实验,并想了解如何解决它的一些提示。谢谢。

+0

43是正确答案。 –

回答

0

为什么不使用类java.math.BigInteger?这个类有一个名为modPow()的方法,它被设计用于密码学使用。

的用法是

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

顺便说变量与小写字母命名(n在我的情况)。

0

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

0

我测试了各种数字到该功能,它的工作很好。然后,我创建了使用基于乌韦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)); 
    } 
} 

这得到输出:

 
BEGIN main 
43 
43