feat(安全): 店铺凭据解密支持历史密钥,为轮换留出双密钥窗口

换 shop-credential-key 会让 435 行历史密文全部解不开,而调用方拿到解不开的串
是当明文口令往外发(紫鸟账号、1688 店铺、第三方 api_key 都这样用)。
现在新增 aiimage.security.shop-credential-key-previous(逗号分隔),解密按
当前→历史的顺序回试,加密只用当前密钥;全部不中时 WARN 写明"这串密文会被
当成明文口令发出去",不再静默回退。与当前密钥相同的历史项自动丢弃。
previous 留空时行为与改动前逐字节一致(6 例单测盯着这一条)。
轮换设计与取证见 docs/ops/credential-rotation-design-2026-10-02.md(只含长度与
sha8 指纹,无明文值);轮换本身与存量重加密脚本仍未做。
This commit is contained in:
2026-10-02 11:01:18 +08:00
parent 5f7f37c788
commit 8812a3b64a
4 changed files with 270 additions and 16 deletions
@@ -10,7 +10,9 @@ import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@Service
@Slf4j
@@ -21,7 +23,12 @@ public class ShopCredentialCryptoService {
@Value("${aiimage.security.shop-credential-key:change-me-shop-credential-key}")
private String rawKey;
/** 轮换过渡期用:逗号分隔的旧密钥,解密时按顺序回试,加密只用当前密钥。 */
@Value("${aiimage.security.shop-credential-key-previous:}")
private String previousKeys;
private SecretKeySpec keySpec;
private List<SecretKeySpec> previousKeySpecs = List.of();
@PostConstruct
public void init() {
@@ -30,16 +37,31 @@ public class ShopCredentialCryptoService {
log.warn("[security] AIIMAGE_SHOP_CREDENTIAL_KEY 未配置或仍为默认值,店铺凭据加密强度不足,"
+ "请通过环境变量 AIIMAGE_SHOP_CREDENTIAL_KEY 配置固定密钥");
}
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] full = sha256.digest(rawKey.getBytes(StandardCharsets.UTF_8));
byte[] key16 = new byte[16];
System.arraycopy(full, 0, key16, 0, 16);
this.keySpec = new SecretKeySpec(key16, "AES");
this.keySpec = deriveKey(rawKey);
List<SecretKeySpec> previous = new ArrayList<>();
for (String old : (previousKeys == null ? "" : previousKeys).split(",")) {
if (old.isBlank()) {
continue;
}
SecretKeySpec spec = deriveKey(old.trim());
if (!spec.equals(keySpec)) {
previous.add(spec);
}
}
this.previousKeySpecs = List.copyOf(previous);
} catch (Exception ex) {
throw new BusinessException("初始化店铺凭据加密器失败");
}
}
private SecretKeySpec deriveKey(String key) throws Exception {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] full = sha256.digest(key.getBytes(StandardCharsets.UTF_8));
byte[] key16 = new byte[16];
System.arraycopy(full, 0, key16, 0, 16);
return new SecretKeySpec(key16, "AES");
}
public String encrypt(String plainText) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
@@ -52,17 +74,26 @@ public class ShopCredentialCryptoService {
}
public String decrypt(String cipherText) {
try {
if (cipherText == null || cipherText.isBlank()) {
return "";
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception ex) {
// 兼容历史数据:旧记录可能是明文或使用旧密钥加密,回退原文避免中断自动化流程。
return cipherText == null ? "" : cipherText;
if (cipherText == null || cipherText.isBlank()) {
return "";
}
List<SecretKeySpec> candidates = new ArrayList<>();
candidates.add(keySpec);
candidates.addAll(previousKeySpecs);
for (SecretKeySpec key : candidates) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception ex) {
// 换下一个密钥再试
}
}
// 兼容历史数据:旧记录可能是明文;回退原文会让调用方把密文当口令用,所以要出声
log.warn("[security] 凭据解密失败(当前密钥 + {} 个历史密钥都试过),回退原文;"
+ "刚轮换过 shop-credential-key 的话这条还没重加密,这串密文会被当成明文口令发出去",
previousKeySpecs.size());
return cipherText;
}
}
@@ -464,6 +464,8 @@ aiimage:
unread-retention-days: ${AIIMAGE_NOTIFICATION_UNREAD_RETENTION_DAYS:180}
security:
shop-credential-key: ${AIIMAGE_SHOP_CREDENTIAL_KEY:change-me-shop-credential-key}
# 轮换过渡期用:逗号分隔的旧密钥,解密按顺序回试,加密只用上面那个;迁完就清空
shop-credential-key-previous: ${AIIMAGE_SHOP_CREDENTIAL_KEY_PREVIOUS:}
internal-token: ${AIIMAGE_INTERNAL_TOKEN:}
internal-token-file: ${AIIMAGE_INTERNAL_TOKEN_FILE:}
auth:
@@ -0,0 +1,96 @@
package com.nanri.aiimage.common.security;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 店铺凭据/用户密钥加密器的轮换语义测试。
* 关键契约:轮换后旧密文必须还能解(按 previous 回试),且全部解不开时是「回退原文」而不是抛错——
* 这条回退会把密文当明文口令发出去,所以轮换必须配合重加密,见 crawler-plugin/docs/ops/credential-rotation-design-2026-10-02.md。
*/
class ShopCredentialCryptoServiceTest {
private static final String OLD_KEY = "old-key-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
private static final String NEW_KEY = "new-key-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
private static final String THIRD_KEY = "third-key-cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
private static ShopCredentialCryptoService newService(String rawKey, String previousKeys) throws Exception {
ShopCredentialCryptoService service = new ShopCredentialCryptoService();
set(service, "rawKey", rawKey);
set(service, "previousKeys", previousKeys);
service.init();
return service;
}
private static void set(Object target, String name, String value) throws Exception {
Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(target, value);
}
@SuppressWarnings("unchecked")
private static List<Object> previousOf(ShopCredentialCryptoService service) throws Exception {
Field field = service.getClass().getDeclaredField("previousKeySpecs");
field.setAccessible(true);
return (List<Object>) field.get(service);
}
@Test
void rotates_key_but_still_decrypts_legacy_ciphertext() throws Exception {
ShopCredentialCryptoService old = newService(OLD_KEY, "");
ShopCredentialCryptoService rotated = newService(NEW_KEY, OLD_KEY);
String legacy = old.encrypt("P@ssw0rd-shopA");
assertEquals("P@ssw0rd-shopA", rotated.decrypt(legacy));
assertNotEquals(old.encrypt("same-input"), rotated.encrypt("same-input"), "加密只用当前密钥");
assertEquals("same-input", rotated.decrypt(rotated.encrypt("same-input")));
}
@Test
void falls_back_to_the_input_when_no_key_matches() throws Exception {
String legacy = newService(OLD_KEY, "").encrypt("P@ssw0rd-shopA");
ShopCredentialCryptoService wrong = newService(NEW_KEY, THIRD_KEY);
assertEquals(legacy, wrong.decrypt(legacy), "回退原文是既有兼容行为,不能借轮换悄悄改成抛错");
}
@Test
void legacy_plaintext_values_pass_through_unchanged() throws Exception {
ShopCredentialCryptoService service = newService(NEW_KEY, "");
assertEquals("not-a-ciphertext!!", service.decrypt("not-a-ciphertext!!"));
assertEquals("", service.decrypt(null));
assertEquals("", service.decrypt(" "));
}
@Test
void behaves_exactly_as_before_when_previous_keys_is_empty() throws Exception {
ShopCredentialCryptoService service = newService(NEW_KEY, "");
String cipher = service.encrypt("v");
assertEquals("v", service.decrypt(cipher));
assertTrue(previousOf(service).isEmpty());
}
@Test
void drops_previous_keys_that_equal_the_current_key() throws Exception {
ShopCredentialCryptoService service = newService(NEW_KEY, NEW_KEY + " , ," + NEW_KEY);
assertTrue(previousOf(service).isEmpty(), "重复密钥白跑一遍解密,还会掩盖 previous 其实没配");
}
@Test
void tries_several_previous_keys_in_order() throws Exception {
String fromThird = newService(THIRD_KEY, "").encrypt("v");
ShopCredentialCryptoService service = newService(NEW_KEY, OLD_KEY + "," + THIRD_KEY);
assertEquals("v", service.decrypt(fromThird));
assertEquals(2, previousOf(service).size());
}
}