Browse Source

添加RSA密钥生成方式 和获取验证码时,获取公钥

DESKTOP-2K9OVK9\siwei 4 months ago
parent
commit
4b0887f476

+ 5 - 0
onemap-common/onemap-common-core/src/main/java/com/onemap/common/core/constant/CacheConstants.java

@@ -37,6 +37,11 @@ public class CacheConstants
      */
     public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
 
+    /**
+     * 权限缓存前缀
+     */
+    public final static String LOGIN_RSA_KEY = "login_rsa:";
+
     /**
      * 参数管理 cache key
      */

+ 101 - 0
onemap-common/onemap-common-core/src/main/java/com/onemap/common/core/utils/RSAUtils.java

@@ -0,0 +1,101 @@
+package com.onemap.common.core.utils;
+
+
+import org.apache.commons.codec.binary.Base64;
+
+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;
+
+public class RSAUtils {
+
+    /**
+     * 公钥解密
+     *
+     * @param publicKeyString 公钥
+     * @param text            待解密的信息
+     * @return 解密后的文本
+     */
+    public static String decryptByPublicKey(String publicKeyString, String text) throws Exception {
+        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
+        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
+        Cipher cipher = Cipher.getInstance("RSA");
+        cipher.init(Cipher.DECRYPT_MODE, publicKey);
+        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
+        return new String(result);
+    }
+
+    /**
+     * 私钥加密
+     *
+     * @param privateKeyString 私钥
+     * @param text             待加密的信息
+     * @return 加密后的文本
+     */
+    public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception {
+        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
+        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
+        Cipher cipher = Cipher.getInstance("RSA");
+        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
+        byte[] result = cipher.doFinal(text.getBytes());
+        return Base64.encodeBase64String(result);
+    }
+
+    /**
+     * 私钥解密
+     *
+     * @param privateKeyString 私钥
+     * @param text             待解密的文本
+     * @return 解密后的文本
+     */
+    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception {
+        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
+        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
+        Cipher cipher = Cipher.getInstance("RSA");
+        cipher.init(Cipher.DECRYPT_MODE, privateKey);
+        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
+        return new String(result);
+    }
+
+    /**
+     * 公钥加密
+     *
+     * @param publicKeyString 公钥
+     * @param text            待加密的文本
+     * @return 加密后的文本
+     */
+    public static String encryptByPublicKey(String publicKeyString, String text) throws Exception {
+        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
+        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);
+    }
+
+    /**
+     * 构建RSA密钥对
+     *
+     * 公钥加密,私钥解密
+     *
+     * @return 生成后的公私钥信息
+     */
+    public static String[] generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
+        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+        keyPairGenerator.initialize(2048);
+        KeyPair keyPair = keyPairGenerator.generateKeyPair();
+        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
+        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
+        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
+        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
+        return new String[]{publicKeyString, privateKeyString};
+    }
+
+}

+ 4 - 1
onemap-gateway/src/main/java/com/onemap/gateway/service/ValidateCodeService.java

@@ -1,6 +1,9 @@
 package com.onemap.gateway.service;
 
 import java.io.IOException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+
 import com.onemap.common.core.exception.CaptchaException;
 import com.onemap.common.core.web.domain.AjaxResult;
 
@@ -14,7 +17,7 @@ public interface ValidateCodeService
     /**
      * 生成验证码
      */
-    public AjaxResult createCaptcha() throws IOException, CaptchaException;
+    public AjaxResult createCaptcha() throws IOException, CaptchaException, NoSuchAlgorithmException, NoSuchProviderException;
 
     /**
      * 校验验证码

+ 23 - 24
onemap-gateway/src/main/java/com/onemap/gateway/service/impl/ValidateCodeServiceImpl.java

@@ -2,9 +2,13 @@ package com.onemap.gateway.service.impl;
 
 import java.awt.image.BufferedImage;
 import java.io.IOException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
 import java.util.concurrent.TimeUnit;
 import javax.annotation.Resource;
 import javax.imageio.ImageIO;
+
+import com.onemap.common.core.utils.RSAUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.util.FastByteArrayOutputStream;
@@ -26,8 +30,7 @@ import com.onemap.gateway.service.ValidateCodeService;
  * @author onemap
  */
 @Service
-public class ValidateCodeServiceImpl implements ValidateCodeService
-{
+public class ValidateCodeServiceImpl implements ValidateCodeService {
     @Resource(name = "captchaProducer")
     private Producer captchaProducer;
 
@@ -44,16 +47,17 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
      * 生成验证码
      */
     @Override
-    public AjaxResult createCaptcha() throws IOException, CaptchaException
-    {
+    public AjaxResult createCaptcha() throws IOException, CaptchaException, NoSuchAlgorithmException, NoSuchProviderException {
         AjaxResult ajax = AjaxResult.success();
         boolean captchaEnabled = captchaProperties.getEnabled();
         ajax.put("captchaEnabled", captchaEnabled);
-        if (!captchaEnabled)
-        {
+        if (!captchaEnabled) {
             return ajax;
         }
 
+        //生成公私钥
+        String[] keyPair = RSAUtils.generateKeyPair();
+
         // 保存验证码信息
         String uuid = IdUtils.simpleUUID();
         String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
@@ -63,15 +67,12 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
 
         String captchaType = captchaProperties.getType();
         // 生成验证码
-        if ("math".equals(captchaType))
-        {
+        if ("math".equals(captchaType)) {
             String capText = captchaProducerMath.createText();
             capStr = capText.substring(0, capText.lastIndexOf("@"));
             code = capText.substring(capText.lastIndexOf("@") + 1);
             image = captchaProducerMath.createImage(capStr);
-        }
-        else if ("char".equals(captchaType))
-        {
+        } else if ("char".equals(captchaType)) {
             capStr = code = captchaProducer.createText();
             image = captchaProducer.createImage(capStr);
         }
@@ -79,17 +80,19 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
         redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
         // 转换流信息写出
         FastByteArrayOutputStream os = new FastByteArrayOutputStream();
-        try
-        {
+        try {
             ImageIO.write(image, "jpg", os);
-        }
-        catch (IOException e)
-        {
+        } catch (IOException e) {
             return AjaxResult.error(e.getMessage());
         }
 
         ajax.put("uuid", uuid);
         ajax.put("img", Base64.encode(os.toByteArray()));
+        //返回公钥信息
+        ajax.put("publicKeyString", keyPair[0]);
+        // 保存私钥信息
+        String keyPairKey = CacheConstants.LOGIN_RSA_KEY + uuid;
+        redisService.setCacheObject(keyPairKey,  keyPair[1], Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
         return ajax;
     }
 
@@ -97,22 +100,18 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
      * 校验验证码
      */
     @Override
-    public void checkCaptcha(String code, String uuid) throws CaptchaException
-    {
-        if (StringUtils.isEmpty(code))
-        {
+    public void checkCaptcha(String code, String uuid) throws CaptchaException {
+        if (StringUtils.isEmpty(code)) {
             throw new CaptchaException("验证码不能为空");
         }
-        if (StringUtils.isEmpty(uuid))
-        {
+        if (StringUtils.isEmpty(uuid)) {
             throw new CaptchaException("验证码已失效");
         }
         String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
         String captcha = redisService.getCacheObject(verifyKey);
         redisService.deleteObject(verifyKey);
 
-        if (!code.equalsIgnoreCase(captcha))
-        {
+        if (!code.equalsIgnoreCase(captcha)) {
             throw new CaptchaException("验证码错误");
         }
     }