Java加密传输流程统一

wen java案例 30

本文目录导读:

Java加密传输流程统一

  1. 加密传输基础架构
  2. 统一加密工具类
  3. 完整传输实现
  4. 使用示例
  5. 安全增强建议

我来为您系统梳理Java加密传输流程的统一实现方案。

加密传输基础架构

整体流程

客户端                         服务端
   |                             |
   |--- 1. 协商加密算法 -------->|
   |                             |
   |<-- 2. 返回公钥/证书 -------|
   |                             |
   |--- 3. 生成会话密钥 ------->| (用公钥加密)
   |                             |
   |--- 4. 加密数据传输 ------->| (用会话密钥)
   |                             |
   |<-- 5. 加密数据响应 ---------|

统一加密工具类

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class CryptoUtils {
    // 非对称加密(RSA)
    public static class RSA {
        private static final String ALGORITHM = "RSA";
        private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";
        private static final int KEY_SIZE = 2048;
        // 生成密钥对
        public static KeyPair generateKeyPair() throws Exception {
            KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM);
            generator.initialize(KEY_SIZE);
            return generator.generateKeyPair();
        }
        // 公钥加密
        public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }
        // 私钥解密
        public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }
    }
    // 对称加密(AES)
    public static class AES {
        private static final String ALGORITHM = "AES";
        private static final String TRANSFORMATION = "AES/GCM/NoPadding";
        private static final int KEY_SIZE = 256;
        private static final int GCM_TAG_LENGTH = 128;
        private static final int IV_LENGTH = 12;
        // 生成密钥
        public static SecretKey generateKey() throws Exception {
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            generator.init(KEY_SIZE);
            return generator.generateKey();
        }
        // 生成随机IV
        public static byte[] generateIV() {
            byte[] iv = new byte[IV_LENGTH];
            new SecureRandom().nextBytes(iv);
            return iv;
        }
        // 加密
        public static EncryptedData encrypt(byte[] data, SecretKey key) throws Exception {
            byte[] iv = generateIV();
            GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
            byte[] encrypted = cipher.doFinal(data);
            return new EncryptedData(iv, encrypted);
        }
        // 解密
        public static byte[] decrypt(EncryptedData encryptedData, SecretKey key) throws Exception {
            GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, encryptedData.getIv());
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, key, gcmSpec);
            return cipher.doFinal(encryptedData.getData());
        }
    }
    // 加密数据传输对象
    public static class EncryptedData {
        private byte[] iv;
        private byte[] data;
        public EncryptedData(byte[] iv, byte[] data) {
            this.iv = iv;
            this.data = data;
        }
        public byte[] getIv() { return iv; }
        public byte[] getData() { return data; }
    }
}

完整传输实现

客户端实现

import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Base64;
public class SecureClient {
    private Socket socket;
    private SecretKey sessionKey;
    private PublicKey serverPublicKey;
    public void connect(String host, int port) throws Exception {
        // 建立连接
        socket = new Socket(host, port);
        DataInputStream in = new DataInputStream(socket.getInputStream());
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        // 1. 获取服务器公钥
        int keyLength = in.readInt();
        byte[] keyBytes = new byte[keyLength];
        in.readFully(keyBytes);
        serverPublicKey = KeyUtils.bytesToPublicKey(keyBytes);
        // 2. 生成会话密钥
        sessionKey = CryptoUtils.AES.generateKey();
        // 3. 用服务器公钥加密会话密钥
        byte[] encryptedKey = CryptoUtils.RSA.encrypt(
            sessionKey.getEncoded(), serverPublicKey);
        // 4. 发送加密的会话密钥
        out.writeInt(encryptedKey.length);
        out.write(encryptedKey);
        out.flush();
        System.out.println("安全连接已建立");
    }
    public void send(String message) throws Exception {
        // 使用会话密钥加密消息
        CryptoUtils.EncryptedData encrypted = 
            CryptoUtils.AES.encrypt(message.getBytes("UTF-8"), sessionKey);
        // 发送加密数据
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        // 发送IV
        out.writeInt(encrypted.getIv().length);
        out.write(encrypted.getIv());
        // 发送加密数据
        out.writeInt(encrypted.getData().length);
        out.write(encrypted.getData());
        out.flush();
    }
    public String receive() throws Exception {
        DataInputStream in = new DataInputStream(socket.getInputStream());
        // 读取IV
        int ivLength = in.readInt();
        byte[] iv = new byte[ivLength];
        in.readFully(iv);
        // 读取加密数据
        int dataLength = in.readInt();
        byte[] data = new byte[dataLength];
        in.readFully(data);
        // 解密
        CryptoUtils.EncryptedData encrypted = new CryptoUtils.EncryptedData(iv, data);
        byte[] decrypted = CryptoUtils.AES.decrypt(encrypted, sessionKey);
        return new String(decrypted, "UTF-8");
    }
    public void close() throws IOException {
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }
}

服务端实现

import java.io.*;
import java.net.*;
import java.security.*;
public class SecureServer {
    private ServerSocket serverSocket;
    private KeyPair keyPair;
    public void start(int port) throws Exception {
        // 生成RSA密钥对
        keyPair = CryptoUtils.RSA.generateKeyPair();
        serverSocket = new ServerSocket(port);
        System.out.println("安全服务器启动在端口: " + port);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            new ClientHandler(clientSocket, keyPair).start();
        }
    }
    private static class ClientHandler extends Thread {
        private Socket socket;
        private KeyPair keyPair;
        private SecretKey sessionKey;
        public ClientHandler(Socket socket, KeyPair keyPair) {
            this.socket = socket;
            this.keyPair = keyPair;
        }
        @Override
        public void run() {
            try {
                handleClient();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void handleClient() throws Exception {
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // 1. 发送公钥
            byte[] publicKeyBytes = KeyUtils.publicKeyToBytes(keyPair.getPublic());
            out.writeInt(publicKeyBytes.length);
            out.write(publicKeyBytes);
            out.flush();
            // 2. 接收加密的会话密钥
            int keyLength = in.readInt();
            byte[] encryptedKey = new byte[keyLength];
            in.readFully(encryptedKey);
            // 3. 解密会话密钥
            byte[] keyBytes = CryptoUtils.RSA.decrypt(encryptedKey, keyPair.getPrivate());
            sessionKey = KeyUtils.bytesToSecretKey(keyBytes);
            System.out.println("客户端安全连接已建立");
            // 4. 处理客户端请求
            String request = receive();
            System.out.println("接收到加密请求: " + request);
            // 5. 发送加密响应
            String response = "处理完成: " + request;
            send(response);
        }
        private String receive() throws Exception {
            // 读取IV
            int ivLength = in.readInt();
            byte[] iv = new byte[ivLength];
            in.readFully(iv);
            // 读取加密数据
            int dataLength = in.readInt();
            byte[] data = new byte[dataLength];
            in.readFully(data);
            // 解密
            CryptoUtils.EncryptedData encrypted = new CryptoUtils.EncryptedData(iv, data);
            byte[] decrypted = CryptoUtils.AES.decrypt(encrypted, sessionKey);
            return new String(decrypted, "UTF-8");
        }
        private void send(String message) throws Exception {
            CryptoUtils.EncryptedData encrypted = 
                CryptoUtils.AES.encrypt(message.getBytes("UTF-8"), sessionKey);
            // 发送IV
            out.writeInt(encrypted.getIv().length);
            out.write(encrypted.getIv());
            // 发送加密数据
            out.writeInt(encrypted.getData().length);
            out.write(encrypted.getData());
            out.flush();
        }
    }
}

密钥工具类

import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class KeyUtils {
    // 公钥转字节数组
    public static byte[] publicKeyToBytes(PublicKey key) {
        return key.getEncoded();
    }
    // 字节数组转公钥
    public static PublicKey bytesToPublicKey(byte[] bytes) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }
    // 私钥转字节数组
    public static byte[] privateKeyToBytes(PrivateKey key) {
        return key.getEncoded();
    }
    // 字节数组转私钥
    public static PrivateKey bytesToPrivateKey(byte[] bytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }
    // 字节数组转AES密钥
    public static SecretKey bytesToSecretKey(byte[] bytes) {
        return new SecretKeySpec(bytes, "AES");
    }
}

使用示例

// 启动服务器
public class ServerApplication {
    public static void main(String[] args) throws Exception {
        SecureServer server = new SecureServer();
        server.start(8443);  // 安全端口
    }
}
// 客户端使用
public class ClientApplication {
    public static void main(String[] args) throws Exception {
        SecureClient client = new SecureClient();
        try {
            // 连接服务器
            client.connect("localhost", 8443);
            // 发送加密消息
            client.send("Hello, Secure Server!");
            // 接收加密响应
            String response = client.receive();
            System.out.println("服务器响应: " + response);
        } finally {
            client.close();
        }
    }
}

安全增强建议

证书验证

public class CertificateValidator {
    public static boolean validateCertificate(X509Certificate cert) {
        try {
            // 验证证书有效期
            cert.checkValidity();
            // 验证签名
            cert.verify(cert.getPublicKey());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

完美前向安全性

// 使用ECDHE进行密钥交换
public class ECDHEKeyExchange {
    public static KeyAgreement performKeyExchange() throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(256);
        KeyPair kp = kpg.generateKeyPair();
        KeyAgreement ka = KeyAgreement.getInstance("ECDH");
        ka.init(kp.getPrivate());
        return ka;
    }
}

消息完整性验证

public class MessageIntegrity {
    public static byte[] addMAC(byte[] data, SecretKey key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] macBytes = mac.doFinal(data);
        // 合并数据和MAC
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(data);
        baos.write(macBytes);
        return baos.toByteArray();
    }
}

这个加密传输框架提供了完整的端到端加密解决方案,确保了数据传输的机密性、完整性和安全性,根据具体需求可以调整加密算法和密钥长度。

抱歉,评论功能暂时关闭!