0

我已经学会了编写代码来实现下面的 Diffie-Hellman 密钥交换算法,但我觉得我的代码并不是最有效的。谁能更正我的代码...?

import java.math.BigInteger;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;;

    public class DH_key {
        static class DHGenParameterSpec implements AlgorithmParameterSpec{
            static BigInteger p;
            static BigInteger g;
            static int a,b;
            static BigInteger A,B;
        static BigInteger getPrimeP_G() {
            Random rand1= new Random(System.currentTimeMillis());
            Random rand2= new Random(System.currentTimeMillis()*10);

            p= BigInteger.probablePrime(32, rand1);
            g= BigInteger.probablePrime(32, rand2);
            System.out.println(""+p+","+g);
            return null;
        }
        static int getExponent() {
            SecureRandom ranGen1 = new SecureRandom();

            a= ranGen1.nextInt(1000);
            b= ranGen1.nextInt(1000);
            System.out.println(a+"__"+b);
            return 0 ;

        }
        public static Object pow (){
            //g.pow(a);
            A = g.pow(getExponent()).mod(getPrimeP_G());
            B = g.pow(b).mod(p);

            return null;        
        }



    public static void main(String[]args){
        //System.out.println(DHGenParameterSpec.getPrimeP_G());
        DHGenParameterSpec.getPrimeP_G();
        DHGenParameterSpec.getExponent();
        A = g.pow(a).mod(p);
        B = g.pow(b).mod(p);

        BigInteger Sa,Sb;
        Sa=B.pow(a).mod(p);
        Sb=A.pow(b).mod(p);

            System.out.println(""+A+"__"+B);
                System.out.println(""+Sa+"__"+Sb);
        }

        }

    }

上面的代码是否适合 java 规则?

4

1 回答 1

1

您已将模幂编写为:

        A = g.pow(getExponent()).mod(getPrimeP_G());
        B = g.pow(b).mod(p);

这是低效的,因为取幂的中间结果可能很大。您应该改用该modPow方法,该方法使用有效的算法执行这两个操作:

        A = g.modPow(getExponent(), getPrimeP_G());
        B = g.modPow(b, p);
于 2013-08-10T20:38:24.507 回答