在java中使用diffie-hellman的ftp服务器

时间:2013-12-25 16:11:11

标签: java diffie-hellman

我在java中只有服务器端代码,我想为我的服务器使用diffie-hellman加密,所以任何人都可以帮我解决这个问题我是编程新手,我刚开始学习这是我的作业和截止日期是非常接近所以任何人都可以帮助我,这将是伟大的... 到目前为止,我得到了这段代码,我不知道如何将它与我的服务器代码合并

import java.util.*;
import java.math.BigInteger;

public class DiffieHellmanBigInt {

final static BigInteger one = new BigInteger("1");

public static void main(String args[]) {

    Scanner stdin = new Scanner(System.in);
    BigInteger p;

    // Get a start spot to pick a prime from the user.
    System.out.println("Enter the approximate value of p you want.");
    String ans = stdin.next();
    p = getNextPrime(ans);
    System.out.println("Your prime is "+p+".");

    // Get the base for exponentiation from the user.
    System.out.println("Now, enter a number in between 2 and p-1.");
    BigInteger g = new BigInteger(stdin.next());

    // Get A's secret number.
    System.out.println("Person A: enter your secret number now.");
    BigInteger a = new BigInteger(stdin.next());

    // Make A's calculation.
    BigInteger resulta = g.modPow(a,p);

    System.out.println("Person A sends to person B "+resulta+".");

    // Get B's secret number.
    System.out.println("Person B: enter your secret number now.");
    BigInteger b = new BigInteger(stdin.next());

    // Make B's calculation.
    BigInteger resultb = g.modPow(b,p);

    System.out.println("Person B sends to person A "+resultb+".");

    BigInteger KeyACalculates = resultb.modPow(a,p);
    BigInteger KeyBCalculates = resulta.modPow(b,p);

    // Print out the Key A calculates.
    System.out.println("A takes "+resultb+" raises it to the power "+a+" mod "+p);
    System.out.println("The Key A calculates is "+KeyACalculates+".");

    // Print out the Key B calculates.
    System.out.println("B takes "+resulta+" raises it to the power "+b+" mod "+p);
    System.out.println("The Key B calculates is "+KeyBCalculates+".");

}

public static BigInteger getNextPrime(String ans) {

    BigInteger test = new BigInteger(ans);
    while (!test.isProbablePrime(99))
        test = test.add(one);
    return test;        
}

}

1 个答案:

答案 0 :(得分:2)

由于评论太长了......

Diffie-hellman仅用于通过未受保护的连接进行密钥交换,使用素数数学问题。它用于使用公钥和私钥初始化异步加密(早期用于SSL / TLS)。

除非需要作为练习(您应该添加作业或练习标记),不要自己实施此类安全性,使用现有的,经过良好测试的库。 Java内置了对SSL的支持(可能使用其他密钥交换方法):SSLContext

尽管如此,您可以使用这些数字来派生公钥和私钥,但是,您必须确保它们真的很大(而不仅仅是isProbablePrime)素数,{{{{{{ 1}}。

要连接客户端和服务器,请从Socket开始。但同样是免责声明,如果这不是一个练习,你很可能会被攻击(黑客攻击,DDOS,......),你最好使用现有的,经过良好测试和强化的服务器。