AES+RSA混合加密:交易链路安全保护实战

1. 混合加密概述

在金融交易系统中,数据安全至关重要。AES+RSA混合加密结合了对称加密的高效性和非对称加密的安全性,为交易链路提供全面的安全保护。本文将详细介绍混合加密算法、交易链路保护、密钥管理、数字签名和安全传输的完整解决方案。

1.1 核心功能

  1. 混合加密: AES对称加密+RSA非对称加密
  2. 交易链路保护: 端到端数据加密传输
  3. 密钥管理: 安全的密钥生成、存储和分发
  4. 数字签名: 数据完整性验证和身份认证
  5. 安全传输: HTTPS+加密的双重保护

1.2 技术架构

1
2
3
4
5
客户端 → 混合加密 → 安全传输 → 服务端
↓ ↓ ↓ ↓
数据加密 → AES加密 → RSA加密 → 数据解密
↓ ↓ ↓ ↓
签名验证 → 数字签名 → 传输加密 → 签名验证

2. 混合加密配置

2.1 Maven依赖配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Bouncy Castle加密库 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>

<!-- Apache Commons Codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>

<!-- Jackson JSON处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>

2.2 混合加密配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* 混合加密配置类
*/
@Configuration
public class HybridEncryptionConfig {

@Value("${encryption.aes.key-size:256}")
private int aesKeySize;

@Value("${encryption.rsa.key-size:2048}")
private int rsaKeySize;

@Value("${encryption.aes.algorithm:AES}")
private String aesAlgorithm;

@Value("${encryption.rsa.algorithm:RSA}")
private String rsaAlgorithm;

@Value("${encryption.signature.algorithm:SHA256withRSA}")
private String signatureAlgorithm;

/**
* 混合加密配置属性
*/
@Bean
public HybridEncryptionProperties hybridEncryptionProperties() {
return HybridEncryptionProperties.builder()
.aesKeySize(aesKeySize)
.rsaKeySize(rsaKeySize)
.aesAlgorithm(aesAlgorithm)
.rsaAlgorithm(rsaAlgorithm)
.signatureAlgorithm(signatureAlgorithm)
.build();
}

/**
* 混合加密服务
*/
@Bean
public HybridEncryptionService hybridEncryptionService() {
return new HybridEncryptionService(hybridEncryptionProperties());
}

/**
* 密钥管理服务
*/
@Bean
public KeyManagementService keyManagementService() {
return new KeyManagementService(hybridEncryptionProperties());
}

/**
* 数字签名服务
*/
@Bean
public DigitalSignatureService digitalSignatureService() {
return new DigitalSignatureService(hybridEncryptionProperties());
}
}

/**
* 混合加密配置属性
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HybridEncryptionProperties {
private int aesKeySize;
private int rsaKeySize;
private String aesAlgorithm;
private String rsaAlgorithm;
private String signatureAlgorithm;

// 加密配置
private String cipherTransformation = "AES/CBC/PKCS5Padding";
private String rsaTransformation = "RSA/ECB/PKCS1Padding";
private int ivLength = 16;

// 密钥配置
private String keyStorePath = "keystore.jks";
private String keyStorePassword = "changeit";
private String keyAlias = "hybrid-key";

// 安全配置
private boolean enableSignature = true;
private boolean enableCompression = true;
private int maxDataSize = 1024 * 1024; // 1MB
}

3. 数据模型定义

3.1 加密数据模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* 加密请求模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EncryptedRequest {
private String encryptedData;
private String encryptedKey;
private String signature;
private String timestamp;
private String requestId;
private String clientId;
}

/**
* 加密响应模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EncryptedResponse {
private String encryptedData;
private String signature;
private String timestamp;
private String responseId;
private String serverId;
private boolean success;
private String errorMessage;
}

/**
* 密钥对模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class KeyPair {
private String publicKey;
private String privateKey;
private String keyId;
private LocalDateTime createTime;
private LocalDateTime expireTime;
private String keyType; // AES, RSA
}

/**
* 加密结果模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EncryptionResult {
private boolean success;
private String encryptedData;
private String encryptedKey;
private String signature;
private String errorMessage;
private LocalDateTime timestamp;
}

/**
* 解密结果模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DecryptionResult {
private boolean success;
private String decryptedData;
private String signature;
private boolean signatureValid;
private String errorMessage;
private LocalDateTime timestamp;
}

/**
* 交易数据模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TransactionData {
private String transactionId;
private String userId;
private BigDecimal amount;
private String currency;
private String transactionType;
private String description;
private LocalDateTime timestamp;
private Map<String, Object> metadata;
}

4. 混合加密服务

4.1 混合加密服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
* 混合加密服务
*/
@Service
public class HybridEncryptionService {

private final HybridEncryptionProperties properties;
private final KeyManagementService keyManagementService;
private final DigitalSignatureService signatureService;

public HybridEncryptionService(HybridEncryptionProperties properties) {
this.properties = properties;
this.keyManagementService = new KeyManagementService(properties);
this.signatureService = new DigitalSignatureService(properties);
}

/**
* 混合加密数据
* @param data 原始数据
* @param publicKey RSA公钥
* @return 加密结果
*/
public EncryptionResult encrypt(String data, String publicKey) {
try {
// 1. 生成AES密钥
SecretKey aesKey = generateAESKey();

// 2. AES加密数据
String encryptedData = encryptWithAES(data, aesKey);

// 3. RSA加密AES密钥
String encryptedKey = encryptAESKeyWithRSA(aesKey, publicKey);

// 4. 数字签名
String signature = null;
if (properties.isEnableSignature()) {
signature = signatureService.sign(encryptedData);
}

return EncryptionResult.builder()
.success(true)
.encryptedData(encryptedData)
.encryptedKey(encryptedKey)
.signature(signature)
.timestamp(LocalDateTime.now())
.build();

} catch (Exception e) {
log.error("混合加密失败", e);
return EncryptionResult.builder()
.success(false)
.errorMessage("加密失败: " + e.getMessage())
.timestamp(LocalDateTime.now())
.build();
}
}

/**
* 混合解密数据
* @param encryptedData 加密数据
* @param encryptedKey 加密的AES密钥
* @param signature 数字签名
* @param privateKey RSA私钥
* @return 解密结果
*/
public DecryptionResult decrypt(String encryptedData, String encryptedKey,
String signature, String privateKey) {
try {
// 1. RSA解密AES密钥
SecretKey aesKey = decryptAESKeyWithRSA(encryptedKey, privateKey);

// 2. AES解密数据
String decryptedData = decryptWithAES(encryptedData, aesKey);

// 3. 验证数字签名
boolean signatureValid = true;
if (properties.isEnableSignature() && signature != null) {
signatureValid = signatureService.verify(encryptedData, signature);
}

return DecryptionResult.builder()
.success(true)
.decryptedData(decryptedData)
.signature(signature)
.signatureValid(signatureValid)
.timestamp(LocalDateTime.now())
.build();

} catch (Exception e) {
log.error("混合解密失败", e);
return DecryptionResult.builder()
.success(false)
.errorMessage("解密失败: " + e.getMessage())
.timestamp(LocalDateTime.now())
.build();
}
}

/**
* 加密交易数据
* @param transactionData 交易数据
* @param publicKey RSA公钥
* @return 加密结果
*/
public EncryptionResult encryptTransaction(TransactionData transactionData, String publicKey) {
try {
// 1. 序列化交易数据
String jsonData = objectToJson(transactionData);

// 2. 压缩数据(可选)
String dataToEncrypt = jsonData;
if (properties.isEnableCompression()) {
dataToEncrypt = compressData(jsonData);
}

// 3. 混合加密
return encrypt(dataToEncrypt, publicKey);

} catch (Exception e) {
log.error("加密交易数据失败", e);
return EncryptionResult.builder()
.success(false)
.errorMessage("加密交易数据失败: " + e.getMessage())
.timestamp(LocalDateTime.now())
.build();
}
}

/**
* 解密交易数据
* @param encryptedData 加密数据
* @param encryptedKey 加密的AES密钥
* @param signature 数字签名
* @param privateKey RSA私钥
* @return 解密结果
*/
public DecryptionResult decryptTransaction(String encryptedData, String encryptedKey,
String signature, String privateKey) {
try {
// 1. 混合解密
DecryptionResult result = decrypt(encryptedData, encryptedKey, signature, privateKey);

if (!result.isSuccess()) {
return result;
}

// 2. 解压缩数据(如果启用了压缩)
String jsonData = result.getDecryptedData();
if (properties.isEnableCompression()) {
jsonData = decompressData(jsonData);
}

// 3. 反序列化交易数据
TransactionData transactionData = jsonToObject(jsonData, TransactionData.class);

return DecryptionResult.builder()
.success(true)
.decryptedData(jsonData)
.signature(result.getSignature())
.signatureValid(result.isSignatureValid())
.timestamp(LocalDateTime.now())
.build();

} catch (Exception e) {
log.error("解密交易数据失败", e);
return DecryptionResult.builder()
.success(false)
.errorMessage("解密交易数据失败: " + e.getMessage())
.timestamp(LocalDateTime.now())
.build();
}
}

/**
* 生成AES密钥
* @return AES密钥
*/
private SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(properties.getAesAlgorithm());
keyGenerator.init(properties.getAesKeySize());
return keyGenerator.generateKey();
}

/**
* AES加密
* @param data 原始数据
* @param key AES密钥
* @return 加密数据
*/
private String encryptWithAES(String data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance(properties.getCipherTransformation());
cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] iv = cipher.getIV();

// 将IV和加密数据合并
byte[] combined = new byte[iv.length + encryptedBytes.length];
System.arraycopy(iv, 0, combined, 0, iv.length);
System.arraycopy(encryptedBytes, 0, combined, iv.length, encryptedBytes.length);

return Base64.getEncoder().encodeToString(combined);
}

/**
* AES解密
* @param encryptedData 加密数据
* @param key AES密钥
* @return 解密数据
*/
private String decryptWithAES(String encryptedData, SecretKey key) throws Exception {
byte[] combined = Base64.getDecoder().decode(encryptedData);

// 分离IV和加密数据
byte[] iv = new byte[properties.getIvLength()];
byte[] encryptedBytes = new byte[combined.length - iv.length];
System.arraycopy(combined, 0, iv, 0, iv.length);
System.arraycopy(combined, iv.length, encryptedBytes, 0, encryptedBytes.length);

Cipher cipher = Cipher.getInstance(properties.getCipherTransformation());
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}

/**
* RSA加密AES密钥
* @param aesKey AES密钥
* @param publicKey RSA公钥
* @return 加密的AES密钥
*/
private String encryptAESKeyWithRSA(SecretKey aesKey, String publicKey) throws Exception {
PublicKey rsaPublicKey = keyManagementService.getPublicKeyFromString(publicKey);
Cipher cipher = Cipher.getInstance(properties.getRsaTransformation());
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

byte[] encryptedKey = cipher.doFinal(aesKey.getEncoded());
return Base64.getEncoder().encodeToString(encryptedKey);
}

/**
* RSA解密AES密钥
* @param encryptedKey 加密的AES密钥
* @param privateKey RSA私钥
* @return AES密钥
*/
private SecretKey decryptAESKeyWithRSA(String encryptedKey, String privateKey) throws Exception {
PrivateKey rsaPrivateKey = keyManagementService.getPrivateKeyFromString(privateKey);
Cipher cipher = Cipher.getInstance(properties.getRsaTransformation());
cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);

byte[] decryptedKey = cipher.doFinal(Base64.getDecoder().decode(encryptedKey));
return new SecretKeySpec(decryptedKey, properties.getAesAlgorithm());
}

/**
* 对象转JSON
* @param obj 对象
* @return JSON字符串
*/
private String objectToJson(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
}

/**
* JSON转对象
* @param json JSON字符串
* @param clazz 目标类型
* @return 对象
*/
private <T> T jsonToObject(String json, Class<T> clazz) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, clazz);
}

/**
* 压缩数据
* @param data 原始数据
* @return 压缩数据
*/
private String compressData(String data) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write(data.getBytes(StandardCharsets.UTF_8));
gzos.close();

byte[] compressed = baos.toByteArray();
return Base64.getEncoder().encodeToString(compressed);
}

/**
* 解压缩数据
* @param compressedData 压缩数据
* @return 原始数据
*/
private String decompressData(String compressedData) throws Exception {
byte[] compressed = Base64.getDecoder().decode(compressedData);

ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
GZIPInputStream gzis = new GZIPInputStream(bais);

byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
while ((len = gzis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
gzis.close();

return baos.toString(StandardCharsets.UTF_8.name());
}
}

5. 密钥管理服务

5.1 密钥管理服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
* 密钥管理服务
*/
@Service
public class KeyManagementService {

private final HybridEncryptionProperties properties;
private final Map<String, KeyPair> keyCache = new ConcurrentHashMap<>();

public KeyManagementService(HybridEncryptionProperties properties) {
this.properties = properties;
}

/**
* 生成RSA密钥对
* @return RSA密钥对
*/
public KeyPair generateRSAKeyPair() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(properties.getRsaAlgorithm());
keyPairGenerator.initialize(properties.getRsaKeySize());
java.security.KeyPair keyPair = keyPairGenerator.generateKeyPair();

String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
String keyId = UUID.randomUUID().toString();

KeyPair result = KeyPair.builder()
.publicKey(publicKey)
.privateKey(privateKey)
.keyId(keyId)
.createTime(LocalDateTime.now())
.expireTime(LocalDateTime.now().plusDays(365))
.keyType("RSA")
.build();

keyCache.put(keyId, result);

return result;

} catch (Exception e) {
log.error("生成RSA密钥对失败", e);
throw new RuntimeException("生成RSA密钥对失败", e);
}
}

/**
* 生成AES密钥
* @return AES密钥
*/
public String generateAESKey() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(properties.getAesAlgorithm());
keyGenerator.init(properties.getAesKeySize());
SecretKey secretKey = keyGenerator.generateKey();

return Base64.getEncoder().encodeToString(secretKey.getEncoded());

} catch (Exception e) {
log.error("生成AES密钥失败", e);
throw new RuntimeException("生成AES密钥失败", e);
}
}

/**
* 从字符串获取公钥
* @param publicKeyString 公钥字符串
* @return 公钥
*/
public PublicKey getPublicKeyFromString(String publicKeyString) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(properties.getRsaAlgorithm());
return keyFactory.generatePublic(spec);
}

/**
* 从字符串获取私钥
* @param privateKeyString 私钥字符串
* @return 私钥
*/
public PrivateKey getPrivateKeyFromString(String privateKeyString) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(properties.getRsaAlgorithm());
return keyFactory.generatePrivate(spec);
}

/**
* 获取密钥对
* @param keyId 密钥ID
* @return 密钥对
*/
public KeyPair getKeyPair(String keyId) {
return keyCache.get(keyId);
}

/**
* 保存密钥对
* @param keyPair 密钥对
*/
public void saveKeyPair(KeyPair keyPair) {
keyCache.put(keyPair.getKeyId(), keyPair);
}

/**
* 删除密钥对
* @param keyId 密钥ID
*/
public void deleteKeyPair(String keyId) {
keyCache.remove(keyId);
}

/**
* 获取所有密钥对
* @return 密钥对列表
*/
public List<KeyPair> getAllKeyPairs() {
return new ArrayList<>(keyCache.values());
}

/**
* 检查密钥是否过期
* @param keyId 密钥ID
* @return 是否过期
*/
public boolean isKeyExpired(String keyId) {
KeyPair keyPair = keyCache.get(keyId);
if (keyPair == null) {
return true;
}
return LocalDateTime.now().isAfter(keyPair.getExpireTime());
}
}

6. 数字签名服务

6.1 数字签名服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* 数字签名服务
*/
@Service
public class DigitalSignatureService {

private final HybridEncryptionProperties properties;
private final KeyManagementService keyManagementService;

public DigitalSignatureService(HybridEncryptionProperties properties) {
this.properties = properties;
this.keyManagementService = new KeyManagementService(properties);
}

/**
* 数字签名
* @param data 原始数据
* @return 签名
*/
public String sign(String data) {
try {
// 使用默认私钥进行签名
String defaultPrivateKey = getDefaultPrivateKey();
return sign(data, defaultPrivateKey);

} catch (Exception e) {
log.error("数字签名失败", e);
throw new RuntimeException("数字签名失败", e);
}
}

/**
* 数字签名
* @param data 原始数据
* @param privateKey 私钥
* @return 签名
*/
public String sign(String data, String privateKey) {
try {
PrivateKey rsaPrivateKey = keyManagementService.getPrivateKeyFromString(privateKey);
Signature signature = Signature.getInstance(properties.getSignatureAlgorithm());
signature.initSign(rsaPrivateKey);
signature.update(data.getBytes(StandardCharsets.UTF_8));

byte[] signatureBytes = signature.sign();
return Base64.getEncoder().encodeToString(signatureBytes);

} catch (Exception e) {
log.error("数字签名失败", e);
throw new RuntimeException("数字签名失败", e);
}
}

/**
* 验证数字签名
* @param data 原始数据
* @param signature 签名
* @return 是否有效
*/
public boolean verify(String data, String signature) {
try {
// 使用默认公钥进行验证
String defaultPublicKey = getDefaultPublicKey();
return verify(data, signature, defaultPublicKey);

} catch (Exception e) {
log.error("验证数字签名失败", e);
return false;
}
}

/**
* 验证数字签名
* @param data 原始数据
* @param signature 签名
* @param publicKey 公钥
* @return 是否有效
*/
public boolean verify(String data, String signature, String publicKey) {
try {
PublicKey rsaPublicKey = keyManagementService.getPublicKeyFromString(publicKey);
Signature sig = Signature.getInstance(properties.getSignatureAlgorithm());
sig.initVerify(rsaPublicKey);
sig.update(data.getBytes(StandardCharsets.UTF_8));

byte[] signatureBytes = Base64.getDecoder().decode(signature);
return sig.verify(signatureBytes);

} catch (Exception e) {
log.error("验证数字签名失败", e);
return false;
}
}

/**
* 获取默认私钥
* @return 默认私钥
*/
private String getDefaultPrivateKey() {
// 这里应该从安全的密钥存储中获取
// 为了演示,使用硬编码的密钥
return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...";
}

/**
* 获取默认公钥
* @return 默认公钥
*/
private String getDefaultPublicKey() {
// 这里应该从安全的密钥存储中获取
// 为了演示,使用硬编码的密钥
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...";
}
}

7. 交易链路加密控制器

7.1 交易链路加密控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/**
* 交易链路加密控制器
*/
@RestController
@RequestMapping("/encryption")
public class TransactionEncryptionController {

@Autowired
private HybridEncryptionService encryptionService;

@Autowired
private KeyManagementService keyManagementService;

@Autowired
private DigitalSignatureService signatureService;

/**
* 加密交易数据
*/
@PostMapping("/encrypt-transaction")
public ResponseEntity<Map<String, Object>> encryptTransaction(@RequestBody TransactionData transactionData) {
try {
// 1. 获取客户端公钥
String clientPublicKey = getClientPublicKey();

// 2. 加密交易数据
EncryptionResult result = encryptionService.encryptTransaction(transactionData, clientPublicKey);

// 3. 构建响应
Map<String, Object> response = new HashMap<>();
response.put("success", result.isSuccess());
response.put("encryptedData", result.getEncryptedData());
response.put("encryptedKey", result.getEncryptedKey());
response.put("signature", result.getSignature());
response.put("timestamp", result.getTimestamp());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("加密交易数据失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "加密失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 解密交易数据
*/
@PostMapping("/decrypt-transaction")
public ResponseEntity<Map<String, Object>> decryptTransaction(@RequestBody EncryptedRequest request) {
try {
// 1. 获取服务端私钥
String serverPrivateKey = getServerPrivateKey();

// 2. 解密交易数据
DecryptionResult result = encryptionService.decryptTransaction(
request.getEncryptedData(),
request.getEncryptedKey(),
request.getSignature(),
serverPrivateKey
);

// 3. 构建响应
Map<String, Object> response = new HashMap<>();
response.put("success", result.isSuccess());
response.put("decryptedData", result.getDecryptedData());
response.put("signatureValid", result.isSignatureValid());
response.put("timestamp", result.getTimestamp());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("解密交易数据失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "解密失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 生成密钥对
*/
@PostMapping("/generate-keypair")
public ResponseEntity<Map<String, Object>> generateKeyPair() {
try {
KeyPair keyPair = keyManagementService.generateRSAKeyPair();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("keyId", keyPair.getKeyId());
response.put("publicKey", keyPair.getPublicKey());
response.put("createTime", keyPair.getCreateTime());
response.put("expireTime", keyPair.getExpireTime());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("生成密钥对失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "生成密钥对失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 验证数字签名
*/
@PostMapping("/verify-signature")
public ResponseEntity<Map<String, Object>> verifySignature(
@RequestParam String data,
@RequestParam String signature,
@RequestParam String publicKey) {
try {
boolean isValid = signatureService.verify(data, signature, publicKey);

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("valid", isValid);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("验证数字签名失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "验证数字签名失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取客户端公钥
* @return 客户端公钥
*/
private String getClientPublicKey() {
// 这里应该从客户端证书或密钥管理中获取
// 为了演示,返回一个示例公钥
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...";
}

/**
* 获取服务端私钥
* @return 服务端私钥
*/
private String getServerPrivateKey() {
// 这里应该从安全的密钥存储中获取
// 为了演示,返回一个示例私钥
return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...";
}
}

8. 总结

通过AES+RSA混合加密的实现,我们成功构建了一个交易链路安全保护系统。关键特性包括:

8.1 核心优势

  1. 混合加密: AES对称加密+RSA非对称加密
  2. 交易链路保护: 端到端数据加密传输
  3. 密钥管理: 安全的密钥生成、存储和分发
  4. 数字签名: 数据完整性验证和身份认证
  5. 安全传输: HTTPS+加密的双重保护

8.2 最佳实践

  1. 加密策略: 完善的混合加密策略
  2. 密钥管理: 安全的密钥生成和管理
  3. 数字签名: 可靠的数据完整性验证
  4. 安全传输: 端到端的安全传输机制
  5. 性能优化: 高效的加密和解密处理

这套AES+RSA混合加密方案不仅能够提供交易链路的安全保护,还包含了密钥管理、数字签名、安全传输等核心功能,是金融系统的重要安全基础设施。