修改秘钥认证方式

master
林颖晨 1 year ago
parent 76622371f2
commit 7ce70c4cb4
  1. 7
      pom.xml
  2. 8
      psdc-business/pom.xml
  3. 8
      psdc-business/src/main/java/com/psdc/entity/PrivateKey.java
  4. 19
      psdc-business/src/main/java/com/psdc/service/impl/GenerateKeyIml.java
  5. 34
      psdc-business/src/main/java/com/psdc/service/impl/PrivateKeyServiceImpl.java
  6. 11
      psdc-business/src/main/java/com/psdc/service/model/impl/BuildHeatingServiceImpl.java
  7. 14
      psdc-business/src/main/resources/mapper/business/PrivateKeyMapper.xml
  8. 14
      psdc-common/pom.xml
  9. 118
      psdc-common/src/main/java/com/psdc/utils/Sm2Util.java
  10. 10
      psdc-web/src/main/java/com/psdc/controller/key/GenerateKeyController.java
  11. 10
      psdc-web/src/main/java/com/psdc/controller/key/SecretKeyController.java
  12. 2
      psdc.iml

@ -15,6 +15,7 @@
<manager.version>0.0.1</manager.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<hutool.version>5.8.18</hutool.version>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<druid.version>1.2.16</druid.version>
@ -52,6 +53,12 @@
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>

@ -29,12 +29,6 @@
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.5</version>
</dependency>
<dependency>
<groupId>com.psdc</groupId>
<artifactId>psdc-quartz</artifactId>
@ -46,7 +40,7 @@
<dependency>
<groupId>com.dky</groupId>
<artifactId>dntd-tool</artifactId>
<version>1.2-SNAPSHOT</version>
<version>1.0-SNAPSHOT</version>
</dependency>

@ -13,10 +13,12 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class PrivateKey {
/** 钥Id */
/** 钥Id */
private Integer id ;
/** 私钥密文 */
private String keyValue ;
/** 公钥 */
private String publicKey ;
/** 私钥 */
private String privateKey ;
/** 授权单位 */
private String keyUnit ;
/** 创建时间 */

@ -3,6 +3,7 @@ package com.psdc.service.impl;
import com.phcomponent.basictech.elementary.util.SM4Util;
import com.psdc.service.IGenerateKey;
import com.psdc.utils.Sm2Util;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Service;
@ -33,18 +34,14 @@ public class GenerateKeyIml implements IGenerateKey {
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
@Override
public String generateKey(Map map, String sm4) {
String key;
public String generateKey(Map map, String publicKey) {
String key = null;
try {
// 解密 SM4Util sm4Util = new SM4Util();
// String decryptBySM4ECB = sm4Util.decryptBySM4ECB(sm4, SM4_KEY);
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec secretKey = new SecretKeySpec(sm4.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(mapToString(map).getBytes(StandardCharsets.UTF_8));
key = Base64.getEncoder().encodeToString(encrypted);
} catch (NoSuchPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | BadPaddingException |
NoSuchProviderException | InvalidKeyException e) {
key = Sm2Util.encryptBase64(mapToString(map), publicKey);
} catch (IllegalArgumentException e) {
System.err.println("提供的秘钥错误");
e.printStackTrace();
} catch (Exception e) {
throw new RuntimeException(e);
}
return key;

@ -5,7 +5,7 @@ import com.psdc.core.domain.AjaxResult;
import com.psdc.entity.PrivateKey;
import com.psdc.mapper.PrivateKeyMapper;
import com.psdc.service.IPrivateKeyService;
import org.apache.commons.lang3.RandomStringUtils;
import com.psdc.utils.Sm2Util;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@ -28,18 +28,19 @@ public class PrivateKeyServiceImpl implements IPrivateKeyService {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String SM4_KEY = "D30CCEEC367C55F0E4C7B3BE8207C5DD";
@Override
public AjaxResult insert(PrivateKey privateKey) {
String key = RandomStringUtils.randomAlphabetic(16);
SM4Util sm4Util = new SM4Util();
// 加密
String encryptBySM4ECB = sm4Util.encryptBySM4ECB(key, SM4_KEY);
privateKey.setKeyValue(encryptBySM4ECB);
privateKey.setCreateTime(sdf.format(new Date()));
public AjaxResult insert(PrivateKey info) {
//生成密钥对
Map<String, String> stringStringMap = Sm2Util.generateSm2Key();
String publicKey = stringStringMap.get(Sm2Util.KEY_PUBLIC_KEY);
String privateKey = stringStringMap.get(Sm2Util.KEY_PRIVATE_KEY);
info.setPublicKey(publicKey);
info.setPrivateKey(privateKey);
info.setCreateTime(sdf.format(new Date()));
AjaxResult ajax = new AjaxResult();
ajax.put("data", privateKeyMapper.insert(privateKey));
ajax.put("data", privateKeyMapper.insert(info));
return ajax;
}
@ -72,13 +73,7 @@ public class PrivateKeyServiceImpl implements IPrivateKeyService {
long pageCount = (count/pageSize) + (count%pageSize==0?0:1);
AjaxResult ajax = new AjaxResult();
Map map = new HashMap<String, Object>();
SM4Util sm4Util = new SM4Util();
List<PrivateKey> list = privateKeyMapper.queryAllByLimit(keyUnit, start, pageSize);
list.parallelStream().forEach((s)->{
// 解密
String decryptBySM4ECB = sm4Util.decryptBySM4ECB(s.getKeyValue(), SM4_KEY);
s.setKeyValue(decryptBySM4ECB);
});
ajax.put("data", list);
map.put("pageCurrent", pageCurrent);
map.put("pageSize", pageSize);
@ -92,13 +87,12 @@ public class PrivateKeyServiceImpl implements IPrivateKeyService {
public AjaxResult selectAll() {
List<Map> ary = new ArrayList<>();
AjaxResult ajax = new AjaxResult();
SM4Util sm4Util = new SM4Util();
List<PrivateKey> list = privateKeyMapper.selectAll();
list.parallelStream().forEach((s)->{
Map map = new HashMap<String, Object>();
// 解密
String decryptBySM4ECB = sm4Util.decryptBySM4ECB(s.getKeyValue(), SM4_KEY);
map.put("key", decryptBySM4ECB);
String publicKey = s.getPublicKey();
map.put("key", publicKey);
map.put("unit", s.getKeyUnit());
ary.add(map);
});

@ -8,7 +8,10 @@ import com.psdc.service.model.IBuildHeatingService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @AuthorStone
@ -26,6 +29,12 @@ public class BuildHeatingServiceImpl implements IBuildHeatingService {
@Override
public JSONObject exeModel2Report(JSONObject param, String key) {
//模拟数据库查询,构造出加密解密方式
List<Map> mapList = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
map.put("CREATE_TIME","2024-02-20 14:46:34");
mapList.add(map);
mapList.add(map);
// 创建JSONObject对象用于承接模型方法输出结果。
JSONObject jsonObject = null;
try{
@ -38,7 +47,7 @@ public class BuildHeatingServiceImpl implements IBuildHeatingService {
// 将这个JSONObject对象list作为入参调用ModelTool的create方法实现产品库初始化。
ModelTool modelTool = ModelTool.create(list);
// 调用ModelTool的唯一入口函数exeModel2Report,将场景参数param和密钥key作为入参传进去,得到输出结果电能替代报告。
jsonObject = modelTool.exeModel2Report(param, key);
jsonObject = modelTool.exeModel2Report(param, key,mapList);
} catch (Exception e){
e.printStackTrace();

@ -4,7 +4,8 @@
<mapper namespace="com.psdc.mapper.PrivateKeyMapper">
<resultMap type="com.psdc.entity.PrivateKey" id="PrivateKeyMap">
<result property="id" column="id" />
<result property="keyValue" column="key_value" />
<result property="publicKey" column="public_key" />
<result property="privateKey" column="private_key" />
<result property="keyUnit" column="key_unit" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
@ -39,8 +40,8 @@
<!--新增数据-->
<insert id="insert" >
Insert into private_key(key_value,key_unit,create_time,update_time)
values (#{keyValue},#{keyUnit},#{createTime},#{updateTime})
Insert into private_key(private_key,public_key,key_unit,create_time,update_time)
values (#{privateKey},#{publicKey},#{keyUnit},#{createTime},#{updateTime})
</insert>
<!-- 更新数据 -->
@ -50,8 +51,11 @@
<if test="id != null and id != ''">
id = #{id},
</if>
<if test="keyValue != null and keyValue != ''">
key_value = #{keyValue},
<if test="privateKey != null and privateKey != ''">
private_key = #{privateKey},
</if>
<if test="publicKey != null and publicKey != ''">
public_key = #{publicKey},
</if>
<if test="keyUnit != null and keyUnit != ''">
key_unit = #{keyUnit},

@ -48,12 +48,24 @@
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

@ -0,0 +1,118 @@
package com.psdc.utils;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import java.util.HashMap;
import java.util.Map;
/**
* SM2秘钥生成签名验签工具类
* @author 只有影子
*/
public class Sm2Util {
/**
* 公钥常量
*/
public static final String KEY_PUBLIC_KEY = "publicKey";
/**
* 私钥返回值常量
*/
public static final String KEY_PRIVATE_KEY = "privateKey";
/**
* 生成SM2公私钥
*
* @return
*/
public static Map<String, String> generateSm2Key() {
SM2 sm2 = new SM2();
ECPublicKey publicKey = (ECPublicKey) sm2.getPublicKey();
ECPrivateKey privateKey = (ECPrivateKey) sm2.getPrivateKey();
// 获取公钥
byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
String publicKeyHex = HexUtil.encodeHexStr(publicKeyBytes);
// 获取64位私钥
String privateKeyHex = privateKey.getD().toString(16);
// BigInteger转成16进制时,不一定长度为64,如果私钥长度小于64,则在前方补0
StringBuilder privateKey64 = new StringBuilder(privateKeyHex);
while (privateKey64.length() < 64) {
privateKey64.insert(0, "0");
}
Map<String, String> result = new HashMap<>();
result.put(KEY_PUBLIC_KEY, publicKeyHex);
result.put(KEY_PRIVATE_KEY, privateKey64.toString());
return result;
}
/**
* SM2私钥签名
*
* @param privateKey 私钥
* @param content 待签名内容
* @return 签名值
*/
public static String sign(String privateKey, String content) {
SM2 sm2 = new SM2(privateKey, null);
return sm2.signHex(HexUtil.encodeHexStr(content));
}
/**
* SM2公钥验签
*
* @param publicKey 公钥
* @param content 原始内容
* @param sign 签名
* @return 验签结果
*/
public static boolean verify(String publicKey, String content, String sign) {
SM2 sm2 = new SM2(null, publicKey);
return sm2.verifyHex(HexUtil.encodeHexStr(content), sign);
}
/**
* SM2公钥加密
*
* @param content 原文
* @param publicKey SM2公钥
* @return
*/
public static String encryptBase64(String content, String publicKey) {
SM2 sm2 = new SM2(null, publicKey);
return sm2.encryptBase64(content, KeyType.PublicKey);
}
/**
* SM2私钥解密
*
* @param encryptStr SM2加密字符串
* @param privateKey SM2私钥
* @return
*/
public static String decryptBase64(String encryptStr, String privateKey) {
SM2 sm2 = new SM2(privateKey, null);
return StrUtil.utf8Str(sm2.decrypt(encryptStr, KeyType.PrivateKey));
}
public static void main(String[] args) {
String privateKey = "1100fba8ee67ddf1f6f4e37c500dc10eee1bf15827ae3837810e30f402fa0bc6";
String publicKey = "048421649b6acdd22bc5075ef937dd35bb165b1db32eb4bd2fc666f07808819c88ac7dbeaeeb367bfe53601db55372bc16bf284dbf12f6b5f0df111023df88a4b0";
String encrypt = "BPTfj7kSlu6fJHpn/t2IQ1R83MPuA3sjgySntyYRo8GEgUNnTYoxaOX2FTK+X/bPllVx8Ly4/1l2FUb9JwRRbzbMPIdIfal7qO4ftJKJTN1M555BUSyGUOEBHivrarFiliiwnZH5dD4YV+kRUUD70o/1zEysm5M6/FrzXebRcH9EsnLEGta9D+urvisjamjQmunV3razxlsd+SYvbSsYmDRp8QjbJLpkfrlJBL484cB5Nhj8XWx8IZb3lvINkkq+";
String decrypt = decryptBase64(encrypt, privateKey);
System.out.println("解密后结果:" + decrypt);
}
}

@ -33,11 +33,7 @@ public class GenerateKeyController extends BaseController {
@PostMapping("/getKey")
public AjaxResult getGenerateKey(@RequestBody Map<String, Object> requestBody) {
List<String> cpuIds = (List<String>) requestBody.get("cpuIds");
List<String> thisCpuIds = new ArrayList<>();
for (String s : cpuIds){
thisCpuIds.add(secretKeyService.getString(s));
}
String cpuIds = (String) requestBody.get("cpuIds");
String expiration = (String) requestBody.get("expiration");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@ -46,13 +42,13 @@ public class GenerateKeyController extends BaseController {
Map map = new HashMap();
map.put("companyname", companyName);
map.put("expireTime", expiration);
map.put("cpuIds", thisCpuIds.toString());
map.put("cpuIds", cpuIds);
AjaxResult ajax = AjaxResult.success();
String s = generateKey.generateKey(map, key);
ajax.put("key", s);
SecretKey secretKey = new SecretKey();
secretKey.setKeyValue(s);
secretKey.setCpuIds(thisCpuIds.toString());
secretKey.setCpuIds(cpuIds);
secretKey.setExportDate(expiration);
secretKey.setKeyUnit(companyName);
SecretKey selOne = secretKeyService.selOne(s, expiration);

@ -73,11 +73,7 @@ public class SecretKeyController {
@PostMapping("/upKeyData")
public AjaxResult upKeyDate(@RequestBody Map<String, Object> requestBody){
List<String> cpuIds = (List<String>) requestBody.get("cpuIds");
List<String> thisCpuIds = new ArrayList<>();
for (String s : cpuIds){
thisCpuIds.add(secretKeyService.getString(s));
}
String cpuIds = (String) requestBody.get("cpuIds");
String expiration = (String) requestBody.get("expiration");
String key = (String) requestBody.get("key");
String companyName = (String) requestBody.get("companyname");
@ -85,14 +81,14 @@ public class SecretKeyController {
Map map = new HashMap();
map.put("companyname", companyName);
map.put("expireTime", expiration);
map.put("cpuIds", thisCpuIds.toString());
map.put("cpuIds", cpuIds);
AjaxResult ajax = AjaxResult.success();
String s = generateKey.generateKey(map, key);
ajax.put("key", s);
SecretKey secretKey = new SecretKey();
secretKey.setKeyValue(s);
secretKey.setId(id);
secretKey.setCpuIds(thisCpuIds.toString());
secretKey.setCpuIds(cpuIds);
secretKey.setExportDate(expiration);
secretKey.setKeyUnit(companyName);
secretKeyService.updateById(secretKey);

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="SonarLintModuleSettings">
<option name="uniqueId" value="e0e65c8c-c72b-4c01-9e02-b8ffdedfe42d" />
<option name="uniqueId" value="6bcdc49b-b703-4695-90af-274371a6666f" />
</component>
</module>
Loading…
Cancel
Save