如何在java中加密聊天应用程序?

时间:2015-12-23 00:42:30

标签: java encryption rsa

我试图用Java编写带有RSA加密的聊天程序。我找到了RSA课程:

public class RSA {

private BigInteger n, d, e;

private int bits = 1024;

/** Create an instance that can encrypt using someone elses public key. */
public RSA(BigInteger newn, BigInteger newe) {
    n = newn;
    e = newe;
}

/** Create an instance that can both encrypt and decrypt. */
public RSA(int bits) {
    this.bits = bits;
    SecureRandom r = new SecureRandom();
    BigInteger p = new BigInteger(this.bits / 2, 100, r);
    BigInteger q = new BigInteger(this.bits / 2, 100, r);
    n = p.multiply(q);
    BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
        .subtract(BigInteger.ONE));
    e = new BigInteger("3");
    while (m.gcd(e).intValue() > 1) {
        e = e.add(new BigInteger("2"));
    }
    d = e.modInverse(m);
}

/** Encrypt the given plaintext message. */
public synchronized String encrypt(String message) {
    return (new BigInteger(message.getBytes())).modPow(e, n).toString();
}

/** Encrypt the given plaintext message. */
public synchronized BigInteger encrypt(BigInteger message) {
    return message.modPow(e, n);
}

/** Decrypt the given ciphertext message. */
public synchronized String decrypt(String message) {
    return new String((new BigInteger(message)).modPow(d, n).toByteArray());
}

/** Decrypt the given ciphertext message. */
public synchronized BigInteger decrypt(BigInteger message) {
    return message.modPow(d, n);
}

/** Generate a new public and private key set. */
public synchronized void generateKeys() {
    SecureRandom r = new SecureRandom();
    BigInteger p = new BigInteger(bits / 2, 100, r);
    BigInteger q = new BigInteger(bits / 2, 100, r);
    n = p.multiply(q);
    BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
        .subtract(BigInteger.ONE));
    e = new BigInteger("3");
    while (m.gcd(e).intValue() > 1) {
        e = e.add(new BigInteger("2"));
    }
    d = e.modInverse(m);
}

/** Return the modulus. */
public synchronized BigInteger getN() {
    return n;
}

/** Return the public key. */
public synchronized BigInteger getE() {
    return e;
}
}

当服务器启动时,它会创建自己的RSA对象:

public static RSA ownRsa = new RSA(1024);

所以,之后我为客户创建了两种方法:

public static BigInteger getServersN() {
    return ownRsa.getN();
}


public static BigInteger getServersE() {
    return ownRsa.getE();
}

当客户端启动时,它还会创建自己的RSA对象,同时他还会使用服务器的公钥创建另一个rsa对象:

public static RSA ownRsa = new RSA(1024);
public static RSA rsa = new RSA(ServerAction.getServersN(), ServerAction.getServersE());

因此,当客户端发送消息时,它将使用服务器的公钥(N和E)进行加密。当消息到达服务器时,我可以解密它。但是如何加密服务器上的消息以将其发送给其他客户端?据我所知,我需要从每个客户端向服务器发送公钥,但后来我必须加密大量消息并保留所有公钥。也许我的逻辑完全错了,或者我没有得到什么。有人可以提出任何建议吗?谢谢。

0 个答案:

没有答案