This commit is contained in:
ran.shang
2026-03-27 18:28:05 +08:00
parent cb29084f97
commit 52356bdc2e
46 changed files with 30 additions and 2076 deletions

View File

@@ -41,10 +41,10 @@ public class TrimAndUpperDeserializer extends StdDeserializer<String> implements
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String s = jsonParser.getText();
if (!(StringUtils.isEmpty(s) || Objects.isNull(executeType))) {
if (ExecuteType.ALL.equals(executeType) || ExecuteType.TRIM.equals(executeType)) {
if (ExecuteType.ALL == executeType || ExecuteType.TRIM == executeType) {
s = StringUtils.replace(StringUtils.trim(s)," ","");
}
if (ExecuteType.ALL.equals(executeType) || ExecuteType.TRIM.equals(executeType)) {
if (ExecuteType.ALL == executeType || ExecuteType.TRIM == executeType) {
s = StringUtils.upperCase(s);
}
}

View File

@@ -55,15 +55,15 @@ public class TrimAndUpperFormatterFactory implements
return value;
}
// 去所有空格
if (ExecuteType.ALL.equals(executeType) || ExecuteType.REPLACE_ALL.equals(executeType)) {
if (ExecuteType.ALL == executeType || ExecuteType.REPLACE_ALL == executeType) {
value = StringUtils.replace(value, " ", "");
}
// 转大写
if (ExecuteType.ALL.equals(executeType) || ExecuteType.UPPER_CASE.equals(executeType)) {
if (ExecuteType.ALL == executeType || ExecuteType.UPPER_CASE == executeType) {
value = StringUtils.upperCase(value);
}
//去两边空格
if (ExecuteType.ALL.equals(executeType) || ExecuteType.TRIM.equals(executeType)) {
if (ExecuteType.ALL == executeType || ExecuteType.TRIM == executeType) {
value = StringUtils.trim(value);
}
return value;

View File

@@ -73,6 +73,7 @@ public class CookieUtils {
cookie.setPath(path);
cookie.setHttpOnly(false);
cookie.setMaxAge(maxAge);
cookie.setSecure(true);
return cookie;
} catch (Exception e) {
log.error("------创建Cookie时,系统异常:{0}", e);
@@ -97,6 +98,7 @@ public class CookieUtils {
Cookie tempCookie = new Cookie(name, "");
tempCookie.setMaxAge(0);
tempCookie.setPath("/");
tempCookie.setSecure(true);
if (!StringUtils.isEmpty(domain)) {
tempCookie.setDomain(domain);
}

View File

@@ -46,9 +46,9 @@ public class ParameterizedTypeImpl implements ParameterizedType {
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments))
return false;
if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null)
if (ownerType != null ? ownerType != that.ownerType : that.ownerType != null)
return false;
return rawType != null ? rawType.equals(that.rawType) : that.rawType == null;
return rawType != null ? rawType != that.rawType : that.rawType == null;
}

View File

@@ -2,6 +2,7 @@ package com.senmesh.common.validation.util;
import com.senmesh.common.constant.CommonConstants;
import com.senmesh.common.exception.util.Assert;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintViolation;
@@ -130,7 +131,7 @@ public class ValidateUtils {
}
char idCardLast = charArray[17];
int idCardMod = sum % 11;
if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
if (idCardY[idCardMod].toUpperCase(Locale.ROOT).equals(String.valueOf(idCardLast).toUpperCase(Locale.ROOT))) {
return true;
} else {
return false;

View File

@@ -92,9 +92,10 @@ public class FileServiceImpl implements FileService {
HttpSession session = request.getSession();
String filename = fileRecord.getFileName();
if (Objects.nonNull(request) && StringUtils.isNotBlank(request.getParameter("filename"))) {
if (StringUtils.isNotBlank(request.getParameter("filename"))) {
filename = URLDecoder.decode(request.getParameter("filename"),"utf-8");
}
filename = filename.replaceAll("[\\r\\n\"']", "");
String mimeType = session.getServletContext().getMimeType(filename);
response.setContentType(mimeType);

View File

@@ -50,8 +50,8 @@ public class LocalFileStorage implements IFileStorage {
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
log.info("下载异常", e);
throw new BusinessException("下载异常" + e.getMessage());
log.error("文件下载失败,文件不存在:{}", filePath, e);
throw new BusinessException("下载异常");
}
}

View File

@@ -1,87 +0,0 @@
package com.senmesh.sdk.ssb;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.security.NoSuchAlgorithmException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.senmesh.common.exception.BusinessException;
import com.senmesh.sdk.ssb.util.AESEncryption;
import com.senmesh.sdk.ssb.util.SsbRsaUtils;
/**
* 随申办配置
*
*/
@ConfigurationProperties(prefix = SsbProperties.PREFIX)
@Data
@Component
@NoArgsConstructor
public class SsbProperties {
/**
* 随申办配置前缀
**/
public static final String PREFIX = "ssb";
/** 开发商标识(在区运营服务平台注册开发商后获得) **/
private String clientId;
private String clientSecret;
/** 接口标识(申请调用 API 后获得) **/
private String apiId;
/** AES 密钥(使用 RSA 公钥加密) **/
private String aesKey;
/** AES 偏移量(使用 RSA 公钥加密) **/
private String aesIv;
/** 公钥 **/
private String pubKey;
/** 网关地址 **/
private String gatewayUrl;
/** sm2公钥 **/
private String sm2PublicKey;
/** sm2私钥 **/
private String sm2PrivateKey;
private String appKey;
private String appSecret;
public static AESEncryption aESEncryption = null;
public static String enAesKey = null;
public static String enAesIv = null;
public AESEncryption getAESEncryption() {
if (aESEncryption == null) {
try {
aESEncryption = new AESEncryption(this.getAesKey(), this.getAesIv());
} catch (NoSuchAlgorithmException e) {
throw new BusinessException("随申办aes配置错误:" + e.getMessage());
}
}
return aESEncryption;
}
public String getEnAesKey() {
if (enAesKey == null) {
try {
enAesKey = SsbRsaUtils.encryptByPublicKey(this.getPubKey(), this.getAesKey());
} catch (Exception e) {
throw new BusinessException("随申办aesKey配置错误:" + e.getMessage());
}
}
return enAesKey;
}
public String getEnAesIv() {
if (enAesIv == null) {
try {
enAesIv = SsbRsaUtils.encryptByPublicKey(this.getPubKey(), this.getAesIv());
} catch (Exception e) {
throw new BusinessException("随申办aesIv配置错误:" + e.getMessage());
}
}
return enAesIv;
}
}

View File

@@ -1,11 +0,0 @@
package com.senmesh.sdk.ssb.constant;
public interface SsbConstants {
/** 成功编码 **/
Integer SUC_CODE = 200;
/** 用户类型:身份证 **/
Integer CERT_TYPE_ID_CARD = 1;
}

View File

@@ -1,24 +0,0 @@
package com.senmesh.sdk.ssb.constant;
public enum SsbPlatformEnum{
/** 随申办APP **/
ESHIMIN("eshimin") ,
/** 微信小程序 **/
WEIXINMINI("weixinmini"),
/** 微信公众号 **/
WEIXINMP("weixinmp"),
/** 支付宝小程序 **/
ALIPAYMINI("alipaymini"),
/** 支付宝生活号 **/
ALIPAYFUWU("alipayfuwu"),
;
SsbPlatformEnum(String type){
this.type = type;
}
private String type;
public String getType() {
return type;
}
}

View File

@@ -1,32 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbAppAccessTokenDTO implements Serializable{
/** **/
private static final long serialVersionUID = 2742615764546777525L;
/** 接口获取授权后的 access_token。(2 小时有效) **/
private String access_token;
/** 用来刷新 access_token 的有效期(24 小时有效, 用户必须重新进入授权入口之后才可以延长refresh_token 有效期) **/
private String refresh_token;
/** access_token 的生命周期,单位是毫秒数(2 小时有效,客户端自行计时) 。 **/
private String scope;
/** token 的类型 **/
private String token_type;
/** 当前获取的可操作类型,目前只提供 read **/
private String expires_in;
/** 用户标识位 **/
private String username;
}

View File

@@ -1,38 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import com.senmesh.sdk.common.dto.ISdkRequest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbAppAccessTokenReq implements ISdkRequest<SsbAppAccessTokenDTO>{
/** **/
private static final long serialVersionUID = 2742615764546777525L;
/** 申请应用时分配的 AppKey。 **/
private String client_id;
/** 调用 authorize 获得的 code 值 **/
private String code;
/** 13 位系统时间戳(链接存在时效性,时间戳必须和北京时间一致 保证每次时间戳都是最新的,时间上下容错五分钟否则链接失效) **/
private String timestamp;
/** 签名(client_id + client_secret + code+timestamp ) **/
private String sign;
@Override
public Class<SsbAppAccessTokenDTO> getResponseClass() {
return SsbAppAccessTokenDTO.class;
}
@Override
public String getUri() {
return "https://api.eshimin.com/newOauth/accessToken";
}
}

View File

@@ -1,14 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Data
public abstract class SsbAppReq {
/** 请求地址 **/
@JsonIgnore
private String url;
}

View File

@@ -1,22 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SsbAppRes implements Serializable{
/** **/
private static final long serialVersionUID = -8065958516522176350L;
public static final String SUC_CODE= "0000";
private String data;
private String code;
}

View File

@@ -1,39 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbAppUserInfoDTO implements Serializable{
/** 已实名 **/
public static final Integer AUTHENTICATIED = 1;
/** **/
private static final long serialVersionUID = 2742615764546777525L;
/** 是否实名 0.非实名 1.实名 **/
private Integer status;
/** 头像地址 **/
private String head_pic;
/** 社保卡号 **/
private String sscard;
/** 用户姓名 **/
private String name;
/** 用户 ID **/
private String userId;
/** 身份证号码 **/
private String idcard;
/** 用户名 **/
private String username;
/** 手机号码 **/
private String mobile;
}

View File

@@ -1,40 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import com.senmesh.sdk.common.dto.ISdkRequest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbAppUserInfoReq implements ISdkRequest<SsbAppUserInfoDTO>{
/** **/
private static final long serialVersionUID = 2742615764546777525L;
/** 申请应用时分配的 AppKey。 **/
private String client_id;
/** 授权令牌(2 小时有效) **/
private String access_token;
/** 用户标识位 **/
private String username;
/** 13 位系统时间戳(链接存在时效性,时间戳必须和北京时间一致 保证每次时间戳都是最新的,时间上下容错五分钟否则链接失效) **/
private String timestamp;
/** 签名(client_id + client_secret + code+timestamp ) **/
private String sign;
@Override
public Class<SsbAppUserInfoDTO> getResponseClass() {
return SsbAppUserInfoDTO.class;
}
@Override
public String getUri() {
return "https://api.eshimin.com/newOauth/userInfo";
}
}

View File

@@ -1,25 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SsbRes implements Serializable {
/** **/
private static final long serialVersionUID = 8271846024223081240L;
/** 返回编码,200 表示成功,其他表示接口调用错误 **/
private Integer status;
/** 错误信息 **/
private String message;
/** AES 加密后的业务数据,使用对应密钥解密后,获得业务返回参数内容 **/
private String data;
}

View File

@@ -1,56 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SsbUserDTO implements Serializable {
/** **/
private static final long serialVersionUID = 315891518492560183L;
/** 是 用户类型(个人) **/
private String zwdtsw_user_type;
/** 是 用户主键 UUID **/
private String zwdtsw_user_id;
/** 邮箱 **/
private String zwdtsw_email;
/** 用户姓名 初级及实名以上用户有值 **/
private String zwdtsw_name;
/** 是 用户名 **/
private String zwdtsw_account;
/** 身份证号 初级及实名以上用户有值 **/
private String zwdtsw_cert_id;
/** 证件类型 身份证、中国护照、普护照、台湾居民通行证、港澳通行证等 **/
private String zwdtsw_cert_type;
/** 手机号码 **/
private String zwdtsw_link_phone;
/** 家庭住址 **/
private String zwdtsw_link_address;
/** 邮政编码 **/
private String zwdtsw_zip_code;
/** 是否激活(激活/未激活) 默认都是激活 **/
private String zwdtsw_user_status;
/** 是 初级身份证实名验证状态(实名通过/实名未通过)初级实名过的用户 **/
private String zwdtsw_after_certification;
/** 注册时间 **/
private String zwdtsw_reg_time;
/** 更新时间 **/
private String zwdtsw_last_update;
/** 是个人用户等级(法人无该字段)未实名、初级、中级、高级 **/
private String zwdtsw_user_CAcert;
/** 是 个人用户等级字典用户等级0,1,2,3 分别表示未实名,初级,中级,高级 **/
private Integer usergrade;
/** 是 用户类型字典 默认身份证 1("1", "居民身份证""414", "普通护照"(对应pc 总门户的中国护照)"3", "外国护照""513", "往来港澳通行证""517", "往来台湾通行证""516","港澳居民来往内地通行证""511", "台湾居民来往内地通行证"**/
private Integer certType;
/** 姓名加身份证号散列值 (唯一) **/
private String certKey;
/** 国籍默认为中国 **/
private String citizenship;
}

View File

@@ -1,21 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SsbUserDataDTO implements Serializable{
/** **/
private static final long serialVersionUID = -576144664556081564L;
private String code;
private String msg;
private SsbUserDTO data;
}

View File

@@ -1,26 +0,0 @@
package com.senmesh.sdk.ssb.dto;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbUserReq implements Serializable{
/** **/
private static final long serialVersionUID = -1531708833509490088L;
/** 用户令牌,2.2 跳转第三方应用时传递 **/
@JsonProperty("access_token")
private String accessToken;
}

View File

@@ -1,160 +0,0 @@
package com.senmesh.sdk.ssb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.senmesh.common.AlitaResult;
import com.senmesh.common.exception.BusinessException;
import com.senmesh.common.exception.util.Assert;
import com.senmesh.common.util.JsonUtils;
import com.senmesh.sdk.common.constant.SdkConstants;
import com.senmesh.sdk.common.dto.DefaultSdkInvokeLogDTO;
import com.senmesh.sdk.common.dto.ISdkRequest;
import com.senmesh.sdk.ssb.SsbProperties;
import com.senmesh.sdk.ssb.constant.SsbConstants;
import com.senmesh.sdk.ssb.dto.SsbAppAccessTokenDTO;
import com.senmesh.sdk.ssb.dto.SsbAppAccessTokenReq;
import com.senmesh.sdk.ssb.dto.SsbAppRes;
import com.senmesh.sdk.ssb.dto.SsbAppUserInfoDTO;
import com.senmesh.sdk.ssb.dto.SsbAppUserInfoReq;
import com.senmesh.sdk.ssb.dto.SsbRes;
import com.senmesh.sdk.ssb.dto.SsbUserDataDTO;
import com.senmesh.sdk.ssb.dto.SsbUserReq;
import com.senmesh.sdk.ssb.util.SM2Utils;
import com.senmesh.sdk.ssb.util.SsbRsaUtils;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class SsbInvoker {
private RestTemplate restTemplate = new RestTemplate();
@Autowired
private SsbProperties ssbProperties;
public AlitaResult<SsbUserDataDTO> getUser(SsbUserReq reqDTO) {
String timestamp = String.valueOf(System.currentTimeMillis());
String clientId = ssbProperties.getClientId();
String clientSecret = ssbProperties.getClientSecret();
String sign = SsbRsaUtils.encryptMd5(clientId + timestamp + clientSecret);
HttpHeaders headers = new HttpHeaders();
headers.set("client-id", clientId);
headers.set("api-id", ssbProperties.getApiId());
headers.set("sign", sign);
headers.set("timestamp", timestamp);
try {
headers.set("aes-key", ssbProperties.getEnAesKey());
headers.set("aes-iv", ssbProperties.getEnAesIv());
} catch (Exception e) {
return AlitaResult.error(SdkConstants.SDK_INVOKE_NOT_REACH_CODE,
"随申办加密aes失败:" + e.getMessage());
}
// headers.setContentType(MediaType.APPLICATION_JSON);
String encryptBodyStr;
SsbRes ssbRes = null;
try {
try {
encryptBodyStr =
ssbProperties.getAESEncryption().encrypt(JsonUtils.toDefaultJsonString(reqDTO));
} catch (Exception e) {
log.info("随申办参数加密失败:", e);
return AlitaResult.error(SdkConstants.SDK_INVOKE_NOT_REACH_CODE,
"随申办参数加密失败:" + e.getMessage());
}
HttpEntity<String> request = new HttpEntity<>(encryptBodyStr, headers);
try {
log.debug("ssb request httpentity:{}", request);
ssbRes =
restTemplate.postForObject(ssbProperties.getGatewayUrl(), request, SsbRes.class);
} catch (Exception e) {
log.info("ssb rest error:", e);
return AlitaResult.error(SdkConstants.SDK_HTTP_INVOKE_ERROR_CODE, e.getMessage());
}
if (SsbConstants.SUC_CODE.equals(ssbRes.getStatus())) {
try {
String responseDtoStr = ssbProperties.getAESEncryption().decrypt(ssbRes.getData());
return AlitaResult.success(JsonUtils.toObject(responseDtoStr, SsbUserDataDTO.class));
} catch (Exception e) {
return AlitaResult.error(SdkConstants.SDK_RESPONSE_CONVERT_ERROR_CODE,
"随申办参数解密失败:" + e.getMessage());
}
} else {
return AlitaResult.error(SdkConstants.SDK_HTTP_INVOKE_RESPONSE_FAIL_CODE,
ssbRes.getMessage());
}
} finally {
log.info("ssb user invoke:{}",
JsonUtils
.toJsonString(
DefaultSdkInvokeLogDTO.builder().requestData(reqDTO).responseData(ssbRes)
.build()));
}
}
public SsbAppAccessTokenDTO getAppAccessToken(String authCode) {
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = SM2Utils.sign(ssbProperties.getSm2PrivateKey(),
ssbProperties.getAppKey() + ssbProperties.getAppSecret() + authCode + timestamp,
ssbProperties.getAppKey());
SsbAppAccessTokenReq ssbAppAccessTokenReq =
SsbAppAccessTokenReq.builder().client_id(ssbProperties.getAppKey()).code(authCode)
.timestamp(timestamp).sign(sign).build();
return executeApp(ssbAppAccessTokenReq);
}
public <RES> RES executeApp(ISdkRequest<RES> req) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity = new HttpEntity<>(req, headers);
SsbAppRes ssbAppRes = null;
try {
ssbAppRes =
restTemplate.postForObject(req.getUri(), httpEntity,
SsbAppRes.class);
String code = ssbAppRes.getCode();
Assert.isTrue(SsbAppRes.SUC_CODE.equals(code), code);
String data = ssbAppRes.getData();
return JsonUtils.toObject(SM2Utils.sm2Decrypt(ssbProperties.getSm2PrivateKey(), data),
req.getResponseClass());
} catch (Exception e) {
log.info("ssb app err:", e);
throw new BusinessException("随申办app调用失败:" + e.getMessage());
} finally {
log.info("ssb app invoke:{}",
JsonUtils
.toJsonString(
DefaultSdkInvokeLogDTO.builder().requestData(req)
.responseData(ssbAppRes)
.build()));
}
}
public SsbAppUserInfoDTO getAppUser(SsbAppAccessTokenDTO accessTokenDTO) {
String accessToken = accessTokenDTO.getAccess_token();
String username = accessTokenDTO.getUsername();
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = SM2Utils.sign(ssbProperties.getSm2PrivateKey(),
ssbProperties.getAppKey() + ssbProperties.getAppSecret() + accessToken + username
+ timestamp,
ssbProperties.getAppKey());
SsbAppUserInfoReq req =
SsbAppUserInfoReq.builder().client_id(ssbProperties.getAppKey()).access_token(accessToken)
.username(username).timestamp(timestamp).sign(sign).build();
return executeApp(req);
}
public SsbAppUserInfoDTO getAppUser(String authCode) {
SsbAppAccessTokenDTO accessTokenDTO = this.getAppAccessToken(authCode);
return this.getAppUser(accessTokenDTO);
}
}

View File

@@ -1,54 +0,0 @@
package com.senmesh.sdk.ssb.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AESEncryption {
private static final String AES_ALGORITHM = "AES";
private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private SecretKeySpec secretKeySpec;
private IvParameterSpec ivParameterSpec;
public AESEncryption(String aesKey, String aesIV) throws NoSuchAlgorithmException {
byte[] keyBytes = aesKey.getBytes(StandardCharsets.UTF_8);
byte[] ivBytes = aesIV.getBytes(StandardCharsets.UTF_8);
// 仅取前16个字节
byte[] key = new byte[16];
System.arraycopy(keyBytes, 0, key, 0, 16);
byte[] iv = new byte[16];
System.arraycopy(ivBytes, 0, iv, 0, 16);
secretKeySpec = new SecretKeySpec(key, AES_ALGORITHM);
ivParameterSpec = new IvParameterSpec(iv);
}
public String encrypt(String plainText) throws Exception{
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public String decrypt(String encryptedText)
throws Exception {
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}

View File

@@ -1,88 +0,0 @@
package com.senmesh.sdk.ssb.util;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;
public class Cipher {
private int ct = 1;
private ECPoint p2;
private SM3Digest sm3keybase;
private SM3Digest sm3c3;
private byte[] key = new byte[32];
private byte keyOff = 0;
private void Reset() {
this.sm3keybase = new SM3Digest();
this.sm3c3 = new SM3Digest();
byte[] p = Util.byteConvert32Bytes(this.p2.getX().toBigInteger());
this.sm3keybase.update(p, 0, p.length);
this.sm3c3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(this.p2.getY().toBigInteger());
this.sm3keybase.update(p, 0, p.length);
this.ct = 1;
NextKey();
}
private void NextKey() {
SM3Digest sm3keycur = new SM3Digest(this.sm3keybase);
sm3keycur.update((byte)(this.ct >> 24 & 0xFF));
sm3keycur.update((byte)(this.ct >> 16 & 0xFF));
sm3keycur.update((byte)(this.ct >> 8 & 0xFF));
sm3keycur.update((byte)(this.ct & 0xFF));
sm3keycur.doFinal(this.key, 0);
this.keyOff = 0;
this.ct++;
}
public ECPoint Init_enc(SM2 sm2, ECPoint userKey) {
AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.getPrivate();
ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.getPublic();
BigInteger k = ecpriv.getD();
ECPoint c1 = ecpub.getQ();
this.p2 = userKey.multiply(k);
Reset();
return c1;
}
public void Encrypt(byte[] data) {
this.sm3c3.update(data, 0, data.length);
for (int i = 0; i < data.length; i++) {
if (this.keyOff == this.key.length)
NextKey();
data[i] = (byte)(data[i] ^ this.key[this.keyOff]);
this.keyOff = (byte)(this.keyOff + 1);
}
}
public void Init_dec(BigInteger userD, ECPoint c1) {
this.p2 = c1.multiply(userD);
Reset();
}
public void Decrypt(byte[] data) {
for (int i = 0; i < data.length; i++) {
if (this.keyOff == this.key.length)
NextKey();
data[i] = (byte)(data[i] ^ this.key[this.keyOff]);
this.keyOff = (byte)(this.keyOff + 1);
}
this.sm3c3.update(data, 0, data.length);
}
public void Dofinal(byte[] c3) {
byte[] p = Util.byteConvert32Bytes(this.p2.getY().toBigInteger());
this.sm3c3.update(p, 0, p.length);
this.sm3c3.doFinal(c3, 0);
Reset();
}
}

View File

@@ -1,125 +0,0 @@
package com.senmesh.sdk.ssb.util;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECPoint;
public class SM2 {
public static String[] ecc_param = new String[] { "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0" };
public final BigInteger ecc_p;
public final BigInteger ecc_a;
public final BigInteger ecc_b;
public final BigInteger ecc_n;
public final BigInteger ecc_gx;
public final BigInteger ecc_gy;
public final ECCurve ecc_curve;
public final ECPoint ecc_point_g;
public final ECDomainParameters ecc_bc_spec;
public final ECKeyPairGenerator ecc_key_pair_generator;
public final ECFieldElement ecc_gx_fieldelement;
public final ECFieldElement ecc_gy_fieldelement;
public static SM2 Instance() {
return new SM2();
}
public SM2() {
this.ecc_p = new BigInteger(ecc_param[0], 16);
this.ecc_a = new BigInteger(ecc_param[1], 16);
this.ecc_b = new BigInteger(ecc_param[2], 16);
this.ecc_n = new BigInteger(ecc_param[3], 16);
this.ecc_gx = new BigInteger(ecc_param[4], 16);
this.ecc_gy = new BigInteger(ecc_param[5], 16);
this.ecc_gx_fieldelement = (ECFieldElement)new ECFieldElement.Fp(this.ecc_p, this.ecc_gx);
this.ecc_gy_fieldelement = (ECFieldElement)new ECFieldElement.Fp(this.ecc_p, this.ecc_gy);
this.ecc_curve = (ECCurve)new ECCurve.Fp(this.ecc_p, this.ecc_a, this.ecc_b);
this.ecc_point_g = (ECPoint)new ECPoint.Fp(this.ecc_curve, this.ecc_gx_fieldelement, this.ecc_gy_fieldelement);
this.ecc_bc_spec = new ECDomainParameters(this.ecc_curve, this.ecc_point_g, this.ecc_n);
ECKeyGenerationParameters ecc_ecgenparam = new ECKeyGenerationParameters(this.ecc_bc_spec, new SecureRandom());
this.ecc_key_pair_generator = new ECKeyPairGenerator();
this.ecc_key_pair_generator.init((KeyGenerationParameters)ecc_ecgenparam);
}
public byte[] sm2GetZ(byte[] userId, ECPoint userKey) {
SM3Digest sm3 = new SM3Digest();
int len = userId.length * 8;
sm3.update((byte)(len >> 8 & 0xFF));
sm3.update((byte)(len & 0xFF));
sm3.update(userId, 0, userId.length);
byte[] p = Util.byteConvert32Bytes(this.ecc_a);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(this.ecc_b);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(this.ecc_gx);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(this.ecc_gy);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(userKey.getX().toBigInteger());
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(userKey.getY().toBigInteger());
sm3.update(p, 0, p.length);
byte[] md = new byte[sm3.getDigestSize()];
sm3.doFinal(md, 0);
return md;
}
public void sm2Sign(byte[] md, BigInteger userD, ECPoint userKey, SM2Result sm2Result) {
BigInteger e = new BigInteger(1, md);
BigInteger k = null;
ECPoint kp = null;
BigInteger r = null;
BigInteger s = null;
while (true) {
String kS = "6CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F";
k = new BigInteger(kS, 16);
kp = this.ecc_point_g.multiply(k);
r = e.add(kp.getX().toBigInteger());
r = r.mod(this.ecc_n);
if (!r.equals(BigInteger.ZERO))
if (!r.add(k).equals(this.ecc_n)) {
BigInteger da_1 = userD.add(BigInteger.ONE);
da_1 = da_1.modInverse(this.ecc_n);
s = r.multiply(userD);
s = k.subtract(s).mod(this.ecc_n);
s = da_1.multiply(s).mod(this.ecc_n);
if (!s.equals(BigInteger.ZERO)) {
sm2Result.r = r;
sm2Result.s = s;
return;
}
}
}
}
public void sm2Verify(byte[] md, ECPoint userKey, BigInteger r, BigInteger s, SM2Result sm2Result) {
sm2Result.R = null;
BigInteger e = new BigInteger(1, md);
BigInteger t = r.add(s).mod(this.ecc_n);
if (!t.equals(BigInteger.ZERO)) {
ECPoint x1y1 = this.ecc_point_g.multiply(sm2Result.s);
x1y1 = x1y1.add(userKey.multiply(t));
sm2Result.R = e.add(x1y1.getX().toBigInteger()).mod(this.ecc_n);
}
}
public static void main(String[] args) {}
}

View File

@@ -1,24 +0,0 @@
package com.senmesh.sdk.ssb.util;
import java.math.BigInteger;
import org.bouncycastle.math.ec.ECPoint;
public class SM2Result {
public BigInteger r;
public BigInteger s;
public BigInteger R;
public byte[] sa;
public byte[] sb;
public byte[] s1;
public byte[] s2;
public ECPoint keyra;
public ECPoint keyrb;
}

View File

@@ -1,249 +0,0 @@
package com.senmesh.sdk.ssb.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Enumeration;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Base64;
public class SM2Utils {
public static void main(String[] args) throws Exception {
String clientId = "xxxxxxx";
MyKeyPair myKeyPair = getMyKeyPair();
String smySm2Public = myKeyPair.getPublicKey();
String smySm2Private = myKeyPair.getPrivateKey();
System.out.println("publicKey:" + smySm2Public);
System.out.println("privateKey:" + smySm2Private);
String sourceData = "clientID+pwd+1.0.0+1630307772898";
String encrypt = sm2Encrypt(smySm2Public, sourceData);
System.out.println("utils 加密"+ encrypt);
String decrypt = sm2Decrypt(smySm2Private, encrypt);
System.out.println("utils 解密"+ decrypt);
String sign = sign(smySm2Private, sourceData, clientId);
System.out.println("utils 签名"+ sign);
byte[] signByte = signByte(smySm2Private, sourceData, clientId);
System.out.println("utils 签名byte" + signByte);
boolean verifySign = verifySign(smySm2Public, sourceData, clientId, sign);
System.out.println("utils 签名验证"+ verifySign);
}
public static MyKeyPair getMyKeyPair() {
MyKeyPair myKeyPair = (new SM2Utils()).generateKeyPair();
return myKeyPair;
}
public static String sm2Encrypt(String publicKey, String data) {
try {
return (!StringUtils.isEmpty(publicKey) && !StringUtils.isEmpty(data)) ? new String(Base64.encode(encrypt(Util.hexToByte(publicKey), data.getBytes()))) : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String sm2Decrypt(String privateKey, String data) {
try {
return (!StringUtils.isEmpty(privateKey) && !StringUtils.isEmpty(data)) ? new String(decrypt(Util.hexToByte(privateKey), Base64.decode(data))) : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String sign(String privateKey, String sourceData, String userId) {
try {
byte[] c = sign(userId.getBytes(), Util.hexToByte(privateKey), sourceData.getBytes());
return Util.getHexString(c);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static boolean verifySign(String publicKey, String sourceData, String userId, String sign) {
try {
return verifySign(userId.getBytes(), Util.hexToByte(publicKey), sourceData.getBytes(), Util.hexToByte(sign));
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static byte[] signByte(String privateKey, String sourceData, String clientId) {
try {
return sign(clientId.getBytes(), Util.hexToByte(privateKey), sourceData.getBytes());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private MyKeyPair generateKeyPair() {
SM2 sm2 = SM2.Instance();
AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.getPrivate();
ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.getPublic();
BigInteger privateKey = ecpriv.getD();
ECPoint publicKey = ecpub.getQ();
MyKeyPair myKeyPair = new MyKeyPair();
myKeyPair.setPrivateKey(Util.byteToHex(privateKey.toByteArray()));
myKeyPair.setPublicKey(Util.byteToHex(publicKey.getEncoded(false)));
return myKeyPair;
}
private static byte[] encrypt(byte[] publicKey, byte[] data) throws IOException {
if (publicKey != null && publicKey.length != 0) {
if (data != null && data.length != 0) {
byte[] source = new byte[data.length];
System.arraycopy(data, 0, source, 0, data.length);
Cipher cipher = new Cipher();
SM2 sm2 = SM2.Instance();
ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey);
ECPoint c1 = cipher.Init_enc(sm2, userKey);
cipher.Encrypt(source);
byte[] c3 = new byte[32];
cipher.Dofinal(c3);
DERInteger x = new DERInteger(c1.getX().toBigInteger());
DERInteger y = new DERInteger(c1.getY().toBigInteger());
DEROctetString derDig = new DEROctetString(c3);
DEROctetString derEnc = new DEROctetString(source);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add((ASN1Encodable)x);
v.add((ASN1Encodable)y);
v.add((ASN1Encodable)derDig);
v.add((ASN1Encodable)derEnc);
DERSequence seq = new DERSequence(v);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DEROutputStream dos = new DEROutputStream(bos);
dos.writeObject((ASN1Encodable)seq);
return bos.toByteArray();
}
return null;
}
return null;
}
private static byte[] decrypt(byte[] privateKey, byte[] encryptedData) throws IOException {
if (privateKey != null && privateKey.length != 0) {
if (encryptedData != null && encryptedData.length != 0) {
byte[] enc = new byte[encryptedData.length];
System.arraycopy(encryptedData, 0, enc, 0, encryptedData.length);
SM2 sm2 = SM2.Instance();
BigInteger userD = new BigInteger(1, privateKey);
ByteArrayInputStream bis = new ByteArrayInputStream(enc);
ASN1InputStream dis = new ASN1InputStream(bis);
ASN1Primitive derObj = dis.readObject();
ASN1Sequence asn1 = ASN1Sequence.getInstance(derObj);
ASN1Integer x = (ASN1Integer)asn1.getObjectAt(0);
ASN1Integer y = (ASN1Integer)asn1.getObjectAt(1);
ECPoint c1 = sm2.ecc_curve.createPoint(x.getValue(), y.getValue(), true);
Cipher cipher = new Cipher();
cipher.Init_dec(userD, c1);
DEROctetString data = (DEROctetString)asn1.getObjectAt(3);
enc = data.getOctets();
cipher.Decrypt(enc);
byte[] c3 = new byte[32];
cipher.Dofinal(c3);
return enc;
}
return null;
}
return null;
}
private static byte[] sign(byte[] userId, byte[] privateKey, byte[] sourceData) throws IOException {
if (privateKey != null && privateKey.length != 0) {
if (sourceData != null && sourceData.length != 0) {
SM2 sm2 = SM2.Instance();
BigInteger userD = new BigInteger(privateKey);
ECPoint userKey = sm2.ecc_point_g.multiply(userD);
byte[] z = sm2.sm2GetZ(userId, userKey);
SM3Digest sm3 = new SM3Digest();
sm3.update(z, 0, z.length);
sm3.update(sourceData, 0, sourceData.length);
byte[] md = new byte[32];
sm3.doFinal(md, 0);
SM2Result sm2Result = new SM2Result();
sm2.sm2Sign(md, userD, userKey, sm2Result);
DERInteger d_r = new DERInteger(sm2Result.r);
DERInteger d_s = new DERInteger(sm2Result.s);
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add((ASN1Encodable)d_r);
v2.add((ASN1Encodable)d_s);
DERSequence sign = new DERSequence(v2);
byte[] signdata = sign.getEncoded();
return signdata;
}
return null;
}
return null;
}
private static boolean verifySign(byte[] userId, byte[] publicKey, byte[] sourceData, byte[] signData) throws IOException {
if (publicKey != null && publicKey.length != 0) {
if (sourceData != null && sourceData.length != 0) {
SM2 sm2 = SM2.Instance();
ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey);
SM3Digest sm3 = new SM3Digest();
byte[] z = sm2.sm2GetZ(userId, userKey);
sm3.update(z, 0, z.length);
sm3.update(sourceData, 0, sourceData.length);
byte[] md = new byte[32];
sm3.doFinal(md, 0);
ByteArrayInputStream bis = new ByteArrayInputStream(signData);
ASN1InputStream dis = new ASN1InputStream(bis);
ASN1Primitive derObj = dis.readObject();
ASN1Sequence asn1 = ASN1Sequence.getInstance(derObj);
Enumeration<ASN1Integer> e = asn1.getObjects();
BigInteger r = ((ASN1Integer)e.nextElement()).getValue();
BigInteger s = ((ASN1Integer)e.nextElement()).getValue();
SM2Result sm2Result = new SM2Result();
sm2Result.r = r;
sm2Result.s = s;
sm2.sm2Verify(md, userKey, sm2Result.r, sm2Result.s, sm2Result);
return sm2Result.r.equals(sm2Result.R);
}
return false;
}
return false;
}
public class MyKeyPair {
String publicKey;
String privateKey;
public String getPublicKey() {
return this.publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getPrivateKey() {
return this.privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
}
}

View File

@@ -1,54 +0,0 @@
package com.senmesh.sdk.ssb.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
public class SsbRsaUtils {
public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 =
new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
public static String encryptMd5(String plainText) {
String re_md5 = new String();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
re_md5 = buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return re_md5;
}
}

View File

@@ -1,378 +0,0 @@
package com.senmesh.sdk.ssb.util;
import java.math.BigInteger;
public class Util {
private static final char[] DIGITS_LOWER = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
public static byte[] intToBytes(int num) {
byte[] bytes = { (byte)(0xFF & num >> 0), (byte)(0xFF & num >> 8), (byte)(0xFF & num >> 16), (byte)(0xFF & num >> 24) };
return bytes;
}
public static int byteToInt(byte[] bytes) {
int num = 0;
int temp = (0xFF & bytes[0]) << 0;
num |= temp;
temp = (0xFF & bytes[1]) << 8;
num |= temp;
temp = (0xFF & bytes[2]) << 16;
num |= temp;
temp = (0xFF & bytes[3]) << 24;
num |= temp;
return num;
}
public static byte[] longToBytes(long num) {
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
bytes[i] = (byte)(int)(0xFFL & num >> i * 8);
return bytes;
}
public static byte[] byteConvert32Bytes(BigInteger n) {
byte[] tmpd = (byte[])null;
if (n == null)
return null;
if ((n.toByteArray()).length == 33) {
tmpd = new byte[32];
System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
} else if ((n.toByteArray()).length == 32) {
tmpd = n.toByteArray();
} else {
tmpd = new byte[32];
for (int i = 0; i < 32 - (n.toByteArray()).length; i++)
tmpd[i] = 0;
System.arraycopy(n.toByteArray(), 0, tmpd, 32 - (n.toByteArray()).length, (n.toByteArray()).length);
}
return tmpd;
}
public static BigInteger byteConvertInteger(byte[] b) {
if (b[0] < 0) {
byte[] temp = new byte[b.length + 1];
temp[0] = 0;
System.arraycopy(b, 0, temp, 1, b.length);
return new BigInteger(temp);
}
return new BigInteger(b);
}
public static String getHexString(byte[] bytes) {
return getHexString(bytes, true);
}
public static String getHexString(byte[] bytes, boolean upperCase) {
String ret = "";
for (int i = 0; i < bytes.length; i++)
ret = ret + Integer.toString((bytes[i] & 0xFF) + 256, 16).substring(1);
return upperCase ? ret.toUpperCase() : ret;
}
public static void printHexString(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1)
hex = '0' + hex;
System.out.print("0x" + hex.toUpperCase() + ",");
}
System.out.println("");
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString != null && !hexString.equals("")) {
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
return null;
}
public static byte charToByte(char c) {
return (byte)"0123456789ABCDEF".indexOf(c);
}
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
int i = 0;
for (int var5 = 0; i < l; i++) {
out[var5++] = toDigits[(0xF0 & data[i]) >>> 4];
out[var5++] = toDigits[0xF & data[i]];
}
return out;
}
public static String encodeHexString(byte[] data) {
return encodeHexString(data, true);
}
public static String encodeHexString(byte[] data, boolean toLowerCase) {
return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static String encodeHexString(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x1) != 0)
throw new RuntimeException("Odd number of characters.");
byte[] out = new byte[len >> 1];
int i = 0;
for (int j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte)(f & 0xFF);
}
return out;
}
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1)
throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
return digit;
}
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
String b = Integer.toHexString(c);
result = result + b;
}
return result;
}
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char)hexStringToAlgorism(hexString.substring(i * encodeType, (i + 1) * encodeType));
result = result + c;
}
return result;
}
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - 48;
} else {
algorism = c - 55;
}
result = (int)(result + Math.pow(16.0D, (max - i)) * algorism);
}
return result;
}
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result = result + "0000";
break;
case '1':
result = result + "0001";
break;
case '2':
result = result + "0010";
break;
case '3':
result = result + "0011";
break;
case '4':
result = result + "0100";
break;
case '5':
result = result + "0101";
break;
case '6':
result = result + "0110";
break;
case '7':
result = result + "0111";
break;
case '8':
result = result + "1000";
break;
case '9':
result = result + "1001";
break;
case 'A':
result = result + "1010";
break;
case 'B':
result = result + "1011";
break;
case 'C':
result = result + "1100";
break;
case 'D':
result = result + "1101";
break;
case 'E':
result = result + "1110";
break;
case 'F':
result = result + "1111";
break;
}
}
return result;
}
public static String AsciiStringToString(String content) {
String result = "";
int length = content.length() / 2;
for (int i = 0; i < length; i++) {
String c = content.substring(i * 2, i * 2 + 2);
int a = hexStringToAlgorism(c);
char b = (char)a;
String d = String.valueOf(b);
result = result + d;
}
return result;
}
public static String algorismToHexString(int algorism, int maxLength) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1)
result = "0" + result;
return patchHexString(result.toUpperCase(), maxLength);
}
public static String byteToString(byte[] bytearray) {
String result = "";
int length = bytearray.length;
for (int i = 0; i < length; i++) {
char temp = (char)bytearray[i];
result = result + temp;
}
return result;
}
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - 48;
result = (int)(result + Math.pow(2.0D, (max - i)) * algorism);
}
return result;
}
public static String algorismToHEXString(int algorism) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1)
result = "0" + result;
result = result.toUpperCase();
return result;
}
public static String patchHexString(String str, int maxLength) {
String temp = "";
for (int i = 0; i < maxLength - str.length(); i++)
temp = "0" + temp;
str = (temp + str).substring(0, maxLength);
return str;
}
public static int parseToInt(String s, int defaultInt, int radix) {
int i;
boolean var3 = false;
try {
i = Integer.parseInt(s, radix);
} catch (NumberFormatException var5) {
i = defaultInt;
}
return i;
}
public static int parseToInt(String s, int defaultInt) {
int i;
boolean var2 = false;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException var4) {
i = defaultInt;
}
return i;
}
public static byte[] hexToByte(String hex) throws IllegalArgumentException {
if (hex.length() % 2 != 0)
throw new IllegalArgumentException();
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
int i = 0;
int j = 0;
for (int l = hex.length(); i < l; j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = (new Integer(byteint)).byteValue();
i++;
}
return b;
}
public static String byteToHex(byte[] b) {
if (b == null)
throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
for (int i = 0; i < length; i++)
bt[i] = input[i + startIndex];
return bt;
}
}

View File

@@ -13,7 +13,6 @@ import com.senmesh.security.handle.MyAuthenctiationFailureHandler;
import com.senmesh.security.mobile.MobileAuthenticationProvider;
import com.senmesh.security.social.service.StandardClientRegistrationRepository;
import com.senmesh.security.social.wechat.service.WechatOauthLoginProvider;
import com.senmesh.security.ssb.SsbAuthenticationProvider;
import com.senmesh.security.temptoken.TokenAuthenticationProvider;
import com.senmesh.security.upassword.UpasswordAuthenticationProvider;
import com.senmesh.security.util.SecurityPropertyUtils;
@@ -80,12 +79,6 @@ public class SecurityConfiguration {
return new UpasswordAuthenticationProvider(userLoginService);
}
@Bean
@ConditionalOnBean(UserLoginService.class)
SsbAuthenticationProvider ssbAuthenticationProvider(UserLoginService userLoginService) {
return new SsbAuthenticationProvider(userLoginService);
}
@Bean
@ConditionalOnBean(UserLoginService.class)
UcardAuthenticationProvider ucardAuthenticationProvider(UserLoginService userLoginService) {

View File

@@ -31,8 +31,6 @@ import com.senmesh.security.mobile.MobileAuthenticationProvider;
import com.senmesh.security.social.service.StandardAuthorizationCodeTokenResponseClient;
import com.senmesh.security.social.service.StandardOAuth2UserService;
import com.senmesh.security.social.service.StandardOauth2AuthorizationRequestResolver;
import com.senmesh.security.ssb.SsbAuthenticationFilter;
import com.senmesh.security.ssb.SsbAuthenticationProvider;
import com.senmesh.security.temptoken.TokenAuthenticationFilter;
import com.senmesh.security.temptoken.TokenAuthenticationProvider;
import com.senmesh.security.upassword.UpasswordAuthenticationFilter;
@@ -78,8 +76,6 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired(required = false)
private TokenAuthenticationProvider tokenAuthenticationProvider;
@Autowired
private SsbAuthenticationProvider ssbAuthenticationProvider;
@Autowired(required = false)
private UcardAuthenticationProvider ucardAuthenticationProvider;
@@ -99,7 +95,6 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
auth.authenticationProvider(upasswordAuthenticationProvider)
.authenticationProvider(mobileAuthenticationProvider)
.authenticationProvider(tokenAuthenticationProvider)
.authenticationProvider(ssbAuthenticationProvider)
.authenticationProvider(ucardAuthenticationProvider);
;
}
@@ -151,12 +146,11 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(mobileAuthenticationFilter(), UpasswordAuthenticationFilter.class);
http.addFilterAfter(tokenAuthenticationFilter(), UpasswordAuthenticationFilter.class);
http.addFilterAfter(ssbAuthenticationFilter(), UpasswordAuthenticationFilter.class);
http.addFilterAfter(ucardAuthenticationFilter(), UpasswordAuthenticationFilter.class);
// 禁用CSRF
http.csrf().disable();
// http.csrf().disable();
http.headers().frameOptions().deny();
http.headers().xssProtection().block(true);
http.headers().contentTypeOptions();
@@ -205,7 +199,7 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
/**
* 手机号登录请求过滤器
*
* @param authenticationManager
* @param
* @return
* @throws Exception
* @author sr on 2020-06-04
@@ -248,11 +242,7 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
return filter;
}
private SsbAuthenticationFilter ssbAuthenticationFilter() throws Exception {
SsbAuthenticationFilter filter = new SsbAuthenticationFilter();
addHandler(filter);
return filter;
}
/**
* 身份证登录

View File

@@ -75,7 +75,7 @@ public class UserInfoDTO implements Serializable{
public void setPassword(String password){
this.password = password;
if (!PasswordUtils.match(UserUtils.DEFAULT_ORG_USER_PASSWORD, password)) {
if (!PasswordUtils.match(UserUtils.getDefaultOrgUserPassword(), password)) {
this.originPassword = Boolean.FALSE;
}
}

View File

@@ -21,7 +21,6 @@ import com.senmesh.common.util.ResponseUtils;
import com.senmesh.security.config.SecurityProperties;
import com.senmesh.security.dto.SecurityUserDTO;
import com.senmesh.security.jwt.JwtTokenUtils;
import com.senmesh.security.ssb.SsbAuthenticationFilter;
import com.senmesh.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
@@ -67,12 +66,7 @@ public class MyLoginSuccessHandler extends SavedRequestAwareAuthenticationSucces
AlitaResult.success(CasTokenDTO.builder().token(token).build()));
} else {
String successPage = securityProperties.getLoginSuccessPage();
if (request.getRequestURI().contains(SsbAuthenticationFilter.LOGIN_URI)) {
successPage = securityProperties.getLoginH5SuccessPage();
}
String successToUrl =
SecurityUtils.dealSuccessUrl(request, successPage, token);
response.sendRedirect(successToUrl);
response.sendRedirect(successPage);
}
}

View File

@@ -5,7 +5,6 @@ import org.springframework.security.oauth2.client.registration.ClientRegistratio
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import com.senmesh.security.ssb.SsbAuthenticationFilter;
import com.senmesh.usercenter.auth.constant.AuthTypeEnum;
public enum CommonOAuth2Provider {
@@ -27,22 +26,6 @@ public enum CommonOAuth2Provider {
}
},
SSBAPP {
@Override
public Builder getBuilder(String registrationId) {
ClientRegistration.Builder builder = getBuilder(registrationId,
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
builder.authorizationUri("https://api.eshimin.com/newOauth/authorize");
builder.tokenUri("https://api.eshimin.com/newOauth/accessToken");
builder.userInfoUri("https://api.eshimin.com/newOauth/userInfo");
builder.clientName(AuthTypeEnum.SSB_APP.name());
builder.scope("read");
builder.redirectUriTemplate("{baseUrl}/" + SsbAuthenticationFilter.LOGIN_URI);
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
return builder;
}
},
WECHAT_LITE {

View File

@@ -1,63 +0,0 @@
package com.senmesh.security.social.ssb.service;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.stereotype.Service;
import com.senmesh.sdk.ssb.SsbProperties;
import com.senmesh.sdk.ssb.util.SM2Utils;
import com.senmesh.security.social.service.IOauthProvider;
import com.senmesh.security.util.SecurityUtils;
import com.senmesh.usercenter.auth.constant.AuthTypeEnum;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class SsbOauthLoginProvider implements IOauthProvider {
private static final String AUTH_URL =
"https://api.eshimin.com/newOauth/authorize?client_id=%s&response_type=authorization_code&scope=read&redirect_uri=%s&timestamp=%s&sign=%s&state=%s";
@Autowired
private SsbProperties ssbProperties;
@Override
public String getName() {
return AuthTypeEnum.SSB_APP.name();
}
@Override
public OAuth2AuthorizationRequest decorateRequest(HttpServletRequest request,
OAuth2AuthorizationRequest authorizationRequest) {
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = SM2Utils.sign(ssbProperties.getSm2PrivateKey(),
ssbProperties.getAppKey() + ssbProperties.getAppSecret() + timestamp,
ssbProperties.getAppKey());
// 指定成功跳转地址
String redirectUrl =
SecurityUtils.dealRedirectUrl(request, authorizationRequest.getRedirectUri());
String state = "123";
// 微信Authorization Request URL
String authorizationRequestUri =
String.format(AUTH_URL,
authorizationRequest.getClientId(),
SecurityUtils.encodeURL(redirectUrl),
timestamp,
sign,
state);
return OAuth2AuthorizationRequest.from(authorizationRequest)
.authorizationRequestUri(authorizationRequestUri)
.build();
}
}

View File

@@ -1,70 +0,0 @@
package com.senmesh.security.ssb;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.senmesh.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 账号密码认证过滤器,指定请求组装token,调起认证
*
* @author sr on 2021-06-21
*/
@Slf4j
public class SsbAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private boolean postOnly = true;
public static final String REQUEST_METHOD = "GET";
public static final String LOGIN_URI = "/h5/ssb_login_notify";
public static final AntPathRequestMatcher requiresAuthenticationRequestMatcher =
new AntPathRequestMatcher(LOGIN_URI, REQUEST_METHOD);
public static final String PARAM_PLATFORM = "platform";
public static final String PARAM_ACCESS_TOKEN = "access_token";
public static final String PARAM_CODE = "code";
public static final String PARAM_STATE = "state";
public SsbAuthenticationFilter() {
super(requiresAuthenticationRequestMatcher);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (postOnly && !REQUEST_METHOD.equals(request.getMethod())) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String platform = request.getParameter(PARAM_PLATFORM);
String accessToken = request.getParameter(PARAM_ACCESS_TOKEN);
String code = request.getParameter(PARAM_CODE);
String state = request.getParameter(PARAM_STATE);
log.info("ssb login req params:{}", JsonUtils.toJsonString(request.getParameterMap()));
AbstractAuthenticationToken authRequest = new SsbAuthenticationToken(
SsbLoginDTO.builder().accessToken(accessToken).platform(platform).code(code).state(state).build(), accessToken);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
}

View File

@@ -1,70 +0,0 @@
package com.senmesh.security.ssb;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.senmesh.common.exception.util.Assert;
import com.senmesh.common.util.JsonUtils;
import com.senmesh.common.validation.util.ValidateUtils;
import com.senmesh.security.dto.SecurityUserDTO;
import com.senmesh.security.expection.BadLoginException;
import com.senmesh.security.mapstruct.UserMapMapper;
import com.senmesh.usercenter.user.login.dto.UserDetailDTO;
import com.senmesh.usercenter.user.login.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
/**
* 账号密码认证provider,比对信息是否匹配
*
* @author sr on 2021-06-21
*/
@Slf4j
public class SsbAuthenticationProvider implements AuthenticationProvider {
private UserLoginService userLoginService;
public SsbAuthenticationProvider(UserLoginService userLoginService) {
this.userLoginService = userLoginService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SsbLoginDTO ssbLoginDTO =
(SsbLoginDTO) authentication.getPrincipal();
log.info("ssb login req:{}", JsonUtils.toJsonString(ssbLoginDTO));
String errMsg = ValidateUtils.validate(ssbLoginDTO);
Assert.isTrue(errMsg == null, new BadLoginException(errMsg));
SecurityUserDTO loadedUser = null;
try {
UserDetailDTO userDetailDTO = this.userLoginService.loadUser(ssbLoginDTO);
loadedUser = UserMapMapper.INSTANCE.dtoToDto(userDetailDTO);
} catch (BadLoginException be) {
throw be;
} catch (Exception e) {
throw new BadLoginException(e.getMessage(), e);
}
SsbAuthenticationToken result =
new SsbAuthenticationToken(loadedUser, listUserGrantedAuthorities(loadedUser));
result.setDetails(authentication.getDetails());
return result;
}
@Override
public boolean supports(Class<?> authentication) {
return (SsbAuthenticationToken.class.isAssignableFrom(authentication));
}
private Set<GrantedAuthority> listUserGrantedAuthorities(UserDetails userDetails) {
// 什么都不用做,访问资源鉴权的时会拿userDetail去缓存获取对应权限
return new HashSet<GrantedAuthority>();
}
}

View File

@@ -1,24 +0,0 @@
package com.senmesh.security.ssb;
import java.util.Collection;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
/**
* 账号密码认证信息
* @author sr on 2021-06-21
*/
public class SsbAuthenticationToken extends UsernamePasswordAuthenticationToken {
public SsbAuthenticationToken(Object principal, Object credentials) {
super(principal, credentials);
}
public SsbAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(principal, credentials, authorities);
}
}

View File

@@ -1,32 +0,0 @@
package com.senmesh.security.ssb;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SsbLoginDTO implements Serializable {
/** **/
private static final long serialVersionUID = 6780283569028235063L;
/** 平台标识
eshimin: 随申办 APP
weixinmini:微信小程序
weixinmp:微信公众号
alipaymini:支付宝小程序
alipayfuwu:支付宝生活号 **/
// @NotBlank(message = "平台标识不能为空")
private String platform;
/** 用户令牌,作为获取用户信息的入参 **/
private String accessToken;
/** oauth code **/
private String code;
private String state;
}

View File

@@ -6,12 +6,6 @@ package com.senmesh.usercenter.constants;
* @author sr on 2019-10-10
*/
public class UserConstants {
/**
* 用户默认密码
**/
public static final String DEFAULT_PASSWORD = "123456";
/**
* 机构管理员后缀
**/

View File

@@ -44,7 +44,7 @@ public class UcUrlController {
if (urlTypeEnum == null) {
return AlitaResult.error("资源类型错误");
}
if (UrlTypeEnum.INTERFACE.equals(urlTypeEnum) && StringUtils.isEmpty(urlDTO.getLink())) {
if (UrlTypeEnum.INTERFACE == urlTypeEnum && StringUtils.isEmpty(urlDTO.getLink())) {
return AlitaResult.error("接口地址不能为空");
}
return AlitaResult.success(urlService.creatUrl(urlDTO));

View File

@@ -102,7 +102,7 @@ public class UserDetailDTO implements Serializable{
public void setPassword(String password){
this.password = password;
if (!PasswordUtils.match(password, UserUtils.DEFAULT_ORG_USER_PASSWORD)) {
if (!PasswordUtils.match(password, UserUtils.getDefaultOrgUserPassword())) {
originPassword = Boolean.FALSE;
}
}

View File

@@ -4,7 +4,6 @@ import com.senmesh.usercenter.user.login.dto.LoginUCardDTO;
import javax.servlet.http.HttpServletRequest;
import com.senmesh.security.service.IUserSecurityService;
import com.senmesh.security.ssb.SsbLoginDTO;
import com.senmesh.usercenter.auth.dto.AuthClientDTO;
import com.senmesh.usercenter.auth.dto.AuthClientQueryDTO;
import com.senmesh.usercenter.auth.dto.AuthDetailLoginDTO;
@@ -44,6 +43,4 @@ public interface UserLoginService extends IUserSecurityService {
*/
void checkActive(HttpServletRequest request);
UserDetailDTO loadUser(SsbLoginDTO ssbLoginDTO);
}

View File

@@ -21,16 +21,9 @@ import com.senmesh.common.util.RandomUtils;
import com.senmesh.common.util.UserContextHolder;
import com.senmesh.common.validation.util.ValidateUtils;
import com.senmesh.frame.redis.util.RedisUtils;
import com.senmesh.sdk.ssb.constant.SsbConstants;
import com.senmesh.sdk.ssb.dto.SsbAppUserInfoDTO;
import com.senmesh.sdk.ssb.dto.SsbUserDTO;
import com.senmesh.sdk.ssb.dto.SsbUserDataDTO;
import com.senmesh.sdk.ssb.dto.SsbUserReq;
import com.senmesh.sdk.ssb.service.SsbInvoker;
import com.senmesh.security.expection.BadLoginException;
import com.senmesh.security.expection.DuplicateOrgException;
import com.senmesh.security.expection.DuplicateUserException;
import com.senmesh.security.ssb.SsbLoginDTO;
import com.senmesh.security.temptoken.dto.DuplMobileToken;
import com.senmesh.security.temptoken.dto.DuplUserToken;
import com.senmesh.security.temptoken.dto.PhoneTokenCreateDTO;
@@ -46,7 +39,6 @@ import com.senmesh.usercenter.user.constant.UserStatusEnum;
import com.senmesh.usercenter.user.constant.UserTypeEnum;
import com.senmesh.usercenter.user.dao.OrgUserMapper;
import com.senmesh.usercenter.user.dao.UserMapper;
import com.senmesh.usercenter.user.dto.AuthenticateUserDTO;
import com.senmesh.usercenter.user.dto.PersonUserPhoneCreateDTO;
import com.senmesh.usercenter.user.dto.UserDetailQueryDTO;
import com.senmesh.usercenter.user.dto.UserRegisterCreateDTO;
@@ -91,8 +83,7 @@ public class UserLoginServiceImpl implements UserLoginService {
@Autowired
private UserRegisterService userRegisterService;
@Autowired
private SsbInvoker ssbInvoker;
@Override
@@ -405,47 +396,6 @@ public class UserLoginServiceImpl implements UserLoginService {
}
}
@Override
public UserDetailDTO loadUser(SsbLoginDTO ssbLoginDTO) {
String realName = null;
String phone = null;
String cardNo = null;
if (StringUtils.isNotBlank(ssbLoginDTO.getCode())) {
// app登录
SsbAppUserInfoDTO ssbAppUserInfoDTO = ssbInvoker.getAppUser(ssbLoginDTO.getCode());
Assert.isTrue(SsbAppUserInfoDTO.AUTHENTICATIED.equals(ssbAppUserInfoDTO.getStatus()), "用户未实名");
realName = ssbAppUserInfoDTO.getName();
phone = ssbAppUserInfoDTO.getMobile();
cardNo = ssbAppUserInfoDTO.getIdcard();
} else {
// 小程序登录
// 调用ssb获取用户信息
AlitaResult<SsbUserDataDTO> ssbUserResult = ssbInvoker
.getUser(SsbUserReq.builder().accessToken(ssbLoginDTO.getAccessToken()).build());
Assert.isTrue(ssbUserResult.getSuccess(),
new BadLoginException("获取随申办用户失败:" + ssbUserResult.getMsg()));
// 根据身份证创建/获取用户
SsbUserDTO ssbUserDTO = ssbUserResult.getData().getData();
Assert.notNull(ssbUserDTO, "获取随申办用户失败null:" + ssbUserResult.getData().getMsg());
realName = ssbUserDTO.getZwdtsw_name();
phone = ssbUserDTO.getZwdtsw_link_phone();
cardNo = ssbUserDTO.getZwdtsw_cert_id();
Integer certType = ssbUserDTO.getCertType();
Assert.notBlank(cardNo, "用户未实名");
Assert.isTrue(SsbConstants.CERT_TYPE_ID_CARD.equals(certType),
new BadLoginException("暂只支持居民身份证实名用户登录"));
}
// 未实名,实名用户
Long userId = userService.createAndAuthenticatePersonUser(
AuthenticateUserDTO.builder().realName(realName).cardNo(cardNo).phone(phone).build());
UserDetailDTO userDetailDTO = this.findUserDetailDTO(
UserDetailQueryDTO.builder().userId(userId).userType(UserTypeEnum.PERSON.getType())
.build());
dealActiveStatus(userDetailDTO);
return userDetailDTO;
}
@Override
public UserDetailDTO loadUser(LoginUCardDTO loginUCardDTO) {
String cardNo = loginUCardDTO.getCardNo();

View File

@@ -21,7 +21,11 @@ public class UserUtils {
public static final int NICKNAME_LENGTH = 12;
public static final String DEFAULT_AVATAR_KEY = "user.default.avatars";
public static final String DEFAULT_ORG_USER_PASSWORD = "Qaz123567!@#";
public static final String DEFAULT_ORG_USER_PASSWORD_KEY = "user.default.password";
public static String getDefaultOrgUserPassword() {
return EnvironmentUtils.getProperty(DEFAULT_ORG_USER_PASSWORD_KEY);
}
/**
* 设置创建用户初始状态数据 (账号随机生成/非超管/非实名/待激活/已启用-登录相关)
@@ -53,7 +57,7 @@ public class UserUtils {
//创建用户的时候就给手机号绑定状态改为已绑定
user.setPhoneBinding(true);
user.setUsername(user.getPhone());
user.setPassword(PasswordUtils.encode(DEFAULT_ORG_USER_PASSWORD));
user.setPassword(PasswordUtils.encode(getDefaultOrgUserPassword()));
}
public static String dealNickname(String nickname, String phone) {

View File

@@ -1,125 +0,0 @@
spring.application.name=s-file
system.code=1
##数据源
spring.datasource.url=jdbc:postgresql://139.159.237.199:8608/f?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=postgres
spring.datasource.password=f123456
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化时建立物理连接的个数
spring.datasource.druid.initial-size=20
# 最大连接池数量
spring.datasource.druid.max-active=50
# 最小连接池数量
spring.datasource.druid.min-idle=20
# 获取连接时最大等待时间,单位毫秒
spring.datasource.druid.max-wait=60000
spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB
spring.cloud.config.allowOverride=true
spring.cloud.config.overrideNone=true
# mybatis
mybatis.mapperLocations=classpath*:com/senmesh/**/mapper/*Mapper.xml
mybatis.configuration.map-underscore-to-camel-case=true
pagehelper.helperDialect=postgresql
pagehelper.reasonable=true
#mybatis plus
mybatis-plus.mapper-locations=classpath*:com/senmesh/**/mapper/*.xml
mybatis-plus.configuration.default-enum-type-handler=com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler
mybatis-plus.type-aliases-package=com.senmesh.**.entity
mybatis-plus.type-enums-package=com.senmesh.**.enums
### 日志文件
logging.file.name=/Users/sr/work/git/project/x-file/logs/${spring.application.name}.log
logging.pattern.console:%d{yyyy/MM/dd-HH:mm:ss} %X{traceId:-} [%thread] %-5level %logger- %msg%n
logging.pattern.file:%d{yyyy/MM/dd-HH:mm:ss} %X{traceId:-} [%thread] %-5level %logger- %msg%n
### 文件路径
file.upload-dir=/Users/sr/work/git/project/x-file/upload
java.io.tmpdir=/var/${spring.application.name}/upload/tmpdir
#文件存储配置
file.storage.type=local
#文件传输配置
### 文件位置:1内网2外网
file.transfer.location=1
### 传输发送目录
file.transfer.send-dir=${file.upload-dir}/transfer/send
### 传输接收目录
file.transfer.receive-dir=${file.upload-dir}/transfer/receive
### 解包风险校验
file.transfer.unpack-risk-check=false
#发号器
#机器id:根据ip自己定义
code.snowflake.workid.192.168.1.28=1
code.snowflake.workid.192.168.71.2=2
##redis配置
spring.redis.password=Nm6uHJQLWQ17qwct
spring.redis.host=121.37.2.171
spring.redis.port=3004
spring.redis.lettuce.pool.min-idle=2
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.database=2
security.useLocal=true
security.ignoring=/*.html,/favicon.ico
security.anonymous=/anon/**,/druid/**,/ws/**
security.loginPage=/login.html
security.loginSuccessPage=/
security.loginH5SuccessPage=/h5/
security.loginProcessingUrl=/login
security.allowIfAllAbstainDecisions=false
security.domain=
#不记日志路径,contains匹配
security.notLogs=/district,/dict/lookup,/dict/flush,/anon/dropdown,/anon/user/info,/domain_setting,/anon/config
security.jwt.enable=true
security.jwt.secret=abcdef
security.jwt.expiration=28800
security.jwt.header=Authorization
security.jwt.iss=${spring.application.name}
#oauth配置
security.oauth2.enable=false
#oauth配置类型:true使用数据库配置,否则配置文件
#security.oauth2.usedb=true
swagger.enable=true
#websocket配置
websocket.enable=true
# 短信开关
sms.enable=false
sms.domain=dysmsapi.aliyuncs.com
sms.accessKeyId=
sms.accessSecret=
sms.regionId=default
sms.version=2017-05-25
# properties中文乱码
sms.signName=
sms.numLimit=0
#短信验证码模板配置
sms.phoneSms=
#dify配置
dify.enable=true
dify.host=http://114.242.42.23:8501
# 规则生成 API Key
dify.risk.rule.api-key=app-MpPUct23vJFOGYThX5AP13MH
# 文件智能风险预警 API Key
dify.risk.scan.api-key=app-yssNjcvzAf5KEZY1ZIiKQU7W

View File

@@ -2,10 +2,6 @@ package com.senmesh;
public class PwdTest {
public static void main(String[] args) {
String password = "Qaz123567!@#";
String encode = com.senmesh.security.util.PasswordUtils.encode(password);
System.out.println(encode);
}
}