ArtList 手机号加密改造:新增 V2 迁移与 PhoneCrypto,登录注册与查询统一走 phone_hash,对外输出脱敏
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s

This commit is contained in:
2026-11-04 19:53:50 +08:00
parent 6e4ee2cd54
commit 772835d80d
18 changed files with 513 additions and 69 deletions
@@ -1,6 +1,7 @@
package com.xiaowang.jayucloud.artlist.core.config; package com.xiaowang.jayucloud.artlist.core.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
log.info("start insert fill ...."); log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
fillPhoneHashes(metaObject);
} }
@Override @Override
@@ -37,5 +39,25 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
public void updateFill(MetaObject metaObject) { public void updateFill(MetaObject metaObject) {
log.info("start update fill ...."); log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
fillPhoneHashes(metaObject);
}
/**
* 实体写入时按明文手机号刷新哈希列。
* 注意:QueryWrapper/UpdateWrapper 的 set 不会经过这里,删除等场景需显式置空哈希。
*/
private void fillPhoneHashes(MetaObject metaObject) {
if (metaObject.hasSetter("phoneHash")) {
Object phone = getFieldValByName("phone", metaObject);
if (phone != null) {
setFieldValByName("phoneHash", PhoneCrypto.current().index(String.valueOf(phone)), metaObject);
}
}
if (metaObject.hasSetter("contactPhoneHash")) {
Object contactPhone = getFieldValByName("contactPhone", metaObject);
if (contactPhone != null) {
setFieldValByName("contactPhoneHash", PhoneCrypto.current().index(String.valueOf(contactPhone)), metaObject);
}
}
} }
} }
@@ -0,0 +1,17 @@
package com.xiaowang.jayucloud.artlist.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 手机号加密配置。密钥口径与 JC-Salon-Core 完全一致,保证两条业务线的 phone_hash 可比对。
* 配置位置:Nacos jayucloud-artlist / DEFAULT_GROUP / secret.yaml。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-artlist.privacy.phone-crypto")
public class PhoneCryptoProperties {
private String encryptionKey;
private String indexKey;
}
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl;
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
@@ -51,6 +52,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final MessageHubClientService messageHubClientService; private final MessageHubClientService messageHubClientService;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -94,15 +96,16 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
public void sendVerificationCode(String phone, String sceneCode) { public void sendVerificationCode(String phone, String sceneCode) {
String code = generateVerificationCode(); String code = generateVerificationCode();
String codeKey = CODE_PREFIX + phone; String phoneKey = phoneCrypto.index(phone);
String sendTimeKey = SEND_TIME_PREFIX + phone; String codeKey = CODE_PREFIX + phoneKey;
String sendTimeKey = SEND_TIME_PREFIX + phoneKey;
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); log.info("验证码已发送,手机号: {}, sceneCode: {}", phoneCrypto.mask(phone), sceneCode);
} }
@Override @Override
@@ -114,21 +117,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* @return boolean result consumed by the caller or returned to the frontend * @return boolean result consumed by the caller or returned to the frontend
*/ */
public boolean verifyCode(String phone, String code) { public boolean verifyCode(String phone, String code) {
String codeKey = CODE_PREFIX + phone; String codeKey = CODE_PREFIX + phoneCrypto.index(phone);
String storedCode = redisTemplate.opsForValue().get(codeKey); String storedCode = redisTemplate.opsForValue().get(codeKey);
if (storedCode == null) { if (storedCode == null) {
log.warn("验证码不存在或已过期,手机号: {}", phone); log.warn("验证码不存在或已过期,手机号: {}", phoneCrypto.mask(phone));
return false; return false;
} }
if (!storedCode.equals(code)) { if (!storedCode.equals(code)) {
log.warn("验证码错误,手机号: {}", phone); log.warn("验证码错误,手机号: {}", phoneCrypto.mask(phone));
return false; return false;
} }
redisTemplate.delete(codeKey); redisTemplate.delete(codeKey);
log.info("验证码验证成功,手机号: {}", phone); log.info("验证码验证成功,手机号: {}", phoneCrypto.mask(phone));
return true; return true;
} }
@@ -140,7 +143,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* @return boolean result consumed by the caller or returned to the frontend * @return boolean result consumed by the caller or returned to the frontend
*/ */
public boolean canResend(String phone) { public boolean canResend(String phone) {
String sendTimeKey = SEND_TIME_PREFIX + phone; String sendTimeKey = SEND_TIME_PREFIX + phoneCrypto.index(phone);
String sendTime = redisTemplate.opsForValue().get(sendTimeKey); String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
return sendTime == null; return sendTime == null;
} }
@@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLogi
import lombok.Data; import lombok.Data;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -87,6 +88,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -350,7 +352,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
} }
return userMapper.selectOne( return userMapper.selectOne(
new LambdaQueryWrapper<UserDO>() new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getPhone, phone) .eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
.last("limit 1") .last("limit 1")
); );
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.security.entity.SecurityAudit
import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper; import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper;
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO; import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -28,6 +29,7 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/ */
private final SecurityAuditLogMapper auditLogMapper; private final SecurityAuditLogMapper auditLogMapper;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -38,7 +40,7 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
try { try {
SecurityAuditLogDO log = new SecurityAuditLogDO(); SecurityAuditLogDO log = new SecurityAuditLogDO();
log.setUserId(userId); log.setUserId(userId);
log.setAccount(limit(account, 80)); log.setAccount(limit(phoneCrypto.maskIfMobile(account), 80));
log.setAction(limit(action, 80)); log.setAction(limit(action, 80));
log.setResult(limit(result, 20)); log.setResult(limit(result, 20));
log.setReason(limit(reason, 500)); log.setReason(limit(reason, 500));
@@ -13,6 +13,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoServi
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -48,6 +49,7 @@ public class ContactInfoServiceImpl implements ContactInfoService {
* Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs. * Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs.
*/ */
private final ObjectStorageUrlSupport objectStorageUrlSupport; private final ObjectStorageUrlSupport objectStorageUrlSupport;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -204,7 +206,7 @@ public class ContactInfoServiceImpl implements ContactInfoService {
vo.setContactUserId(user.getId()); vo.setContactUserId(user.getId());
vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount());
String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone();
vo.setPhone(contactPhone); vo.setPhone(phoneCrypto.mask(contactPhone));
vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); vo.setPhoneAvailable(StringUtils.hasText(contactPhone));
vo.setWechatId(user.getWechatId()); vo.setWechatId(user.getWechatId());
vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); vo.setWechatAvailable(StringUtils.hasText(user.getWechatId()));
@@ -38,6 +38,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService;
import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService;
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
@@ -89,6 +90,7 @@ public class UserController {
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final UserService userService; private final UserService userService;
private final PhoneCrypto phoneCrypto;
/** /**
* Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
@@ -421,7 +423,7 @@ public class UserController {
public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) { public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) {
UserDO userDO = userMapper.selectOne( UserDO userDO = userMapper.selectOne(
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phone) .eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
); );
boolean available = userDO == null; boolean available = userDO == null;
@@ -12,6 +12,7 @@ import lombok.EqualsAndHashCode;
import java.time.LocalDate; import java.time.LocalDate;
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneEncryptionTypeHandler;
/** /**
* 系统用户信息表 DO * 系统用户信息表 DO
* 对应数据库表 t_user * 对应数据库表 t_user
@@ -22,7 +23,7 @@ import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@TableName("t_user") @TableName(value = "t_user", autoResultMap = true)
public class UserDO extends BaseEntity { public class UserDO extends BaseEntity {
/** /**
@@ -50,17 +51,29 @@ public class UserDO extends BaseEntity {
private String account; private String account;
/** /**
* 手机号 * 手机号(AES-GCM 密文,落库列 phone_cipher;实体中保持明文,便于业务使用)
*/ */
@TableField("phone") @TableField(value = "phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class)
private String phone; private String phone;
/** /**
* 联系电话 * 手机号哈希(HMAC-SHA256,十六进制小写),用于等值查询与唯一去重
*/ */
@TableField("contact_phone") @TableField("phone_hash")
private String phoneHash;
/**
* 联系电话(AES-GCM 密文,落库列 contact_phone_cipher;实体中保持明文)
*/
@TableField(value = "contact_phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class)
private String contactPhone; private String contactPhone;
/**
* 联系电话哈希(HMAC-SHA256,十六进制小写),用于等值查询
*/
@TableField("contact_phone_hash")
private String contactPhoneHash;
/** /**
* 生日 * 生日
*/ */
@@ -48,6 +48,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPa
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog;
import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy;
import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext;
@@ -118,10 +119,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5);
/** /**
* Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. * Purpose: DELETED_ACCOUNT_MARKER supports UserServiceImpl.java by holding or executing the deleted account marker business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/ */
private static final String DELETED_PHONE_MARKER = "_deleted_"; private static final String DELETED_ACCOUNT_MARKER = "_deleted_";
/** /**
* Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
@@ -170,6 +171,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/ */
private final UserInviteCodeMapper userInviteCodeMapper; private final UserInviteCodeMapper userInviteCodeMapper;
private final BrandProperties brandProperties; private final BrandProperties brandProperties;
private final PhoneCrypto phoneCrypto;
/** /**
* Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
@@ -659,7 +661,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.eq(UserDO::getId, id) .eq(UserDO::getId, id)
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
.set(UserDO::getAccount, buildDeletedAccount(userDO)) .set(UserDO::getAccount, buildDeletedAccount(userDO))
.set(UserDO::getPhone, buildDeletedPhone(userDO)) .set(UserDO::getPhone, null)
.set(UserDO::getPhoneHash, null)
.set(UserDO::getContactPhoneHash, null)
.set(UserDO::getStatus, 0) .set(UserDO::getStatus, 0)
.set(UserDO::getIsDelete, 1) .set(UserDO::getIsDelete, 1)
.set(UserDO::getUpdateTime, now) .set(UserDO::getUpdateTime, now)
@@ -792,8 +796,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
userVO.setNickname(userDO.getNickname()); userVO.setNickname(userDO.getNickname());
userVO.setAccount(userDO.getAccount()); userVO.setAccount(userDO.getAccount());
userVO.setPhone(userDO.getPhone()); userVO.setPhone(maskPhone(userDO.getPhone()));
userVO.setContactPhone(userDO.getContactPhone()); userVO.setContactPhone(maskPhone(userDO.getContactPhone()));
userVO.setBirthday(userDO.getBirthday()); userVO.setBirthday(userDO.getBirthday());
userVO.setWechatId(userDO.getWechatId()); userVO.setWechatId(userDO.getWechatId());
userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode()));
@@ -919,7 +923,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
UserDO userDO = userMapper.selectOne( UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class) Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, normalizedPhone) .eq(UserDO::getPhoneHash, phoneCrypto.index(normalizedPhone))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
.last("limit 1") .last("limit 1")
); );
@@ -1085,7 +1089,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
UserDO userDO = userMapper.selectOne( UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class) Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) .eq(UserDO::getPhoneHash, phoneCrypto.index(phoneLoginRequestDTO.getPhone()))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
); );
@@ -1126,7 +1130,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) {
UserDO userDO = userMapper.selectOne( UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class) Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phone) .eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
.last("limit 1") .last("limit 1")
); );
@@ -1471,7 +1475,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
UserDO existingPhoneUser = userMapper.selectOne( UserDO existingPhoneUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class) Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, registerRequestDTO.getPhone()) .eq(UserDO::getPhoneHash, phoneCrypto.index(registerRequestDTO.getPhone()))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
); );
@@ -1896,10 +1900,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
wrapper.eq(UserDO::getIsDelete, 0); wrapper.eq(UserDO::getIsDelete, 0);
// 不再过滤普通用户,由前端根据用户角色进行过滤 // 不再过滤普通用户,由前端根据用户角色进行过滤
if (StringUtils.hasText(keyword)) { if (StringUtils.hasText(keyword)) {
wrapper.and(w -> w.like(UserDO::getAccount, keyword) String keywordPhoneHash = phoneCrypto.isMobilePhone(keyword) ? phoneCrypto.index(keyword) : null;
.or().like(UserDO::getNickname, keyword) wrapper.and(w -> {
.or().like(UserDO::getPhone, keyword) w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword);
.or().like(UserDO::getContactPhone, keyword)); // 手机号只做精确匹配:密文不可模糊检索,统一走 phone_hash
if (keywordPhoneHash != null) {
w.or().eq(UserDO::getPhoneHash, keywordPhoneHash)
.or().eq(UserDO::getContactPhoneHash, keywordPhoneHash);
}
});
} }
if (shopId != null && shopId > 0) { if (shopId != null && shopId > 0) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
@@ -2231,7 +2240,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/ */
throw new RuntimeException("当前账号未绑定手机号"); throw new RuntimeException("当前账号未绑定手机号");
} }
if (!userDO.getPhone().equals(oldPhone)) { if (!Objects.equals(phoneCrypto.index(userDO.getPhone()), phoneCrypto.index(oldPhone))) {
/** /**
* Run business method `RuntimeException`. * Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -2284,9 +2293,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/ */
validateVerificationCode(phone, verificationCode); validateVerificationCode(phone, verificationCode);
// 根据手机号查找用户 // 根据手机号哈希查找用户
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class); LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class);
wrapper.eq(UserDO::getPhone, phone); wrapper.eq(UserDO::getPhoneHash, phoneCrypto.index(phone));
wrapper.eq(UserDO::getIsDelete, 0); wrapper.eq(UserDO::getIsDelete, 0);
UserDO userDO = userMapper.selectOne(wrapper); UserDO userDO = userMapper.selectOne(wrapper);
@@ -2334,26 +2343,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @param 50 parameter `50` supplied by the caller * @param 50 parameter `50` supplied by the caller
* @return return result consumed by the caller or returned to the frontend * @return return result consumed by the caller or returned to the frontend
*/ */
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); return trimDeletedPlaceholder(base + DELETED_ACCOUNT_MARKER + suffix, 50);
}
/**
* Run business method `buildDeletedPhone`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userDO parameter `userDO` supplied by the caller
* @return private String result consumed by the caller or returned to the frontend
*/
private String buildDeletedPhone(UserDO userDO) {
String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString();
String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone";
/**
* Run business method `trimDeletedPlaceholder`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param suffix parameter `suffix` supplied by the caller
* @param 50 parameter `50` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
} }
/** /**
@@ -2969,9 +2959,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
} }
return null; return null;
} }
if (isDeletedPlaceholderPhone(normalizedPhone)) {
return normalizedPhone;
}
if (!normalizedPhone.matches(PHONE_REGEX)) { if (!normalizedPhone.matches(PHONE_REGEX)) {
/** /**
* Run business method `RuntimeException`. * Run business method `RuntimeException`.
@@ -2991,16 +2978,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return normalizedPhone; return normalizedPhone;
} }
/**
* Run business method `isDeletedPlaceholderPhone`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @return private boolean result consumed by the caller or returned to the frontend
*/
private boolean isDeletedPlaceholderPhone(String phone) {
return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER);
}
/** /**
* Run business method `ensurePhoneNotUsed`. * Run business method `ensurePhoneNotUsed`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -3010,7 +2987,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/ */
private void ensurePhoneNotUsed(String phone, Long currentUserId) { private void ensurePhoneNotUsed(String phone, Long currentUserId) {
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class) LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phone) .eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
.eq(UserDO::getIsDelete, 0); .eq(UserDO::getIsDelete, 0);
if (currentUserId != null) { if (currentUserId != null) {
wrapper.ne(UserDO::getId, currentUserId); wrapper.ne(UserDO::getId, currentUserId);
@@ -0,0 +1,134 @@
package com.xiaowang.jayucloud.artlist.core.support.privacy;
import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.HexFormat;
/**
* 手机号加密与索引组件,算法与 JC-Salon-Core 的 PhoneCrypto 逐字对齐:
* <ul>
* <li>加密:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag,前缀 {@code enc:v1:},载荷为 Base64(IV||密文);</li>
* <li>索引:HMAC-SHA256,输入为 {@code value.trim()},输出十六进制小写;</li>
* <li>手机号识别:{@code 1[3-9]\d{9}}。</li>
* </ul>
* 两条线使用同一把 index-key,phone_hash 才可跨线比对;密文因随机 IV 各自独立,不要求可比。
*/
@Component
public class PhoneCrypto {
private static final String CIPHER_PREFIX = "enc:v1:";
private static final SecureRandom RANDOM = new SecureRandom();
private static volatile PhoneCrypto current;
private final PhoneCryptoProperties properties;
private byte[] encryptionKey;
private byte[] indexKey;
public PhoneCrypto(PhoneCryptoProperties properties) {
this.properties = properties;
}
@PostConstruct
public void initialize() {
encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key");
indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key");
if (encryptionKey.length != 32 || indexKey.length < 32) {
throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥");
}
if (Arrays.equals(encryptionKey, indexKey)) {
throw new IllegalStateException("手机号加密密钥与索引密钥必须独立");
}
current = this;
}
public String encrypt(String value) {
if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value;
try {
byte[] iv = new byte[12];
RANDOM.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv));
byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
byte[] payload = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, payload, 0, iv.length);
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload);
} catch (GeneralSecurityException exception) {
throw new IllegalStateException("手机号加密失败", exception);
}
}
public String decrypt(String value) {
if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value;
try {
byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length()));
if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效");
byte[] iv = Arrays.copyOfRange(payload, 0, 12);
byte[] encrypted = Arrays.copyOfRange(payload, 12, payload.length);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv));
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
} catch (GeneralSecurityException | IllegalArgumentException exception) {
throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception);
}
}
public boolean isEncrypted(String value) {
return value != null && value.startsWith(CIPHER_PREFIX);
}
public boolean isMobilePhone(String value) {
return value != null && value.trim().matches("1[3-9]\\d{9}");
}
public String mask(String value) {
if (!StringUtils.hasText(value)) return value;
String plain = isEncrypted(value) ? decrypt(value) : value;
return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain;
}
/**
* 非手机号内容原样返回,手机号返回脱敏值;用于审计日志等既有账号字段。
*/
public String maskIfMobile(String value) {
return isMobilePhone(value) ? mask(value) : value;
}
public String index(String value) {
if (!StringUtils.hasText(value)) return null;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(indexKey, "HmacSHA256"));
byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (GeneralSecurityException exception) {
throw new IllegalStateException("手机号索引生成失败", exception);
}
}
public static PhoneCrypto current() {
PhoneCrypto instance = current;
if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化");
return instance;
}
private byte[] decodeKey(String value, String name) {
if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-artlist.privacy." + name);
try {
return Base64.getDecoder().decode(value.trim());
} catch (IllegalArgumentException exception) {
throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception);
}
}
}
@@ -0,0 +1,35 @@
package com.xiaowang.jayucloud.artlist.core.support.privacy;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 手机号密文列的类型处理器,与 JC-Salon-Core 的 PhoneEncryptionTypeHandler 一致。
* 仅作用于实体读写;QueryWrapper 条件不会经过类型处理器,按手机号查询必须使用 phone_hash。
*/
public class PhoneEncryptionTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(index, PhoneCrypto.current().encrypt(parameter));
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return PhoneCrypto.current().decrypt(rs.getString(columnName));
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return PhoneCrypto.current().decrypt(rs.getString(columnIndex));
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return PhoneCrypto.current().decrypt(cs.getString(columnIndex));
}
}
@@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.artlist.core.support.security;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.DefaultRedisScript;
@@ -55,6 +56,10 @@ public class OperationGuardService {
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/ */
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
/**
* Purpose: phoneCrypto supports OperationGuardService.java by hashing phone numbers before they become Redis key segments.
*/
private final PhoneCrypto phoneCrypto;
/** /**
* Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role.
@@ -186,7 +191,8 @@ public class OperationGuardService {
readBodyField(request, key) readBodyField(request, key)
); );
if (StringUtils.hasText(value)) { if (StringUtils.hasText(value)) {
return sanitize(value); // 手机号不落 Redis 键:统一替换为哈希
return "phone".equals(key) ? phoneCrypto.index(value) : sanitize(value);
} }
} }
return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI());
@@ -0,0 +1,123 @@
-- =============================================================================
-- V2 手机号加密与手机号哈希(ArtList)
-- 日期:2026-11-04
-- 口径:不做数据迁移,空库初始化。本迁移只调整结构,不回填历史数据。
-- 说明:
-- - t_user.phone / t_user.contact_phone 改为密文列 phone_cipher / contact_phone_cipher;
-- - 新增 phone_hash / contact_phone_hash,用于等值查询与去重;
-- - 哈希算法与 Salon 一致:HMAC-SHA256(规范化手机号),规范化为 trim;
-- - 加密算法与 Salon 一致:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag。
-- 可重复执行:所有 DDL 均先查 information_schema 再执行。
-- =============================================================================
DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists;
DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists;
DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_v2_add_column_if_not_exists(
IN p_table VARCHAR(64),
IN p_column VARCHAR(64),
IN p_definition VARCHAR(500)
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column
) THEN
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_definition);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
CREATE PROCEDURE sp_v2_drop_column_if_exists(
IN p_table VARCHAR(64),
IN p_column VARCHAR(64)
)
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column
) THEN
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
CREATE PROCEDURE sp_v2_drop_index_if_exists(
IN p_table VARCHAR(64),
IN p_index VARCHAR(64)
)
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
) THEN
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
CREATE PROCEDURE sp_v2_add_index_if_not_exists(
IN p_table VARCHAR(64),
IN p_index VARCHAR(64),
IN p_columns VARCHAR(255)
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
) THEN
SET @ddl = CONCAT('CREATE INDEX `', p_index, '` ON `', p_table, '` ', p_columns);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
CREATE PROCEDURE sp_v2_add_unique_index_if_not_exists(
IN p_table VARCHAR(64),
IN p_index VARCHAR(64),
IN p_columns VARCHAR(255)
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
) THEN
SET @ddl = CONCAT('CREATE UNIQUE INDEX `', p_index, '` ON `', p_table, '` ', p_columns);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
DELIMITER ;
CALL sp_v2_add_column_if_not_exists('t_user', 'phone_cipher', 'varchar(255) NULL COMMENT ''手机号密文(AES-GCM)''');
CALL sp_v2_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号哈希(HMAC-SHA256,十六进制小写)''');
CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_cipher', 'varchar(255) NULL COMMENT ''联系电话密文(AES-GCM)''');
CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话哈希(HMAC-SHA256,十六进制小写)''');
CALL sp_v2_drop_index_if_exists('t_user', 'idx_phone');
CALL sp_v2_drop_column_if_exists('t_user', 'phone');
CALL sp_v2_drop_column_if_exists('t_user', 'contact_phone');
-- MySQL 唯一索引允许多行 NULL,因此未绑定手机号的用户不受影响。
CALL sp_v2_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(phone_hash)');
CALL sp_v2_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(contact_phone_hash)');
DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists;
DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists;
DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists;
@@ -0,0 +1,68 @@
package com.xiaowang.jayucloud.artlist.core.support.privacy;
import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PhoneCryptoTest {
private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM=";
private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU=";
private PhoneCrypto phoneCrypto;
@BeforeEach
void setUp() {
PhoneCryptoProperties properties = new PhoneCryptoProperties();
properties.setEncryptionKey(ENCRYPTION_KEY);
properties.setIndexKey(INDEX_KEY);
phoneCrypto = new PhoneCrypto(properties);
phoneCrypto.initialize();
}
@Test
void encryptAndDecryptRoundTrip() {
String phone = "13800000000";
String cipher = phoneCrypto.encrypt(phone);
assertTrue(cipher.startsWith("enc:v1:"));
assertEquals(phone, phoneCrypto.decrypt(cipher));
assertNotEquals(cipher, phoneCrypto.encrypt(phone), "随机IV使同一明文的密文不同");
}
@Test
void hashIsStableForSamePhone() {
String phone = "13800000000";
String first = phoneCrypto.index(phone);
String second = phoneCrypto.index(phone);
assertEquals(first, second);
assertEquals(64, first.length());
assertEquals(first, first.toLowerCase());
}
@Test
void normalizationOnlyTrimsToMatchSalon() {
assertEquals(phoneCrypto.index("13800000000"), phoneCrypto.index(" 13800000000 "));
assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("+8613800000000"));
assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("138-0000-0000"));
assertFalse(phoneCrypto.isMobilePhone("+8613800000000"));
assertFalse(phoneCrypto.isMobilePhone("138-0000-0000"));
assertTrue(phoneCrypto.isMobilePhone("13800000000"));
}
@Test
void hashOfUnknownPhoneDoesNotMatchRegisteredPhone() {
assertNotEquals(phoneCrypto.index("13900000000"), phoneCrypto.index("13800000000"));
}
@Test
void maskKeepsPrefixAndSuffix() {
assertEquals("138****0000", phoneCrypto.mask("13800000000"));
assertEquals("138****0000", phoneCrypto.mask(phoneCrypto.encrypt("13800000000")));
assertEquals("zhangsan", phoneCrypto.mask("zhangsan"));
}
}
@@ -27,3 +27,10 @@ aliyun:
oss: oss:
access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-id: LTAI5t9divmxMWHiKhLSRdDd
access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q
# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。
jayucloud-artlist:
privacy:
phone-crypto:
encryption-key: "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="
index-key: "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="
@@ -27,3 +27,11 @@ aliyun:
oss: oss:
access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-id: LTAI5t9divmxMWHiKhLSRdDd
access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q
# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。
# 生产密钥沿用 jayucloud-salon 生产配置;如需独立轮换,必须两条线同步替换 index-key,否则 hash 不可比对。
jayucloud-artlist:
privacy:
phone-crypto:
encryption-key: "zelWItNk7yyDA/LGkq4+Mqo0IOyBzAUmgyR4qLL1htw="
index-key: "01lUBIigsJL/GW/SeYLigYC4ngiY9ntknX+ScDeuNzQ="
@@ -27,3 +27,10 @@ aliyun:
oss: oss:
access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-id: LTAI5t9divmxMWHiKhLSRdDd
access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q
# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。
jayucloud-artlist:
privacy:
phone-crypto:
encryption-key: "/+Hq9v64U+5SHdBIw1w/6smGsbHh5224NSOvrn1o/fw="
index-key: "bEQkH9PtYIMbe1SnO5z0lntr7esGl1ZrxI4Yg+XkFY8="
@@ -2,7 +2,7 @@
- 日期:2026-11-04 - 日期:2026-11-04
- 范围:`JC-ArtList-Core` 的 Flyway 数据库迁移接入、Redis 会话库隔离 - 范围:`JC-ArtList-Core` 的 Flyway 数据库迁移接入、Redis 会话库隔离
- 涉及配置:`nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/core.yaml`、同目录 `infra.yaml` - 涉及配置:`nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/core.yaml`、同目录 `infra.yaml`、`secret.yaml`
## 一、本次改了什么 ## 一、本次改了什么
@@ -17,6 +17,8 @@
> **口径:不做数据迁移,空库从 V1 全量初始化。** 三个环境均按此口径执行,不存在“把存量库 baseline 到 V1”的场景。 > **口径:不做数据迁移,空库从 V1 全量初始化。** 三个环境均按此口径执行,不存在“把存量库 baseline 到 V1”的场景。
- 新增 `V2__手机号加密与手机号哈希_20261104.sql`:`t_user` 增加 `phone_cipher`/`phone_hash`/`contact_phone_cipher`/`contact_phone_hash`,删除明文列 `phone`/`contact_phone` 及索引 `idx_phone`,新增 `uk_user_phone_hash` 唯一索引与 `idx_user_contact_phone_hash` 普通索引;脚本幂等可重复执行。
2. **Redis 会话库迁移** 2. **Redis 会话库迁移**
- ArtList 的 `spring.redis.database` 从 `0` 改为 `1`,与 Salon 的 `0` 分开,避免两者会话 key 空间互相干扰。 - ArtList 的 `spring.redis.database` 从 `0` 改为 `1`,与 Salon 的 `0` 分开,避免两者会话 key 空间互相干扰。
- 会话 key 前缀统一为 `artlist:auth:session:` 与 `artlist:auth:user:sessions:`,覆盖登录校验、刷新令牌、踢下线等全部读写路径。 - 会话 key 前缀统一为 `artlist:auth:session:` 与 `artlist:auth:user:sessions:`,覆盖登录校验、刷新令牌、踢下线等全部读写路径。
@@ -92,3 +94,17 @@
3. 启动 `JC-ArtList-Core`,检查日志中 Flyway 迁移记录与 `flyway_schema_history` 内容。 3. 启动 `JC-ArtList-Core`,检查日志中 Flyway 迁移记录与 `flyway_schema_history` 内容。
4. 重新登录一次,确认会话写入 Redis `db 1`(`INFO keyspace` 或 `KEYS artlist:auth:session:*` 使用 `-n 1`)。 4. 重新登录一次,确认会话写入 Redis `db 1`(`INFO keyspace` 或 `KEYS artlist:auth:session:*` 使用 `-n 1`)。
5. 验证旧登录态确实失效(使用旧 token 请求应返回未登录)。 5. 验证旧登录态确实失效(使用旧 token 请求应返回未登录)。
## 七、手机号加密配置(`secret.yaml`)
1. **新增配置项**:三个环境 `nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/secret.yaml` 增加
`jayucloud-artlist.privacy.phone-crypto.encryption-key` 与 `index-key`。
2. **用途**:
- `encryption-key`:AES-GCM 加密手机号,落库到 `t_user.phone_cipher` / `contact_phone_cipher`;
- `index-key`:HMAC-SHA256 生成 `phone_hash` / `contact_phone_hash`,用于等值查询与唯一去重。
3. **与 Salon 的关系**:算法与 Salon 的 `PhoneCrypto` 逐字一致(AES/GCM/NoPadding、12 字节随机 IV、128 位 tag、`enc:v1:` 前缀;HMAC-SHA256,规范化为 `trim`)。三个环境分别与同环境 Salon 的密钥保持一致,因此同环境两条线的 `phone_hash` 可直接比对;密文因随机 IV 各自独立,不要求可比。
4. **三环境差异**:dev/sit/prod 均为独立密钥,不做跨环境共享;prod 生产密钥沿用 Salon 生产配置,**轮换时必须两条线同步替换 `index-key`**,否则跨线查询失效。
5. **缺失时行为**:任一密钥缺失、非 Base64、长度不足 32 字节、或两项相同,`PhoneCrypto` 初始化即抛异常,应用启动失败(不会以明文降级)。
6. **轮换与回退风险**:更换 `encryption-key` 会导致既有密文无法解密(需新增补偿迁移重新加密);更换 `index-key` 会导致既有哈希全部失效(需重建哈希);两种轮换都属于破坏性操作,必须先备份并评估。
7. **安全要求**:仓库只放与环境一致的密钥引用,禁止在代码、日志、异常、审计中输出明文手机号;如需彻底外置,改为部署时注入,并同步 dev/sit/prod 的 Nacos。