You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java Socket客户端-服务端实现RSA加密通信(服务端发密文)

Got it, let's walk through implementing this RSA client-server chat step by step. I'll break it down into clear, actionable parts with Java code snippets you can test right away.

整体流程 Overview

Before diving into code, let's make sure we're aligned on the exact steps we need to build:

  1. Both Alice (server) and Bob (client) generate their own RSA key pairs (public + private).
  2. Bob connects to Alice's server.
  3. Alice sends her public key to Bob; Bob sends his public key to Alice.
  4. Alice encrypts the message "Hello!" using Bob's public key, then sends the encrypted bytes to Bob.
  5. Bob receives the encrypted message and decrypts it using his own private key.
1. RSA Key Pair Generation Utility

First, let's create a helper method to generate RSA key pairs—this will be used by both server and client:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

public class RSAKeyGenerator {
    public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
        // Use 2048-bit keys (1024 is no longer considered secure)
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        return keyGen.generateKeyPair();
    }
}
2. Server (Alice) Implementation

The server will listen for incoming connections, exchange public keys, encrypt the message, and send it:

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyPair;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class AliceServer {
    public static void main(String[] args) {
        try {
            // Generate Alice's key pair
            KeyPair aliceKeyPair = RSAKeyGenerator.generateRSAKeyPair();
            PublicKey alicePublicKey = aliceKeyPair.getPublic();

            // Start server on port 12345
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Alice's server is running, waiting for Bob...");
            
            // Accept Bob's connection
            Socket bobSocket = serverSocket.accept();
            System.out.println("Bob connected!");

            // Set up streams for key exchange and message transfer
            ObjectOutputStream out = new ObjectOutputStream(bobSocket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(bobSocket.getInputStream());

            // Send Alice's public key to Bob
            out.writeObject(alicePublicKey);
            out.flush();
            System.out.println("Sent Alice's public key to Bob");

            // Receive Bob's public key
            PublicKey bobPublicKey = (PublicKey) in.readObject();
            System.out.println("Received Bob's public key");

            // Encrypt "Hello!" using Bob's public key
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, bobPublicKey);
            String message = "Hello!";
            byte[] encryptedMessage = cipher.doFinal(message.getBytes());

            // Send encrypted message to Bob
            out.writeObject(encryptedMessage);
            out.flush();
            System.out.println("Sent encrypted message to Bob");

            // Cleanup
            in.close();
            out.close();
            bobSocket.close();
            serverSocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
3. Client (Bob) Implementation

The client will connect to Alice's server, exchange public keys, receive the encrypted message, and decrypt it:

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class BobClient {
    public static void main(String[] args) {
        try {
            // Generate Bob's key pair
            KeyPair bobKeyPair = RSAKeyGenerator.generateRSAKeyPair();
            PublicKey bobPublicKey = bobKeyPair.getPublic();
            PrivateKey bobPrivateKey = bobKeyPair.getPrivate();

            // Connect to Alice's server (localhost for testing)
            Socket aliceSocket = new Socket("localhost", 12345);
            System.out.println("Connected to Alice's server");

            // Set up streams
            ObjectOutputStream out = new ObjectOutputStream(aliceSocket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(aliceSocket.getInputStream());

            // Receive Alice's public key
            PublicKey alicePublicKey = (PublicKey) in.readObject();
            System.out.println("Received Alice's public key");

            // Send Bob's public key to Alice
            out.writeObject(bobPublicKey);
            out.flush();
            System.out.println("Sent Bob's public key to Alice");

            // Receive encrypted message from Alice
            byte[] encryptedMessage = (byte[]) in.readObject();
            System.out.println("Received encrypted message");

            // Decrypt using Bob's private key
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, bobPrivateKey);
            byte[] decryptedBytes = cipher.doFinal(encryptedMessage);
            String decryptedMessage = new String(decryptedBytes);
            System.out.println("Decrypted message: " + decryptedMessage);

            // Cleanup
            in.close();
            out.close();
            aliceSocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4. Key Things to Keep in Mind
  • Key Length: We used 2048-bit keys here—avoid 1024-bit keys as they're no longer secure for modern use.
  • Message Size Limits: RSA can only encrypt data up to (key length / 8) - 11 bytes (for PKCS#1 padding). For longer messages, you'd use a hybrid approach: encrypt the actual message with a symmetric key (like AES), then encrypt the symmetric key with RSA.
  • Exception Handling: The code above uses a broad Exception catch for simplicity—you'll want to handle specific exceptions (like NoSuchAlgorithmException, IOException, InvalidKeyException) in production code for better error tracking.
  • Serialization: We're using Java's object serialization to send public keys over the network. This works because PublicKey and PrivateKey implement Serializable, but in production, you might want to use standard formats like PEM for key exchange instead.

内容的提问来源于stack exchange,提问作者Derrick C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:33:45