Commit 96ee03a3 by 杨林龙

优化RSA公秘钥生成和使用方式 yangll

1 parent 76c1aa41
......@@ -4,6 +4,7 @@ import cn.com.glsx.openplatform.model.PlatformCustomer;
import cn.com.glsx.openplatform.vo.R;
import cn.hutool.db.Page;
import java.security.NoSuchAlgorithmException;
import java.util.List;
public interface CustomerMgrService {
......@@ -15,7 +16,7 @@ public interface CustomerMgrService {
int getCustomerCount();
int register(PlatformCustomer customer);
int register(PlatformCustomer customer) throws NoSuchAlgorithmException;
PlatformCustomer login(PlatformCustomer customer);
......
......@@ -28,4 +28,6 @@ public interface PlatformCustomerMapper extends OreMapper<PlatformCustomer> {
List<String> getAddressOptionList(@Param("id") int id);
String getAddressStr(@Param("id") Integer id);
String getPrivateSecret(@Param("appId") int appId);
}
\ No newline at end of file
......@@ -2,6 +2,7 @@ package cn.com.glsx.openplatform.service;
import cn.com.glsx.openplatform.mapper.PlatformCustomerMapper;
import cn.com.glsx.openplatform.model.PlatformCustomer;
import cn.com.glsx.openplatform.util.RSAUtils;
import cn.com.glsx.openplatform.vo.R;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Page;
......@@ -13,9 +14,11 @@ import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;
@Service
public class CustomerMgrServiceImpl implements CustomerMgrService {
......@@ -57,15 +60,20 @@ public class CustomerMgrServiceImpl implements CustomerMgrService {
}
@Override
public int register(PlatformCustomer customer) {
String modulus = RandomUtil.randomNumbers(512);
String exponent = RandomUtil.randomNumbers(64);
public int register(PlatformCustomer customer) throws NoSuchAlgorithmException {
// String modulus = RandomUtil.randomNumbers(512);
// String exponent = RandomUtil.randomNumbers(64);
//
// PrivateKey privateKey = RsaUtil.generatePrivateKey(modulus, exponent);
// PublicKey publicKey = RsaUtil.generatePublicKey(modulus, exponent);
// BASE64Encoder enc = new BASE64Encoder();
// customer.setPrivateKey(enc.encode(privateKey.getEncoded()));
// customer.setPublicKey(enc.encode(publicKey.getEncoded()));
PrivateKey privateKey = RsaUtil.generatePrivateKey(modulus, exponent);
PublicKey publicKey = RsaUtil.generatePublicKey(modulus, exponent);
BASE64Encoder enc = new BASE64Encoder();
customer.setPrivateKey(enc.encode(privateKey.getEncoded()));
customer.setPublicKey(enc.encode(publicKey.getEncoded()));
Map<Integer, String> map = RSAUtils.genKeyPair();
customer.setPublicKey(map.get(0));
customer.setPrivateKey(map.get(1));
String province = customerMapper.getAddressStr(customer.getProvince());
String city = customerMapper.getAddressStr(customer.getCity());
......
......@@ -8,8 +8,8 @@ import cn.hutool.db.Page;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
......@@ -20,7 +20,6 @@ import java.util.Map;
* 开放平台对外接口API相关服务
*/
@Service
@Data
@Slf4j
public class IceOpenApiServiceImpl implements IceOpenApiService {
@Resource
......@@ -34,6 +33,7 @@ public class IceOpenApiServiceImpl implements IceOpenApiService {
/**
* 获取商户下的数据概况信息
*
* @param customerId 客户id
* @return Map 数据信息
*/
......@@ -68,22 +68,22 @@ public class IceOpenApiServiceImpl implements IceOpenApiService {
/**
* 获取私钥
*
* @param appId 用户id
* @return String 私钥
*/
@Override
public String getPrivateSecret(int appId) {
log.info("rpc==getPrivateSecret开始==appid:"+appId);
log.info("rpc==getPrivateSecret开始==appid:" + appId);
//查询客户信息
PlatformCustomer platformCustomer = getPlatformCustomer(appId);
//返回客户私钥
String privateKey = platformCustomer.getPrivateKey();
log.info("rpc==getPrivateSecret开始==appid:"+privateKey);
String privateKey = customerMapper.getPrivateSecret(appId);
log.info("rpc==getPrivateSecret开始==appid:" + privateKey);
return privateKey;
}
/**
* 查询客户信息
*
* @param appId 客户id
* @return PlatformCustomer 客户信息实体类
*/
......@@ -95,34 +95,35 @@ public class IceOpenApiServiceImpl implements IceOpenApiService {
/**
* 获取客户数据概况信息
*
* @param appId 用户id
* @return Map 用户信息
*/
@Override
public Map<String,Object> getCustomerInfo(int appId) {
log.info("rpc==getCustomerInfo开始==appid:"+appId);
public Map<String, Object> getCustomerInfo(int appId) {
log.info("rpc==getCustomerInfo开始==appid:" + appId);
//查询客户信息
PlatformCustomer platformCustomer = getPlatformCustomer(appId);
//封装返回数据
Map<String,Object> res = new HashMap<>();
Map<String, Object> res = new HashMap<>();
//客户ID
res.put("appid",appId);
res.put("appid", appId);
//客户名称
res.put("customer_name",platformCustomer.getCustomerName());
res.put("customer_name", platformCustomer.getCustomerName());
//联系电话
res.put("contact_number",platformCustomer.getContactNumber());
res.put("contact_number", platformCustomer.getContactNumber());
//渠道号
res.put("channel_number",platformCustomer.getChannelNumber());
log.info("rpc==getCustomerInfo结果==appid:"+res);
res.put("channel_number", platformCustomer.getChannelNumber());
log.info("rpc==getCustomerInfo结果==appid:" + res);
return res;
}
@Override
public Map<String, Object> getDeviceList(Integer appid,Page page, Date start_time, Date end_time) {
log.info("rpc==getDeviceList开始==appid:"+appid,"==page:"+page+"==start_time:"+start_time,"==end_time:"+start_time);
public Map<String, Object> getDeviceList(Integer appid, Page page, Date start_time, Date end_time) {
log.info("rpc==getDeviceList开始==appid:" + appid, "==page:" + page + "==start_time:" + start_time, "==end_time:" + start_time);
//分页查询
PageHelper.startPage(page.getPageNumber(), page.getPageSize(), true);
List<Map<String, Object>> deviceList = deviceMapper.getDeviceByTimeRangeAndCustID(start_time,end_time,appid+"");
List<Map<String, Object>> deviceList = deviceMapper.getDeviceByTimeRangeAndCustID(start_time, end_time, appid + "");
//分页结果
PageInfo pageInfo = new PageInfo<>(deviceList);
......@@ -130,13 +131,13 @@ public class IceOpenApiServiceImpl implements IceOpenApiService {
HashMap<String, Object> hashMap = new HashMap<>();
//是否有更多用户数据
boolean hasMore = page.getPageNumber() < pageInfo.getPages();
hashMap.put("has_more",hasMore);
hashMap.put("has_more", hasMore);
//显示该appid下所有的用户数
int total = userMapper.getUserCountByCustomerId(appid);
hashMap.put("total",total);
hashMap.put("total", total);
//设备数据
hashMap.put("list",pageInfo.getList());
log.info("rpc==getDeviceList结果=="+hashMap);
hashMap.put("list", pageInfo.getList());
log.info("rpc==getDeviceList结果==" + hashMap);
return hashMap;
}
}
package cn.com.glsx.openplatform.util;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* @author fengzhi
* @version V1.0
* @Description: RSA工具类
*/
@Component
public class RSAUtils {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
//加密字符串
String message = "appId4grantType1time123456";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的公钥为:" + keyMap.get(0).length());
System.out.println("随机生成的私钥为:" + keyMap.get(1));
System.out.println("随机生成的私钥为:" + keyMap.get(1).length());
//String messageEn = encrypt(message, OpenAPIConstant.TEST_PUBLIC_KEY);
String messageEn = encrypt(message, keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = decrypt(messageEn, keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
}
/**
* 随机生成密钥对
*
* @throws NoSuchAlgorithmException
*/
public static Map<Integer, String> genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(512, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0, publicKeyString); //0表示公钥
keyMap.put(1, privateKeyString); //1表示私钥
return keyMap;
}
/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(String str, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
}
......@@ -98,4 +98,13 @@
from t_sys_area
where id = #{id,jdbcType=INTEGER}
</select>
<select id="getPrivateSecret" resultType="java.lang.String">
select
private_key
from
t_platform_secretkey a
left join t_platform_customer b on a.id = b.key_id
where b.id = #{appId,jdbcType=INTEGER}
</select>
</mapper>
......@@ -6,11 +6,11 @@ import cn.hutool.core.util.RandomUtil;
import net.dreamlu.mica.core.utils.RsaUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
......@@ -20,9 +20,10 @@ public class CustomerMgrServiceImplTest {
@Resource
private CustomerMgrService customerMgrService;
@Test
public void register() {
public void register() throws NoSuchAlgorithmException {
String modulus = RandomUtil.randomNumbers(512);
String exponent = RandomUtil.randomNumbers(64);
PlatformCustomer customer = new PlatformCustomer();
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!