一、目的根据TCP传输层协议设计加密协议。关键思路用非对称加密算法传递一个对称密钥之后的数据通信用对称加密通信。非对称算法采用RSA对称加密算法采用AES。二、协议格式1、建立TCP连接服务端回复公钥给客户端生成一对RSA密钥把公钥分享给客户端。格式如下1字节类型值为12字节长度公钥的字节序列2、客户端回复对称密钥给服务端生成1个对称密钥用公钥加密协议格式如下1字节类型值为22字节长度用RSA非对称算法和公钥来对对称密钥的加密字节序列3、全双工通信格式如下1字节类型值为32字节长度数据的AES加密序列三、主要代码(一)工具类1、对称加密工具import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class CipherUtil { /** * 生成对称的AES加密密钥 * return * throws NoSuchAlgorithmException */ public static byte[] genAESKey() throws NoSuchAlgorithmException { // 生成密钥 KeyGenerator keyGenerator KeyGenerator.getInstance(AES); keyGenerator.init(128); // 可以是128, 192或256位 SecretKey secretKey keyGenerator.generateKey(); byte[] key secretKey.getEncoded(); return key; } /** * 加密 * param secret 密钥 * param data 明文 * return * throws NoSuchPaddingException * throws NoSuchAlgorithmException * throws InvalidKeyException * throws BadPaddingException * throws IllegalBlockSizeException */ public static byte[] encrypt(byte[] secret, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { return encrypt(secret, data, 0, data.length); } /** * 加密 * param secret 密钥 * param data 明文 * return * throws NoSuchPaddingException * throws NoSuchAlgorithmException * throws InvalidKeyException * throws BadPaddingException * throws IllegalBlockSizeException */ public static byte[] encrypt(byte[] secret, byte[] data, int offset, int length) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec keySpec new SecretKeySpec(secret, AES); // 加密 Cipher cipher Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(data, offset, length); } /** * 解密 * param secret 密钥 * param data 密文 * return * throws NoSuchPaddingException * throws NoSuchAlgorithmException * throws InvalidKeyException * throws BadPaddingException * throws IllegalBlockSizeException */ public static byte[] decrypt(byte[] secret, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { // 解密 SecretKeySpec keySpec new SecretKeySpec(secret, AES); Cipher cipher Cipher.getInstance(AES); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(data); } }2、非对称加密工具import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class RSAUtil { /** * 生成RSA非对称密钥对 * return 密钥对 * throws NoSuchAlgorithmException */ public static KeyPair genKeyPair() throws NoSuchAlgorithmException { // 生成密钥对 KeyPairGenerator keyPairGenerator KeyPairGenerator.getInstance(RSA); keyPairGenerator.initialize(2048); // 可以是1024, 2048, 4096等 return keyPairGenerator.generateKeyPair(); } public static PublicKey packPublicKey(byte[] publicKeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory KeyFactory.getInstance(RSA); X509EncodedKeySpec spec new X509EncodedKeySpec(publicKeyData); return factory.generatePublic(spec); } public static PrivateKey packPrivateKey(byte[] privateKeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory KeyFactory.getInstance(RSA); PKCS8EncodedKeySpec spec new PKCS8EncodedKeySpec(privateKeyData); return factory.generatePrivate(spec); } /** * 加密 * param publicKey 公钥 * param data 明文 * return * throws NoSuchPaddingException * throws NoSuchAlgorithmException * throws InvalidKeyException * throws BadPaddingException * throws IllegalBlockSizeException */ public static byte[] encrypt(PublicKey publicKey, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { // 加密 Cipher cipher Cipher.getInstance(RSA); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } /** * 解密 * param privateKey 私钥 * param data 密文 * return * throws NoSuchPaddingException * throws NoSuchAlgorithmException * throws InvalidKeyException * throws BadPaddingException * throws IllegalBlockSizeException */ public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { // 解密 Cipher cipher Cipher.getInstance(RSA); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } }3、读写工具import java.io.IOException; import java.io.InputStream; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class Util { /** * 读取2个字节凑成int变量值 * param data 字节数组 * return */ public static int get2Array(byte[] data){ return ((data[0] 0xFF) 8) | ((data[1] 0xFF)); } /** * 把变量转成2字节数组 * param data * return */ public static byte[] getArray(int data){ byte[] temp new byte[2]; temp[0] (byte)((data 0xFF00L) 8); temp[1] (byte)(data 0xFFL); return temp; } /** * 读满数组直到结束或者抛出异常 * param input 输入流 * param data 存放数据的字节数组 * param offset 偏移量 * param length 本次读取的数据长度 */ public static void readFully(InputStream input, byte[] data, int offset, int length) throws IOException { // 定义计数变量 int count 0; // 定义返回的变量 int size 0; while(count length){ size input.read(data, offset count, length - count); if(size -1){ throw new IOException(input stream is close.); } count count size; } } }(二)服务端import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class SServer { /** * TCP服务端 */ private ServerSocket socket; public SServer(int port) throws IOException { this.socket new ServerSocket(port); } public SServer(String host, int port) throws IOException { this(host, port, 50); } public SServer(String host, int port, int backlog) throws IOException { this.socket new ServerSocket(port, backlog, InetAddress.getByName(host)); } public void setTimeOut(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } public HSocket accept() throws IOException { Socket sock socket.accept(); return new HSocket(sock); } public void close() throws IOException { if (this.socket ! null){ socket.close(); } } }服务端的客户端import org.util.CipherUtil; import org.util.RSAUtil; import org.util.Util; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.security.*; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class HSocket { private Socket socket; private InputStream input; private OutputStream output; /** * 对称密钥 */ private byte[] secret; /** * 上次缓冲的数据 */ private byte[] cache null; public HSocket(Socket socket) throws IOException { this.socket socket; this.input socket.getInputStream(); this.output socket.getOutputStream(); init(); } private void init(){ try { KeyPair keyPair RSAUtil.genKeyPair(); PublicKey key1 keyPair.getPublic(); PrivateKey privateKey keyPair.getPrivate(); byte[] encoded key1.getEncoded(); output.write(1); output.write(Util.getArray(encoded.length)); output.write(encoded); output.flush(); int code input.read(); if (code -1){ throw new IOException(input is close.); } if(code 2){ byte[] temp new byte[2]; Util.readFully(input, temp, 0, 2); int length Util.get2Array(temp); // 定义对称密钥 byte[] key new byte[length]; Util.readFully(input, key, 0, length); // 存放对称密钥 secret RSAUtil.decrypt(privateKey, key); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } public int read(byte[] data, int offset, int size) throws IOException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { if(cache ! null){ // 求最小值 int length Math.min(cache.length, size); System.arraycopy(cache, 0, data, offset, length); // 如果有剩余 if (cache.length - length 0){ byte[] temp new byte[cache.length - length]; System.arraycopy(cache, length, temp, 0, cache.length - length); cache temp; } else { // 没有剩余设为null cache null; } return length; } else { int code input.read(); if (code -1){ return -1; } if (code 3){ byte[] temp new byte[2]; Util.readFully(input, temp, 0, 2); int length Util.get2Array(temp); // 定义数据 byte[] recv new byte[length]; Util.readFully(input, recv, 0, length); // 解密 byte[] plain CipherUtil.decrypt(secret, recv); // 求最小值 int min Math.min(plain.length, size); System.arraycopy(plain, 0, data, offset, min); // 如果有剩余存在缓冲 if (plain.length - min 0){ temp new byte[plain.length - min]; System.arraycopy(plain, min, temp, 0, plain.length - min); cache temp; } return min; } } return -1; } public void write(byte[] data, int offset, int size) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { output.write(3); byte[] encrypt CipherUtil.encrypt(secret, data, offset, size); output.write(Util.getArray(encrypt.length)); output.write(encrypt); output.flush(); } public void setTimeout(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } public void close() throws IOException { this.socket.close(); } }(三)客户端import org.util.CipherUtil; import org.util.RSAUtil; import org.util.Util; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class SSocket { private Socket socket; private InputStream input; private OutputStream output; private byte[] secret; /** * 上次缓冲的数据 */ private byte[] cache null; public SSocket(String host, int port) throws IOException { this.socket new Socket(host, port); this.input socket.getInputStream(); this.output socket.getOutputStream(); init(); } private void init(){ try { int code input.read(); if (code -1){ throw new IOException(input is close.); } if(code 1){ byte[] temp new byte[2]; Util.readFully(input, temp, 0, 2); int length Util.get2Array(temp); // 定义公钥 byte[] key new byte[length]; Util.readFully(input, key, 0, length); PublicKey publicKey RSAUtil.packPublicKey(key); this.secret CipherUtil.genAESKey(); byte[] encrypt RSAUtil.encrypt(publicKey, secret); output.write(2); output.write(Util.getArray(encrypt.length)); output.write(encrypt); output.flush(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } public int read(byte[] data, int offset, int size) throws IOException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { if(cache ! null){ // 求最小值 int length Math.min(cache.length, size); System.arraycopy(cache, 0, data, offset, length); // 如果有剩余 if (cache.length - length 0){ byte[] temp new byte[cache.length - length]; System.arraycopy(cache, length, temp, 0, cache.length - length); cache temp; } else { // 没有剩余设为null cache null; } return length; } else { int code input.read(); if (code -1){ return -1; } if (code 3){ byte[] temp new byte[2]; Util.readFully(input, temp, 0, 2); int length Util.get2Array(temp); // 定义数据 byte[] recv new byte[length]; Util.readFully(input, recv, 0, length); // 解密 byte[] plain CipherUtil.decrypt(secret, recv); // 求最小值 int min Math.min(plain.length, size); System.arraycopy(plain, 0, data, offset, min); // 如果有剩余存在缓冲 if (plain.length - min 0){ temp new byte[plain.length - min]; System.arraycopy(plain, min, temp, 0, plain.length - min); cache temp; } return min; } } return -1; } public void write(byte[] data, int offset, int size) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { output.write(3); byte[] encrypt CipherUtil.encrypt(secret, data, offset, size); output.write(Util.getArray(encrypt.length)); output.write(encrypt); output.flush(); } public void setTimeout(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } public void close() throws IOException { this.socket.close(); } }四、测试类1、服务端import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.net.ssl.SSLSocket; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class TestS { public static void main(String[] args) { try { // 监听端口8888 SServer sServer new SServer(8888); HSocket socket sServer.accept(); byte[] data 我是小明.getBytes(UTF-8); System.out.println(发送长度 data.length); socket.write(data, 0, data.length); byte[] temp new byte[888]; int k socket.read(temp, 0, temp.length); System.out.println(读取个数 k); System.out.println(new String(temp, 0, k, UTF-8)); socket.close(); sServer.close(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } }2、测试客户端import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * author * version 1.0.0 * p * date: 2026/1/9 **/ public class TestC { public static void main(String[] args) { try { SSocket socket new SSocket(127.0.0.1, 8888); byte[] temp new byte[888]; int k socket.read(temp, 0, temp.length); System.out.println(读取个数 k); System.out.println(服务器返回 new String(temp, 0, k, UTF-8)); byte[] data 客户端回复OK.getBytes(UTF-8); socket.write(data, 0, data.length); socket.close(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } }五、测试结果1、服务端结果2、客户端结果六、总结1、基本满足加密要求加密比明文通信更耗时。2、每次都是重新生成密钥不需要指定密钥。3、交换的对称密钥只交换1次没有定时更换。4、优点加密不需要第三方干预没有证书适合简单的低成本私密一对一通信局域网内的TCP加密通信。5、缺点没有认证中心的证书鉴定不支持身份认证机制。公钥的交换容易被中间设备替换公钥的合法来源没有办法验证真假。