sunhuijun před 4 dny
rodič
revize
43375c75f8

+ 11 - 0
pom.xml

@@ -142,6 +142,17 @@
             <artifactId>log4j-slf4j-impl</artifactId>
             <version>${log4j2.version}</version>
         </dependency>
+        <dependency>
+            <groupId>org.bouncycastle</groupId>
+            <artifactId>bcprov-jdk15on</artifactId>
+            <version>1.70</version>  <!-- 使用最新版本 -->
+        </dependency>
+        <dependency>
+            <groupId>org.bouncycastle</groupId>
+            <artifactId>bcpkix-jdk15on</artifactId>
+            <version>1.70</version>  <!-- 使用最新版本 -->
+        </dependency>
+
     </dependencies>
 
     <build>

+ 56 - 15
src/main/java/cn/chinaunicom/omniFlowNetCompute/controller/LoginController.java

@@ -1,7 +1,11 @@
 package cn.chinaunicom.omniFlowNetCompute.controller;
 
 import cn.chinaunicom.omniFlowNetCompute.core.domain.R;
+import cn.chinaunicom.omniFlowNetCompute.domain.SysUser;
 import cn.chinaunicom.omniFlowNetCompute.dto.LoginDTO;
+import cn.chinaunicom.omniFlowNetCompute.mapper.SysUserMapper;
+import cn.chinaunicom.omniFlowNetCompute.service.RsaService;
+import cn.chinaunicom.omniFlowNetCompute.until.MD5;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.web.bind.annotation.*;
@@ -25,6 +29,10 @@ public class LoginController {
     private HttpServletResponse httpServletResponse;
 	@Resource
 	private StringRedisTemplate stringRedisTemplate;
+	@Resource
+	private RsaService rsaService;
+	@Resource
+	private SysUserMapper sysUserMapper;
 
     @PostMapping("/login")
     public R<?> login(@RequestBody LoginDTO loginDTO) {
@@ -37,23 +45,56 @@ public class LoginController {
 		}
 		//删除图形验证码
 		stringRedisTemplate.delete("app:imageCode:" + loginDTO.getCaptcha().toLowerCase());
+
+		String rsaKey = rsaService.decrypt(loginDTO.getUsername());
+		String rsaPwd = rsaService.decrypt(loginDTO.getPassword());
+		// 查询用户信息
+		// 根据用户名查询用户信息
+		SysUser sysUser = sysUserMapper.selectSysUserByAccountWithPasswd(rsaKey);
+
+		// 检查用户是否存在
+		if (sysUser == null) {
+			return R.fail(1002, "账号或密码错误");
+		}
+
+		// 验证密码是否正确(假设密码字段为password,且已加密存储)
+		try {
+			if (!MD5.verify2(rsaPwd, sysUser.getPasswd())) {
+				return R.fail(1001, "账号或密码错误");
+			}
+		} catch (Exception e) {
+			return R.fail(-1, "账号或密码错误");
+		}
+
         // 简化登录验证,直接返回成功
-        if ("admin".equals(loginDTO.getUsername()) && "Welcome1#".equals(loginDTO.getPassword())) {
-            // 模拟菜单数据
-            Map<String, Object> menus = new HashMap<>();
-            menus.put("告警情况统计分析", "/alarm/statistics");
-            menus.put("机房巡检管理", "/inspection/manage");
-            menus.put("告警数据驾驶舱", "/dashboard/alarm");
+        // if ("admin".equals(loginDTO.getUsername()) && "Welcome1#".equals(loginDTO.getPassword())) {
+        //     // 模拟菜单数据
+        //     Map<String, Object> menus = new HashMap<>();
+        //     menus.put("告警情况统计分析", "/alarm/statistics");
+        //     menus.put("机房巡检管理", "/inspection/manage");
+        //     menus.put("告警数据驾驶舱", "/dashboard/alarm");
+		//
+        //     result.put("menus", menus);
+        //     Map<String, Object> user = new HashMap<>();
+        //     user.put("username", loginDTO.getUsername());
+		// 	user.put("name", "管理员");
+        //     user.put("role", "管理员");
+        //     result.put("user", user);
+        // } else {
+        //     return R.fail(1002, "账号或密码错误");
+        // }
+		// 模拟菜单数据
+		Map<String, Object> menus = new HashMap<>();
+		menus.put("告警情况统计分析", "/alarm/statistics");
+		menus.put("机房巡检管理", "/inspection/manage");
+		menus.put("告警数据驾驶舱", "/dashboard/alarm");
 
-            result.put("menus", menus);
-            Map<String, Object> user = new HashMap<>();
-            user.put("username", loginDTO.getUsername());
-			user.put("name", "管理员");
-            user.put("role", "管理员");
-            result.put("user", user);
-        } else {
-            return R.fail(1002, "账号或密码错误");
-        }
+		result.put("menus", menus);
+		Map<String, Object> user = new HashMap<>();
+		user.put("username", rsaKey);
+		user.put("name", sysUser.getName());
+		user.put("role", "管理员");
+		result.put("user", user);
         return R.ok(result);
     }
 

+ 89 - 0
src/main/java/cn/chinaunicom/omniFlowNetCompute/domain/SysUser.java

@@ -0,0 +1,89 @@
+package cn.chinaunicom.omniFlowNetCompute.domain;
+
+import cn.chinaunicom.omniFlowNetCompute.core.web.domain.BaseEntity;
+import org.springframework.data.annotation.Transient;
+
+/**
+ * 用户对象 sys_user
+ *
+ */
+public class SysUser extends BaseEntity
+{
+    private static final long serialVersionUID = 1L;
+
+    private Long id;
+
+    private String account;
+
+    private String passwd;
+
+    private String name;
+
+    private String phonenumber;
+
+    private Integer sex;
+
+    private String status;
+
+    @Transient
+    private String userToken;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getAccount() {
+        return account;
+    }
+
+    public void setAccount(String account) {
+        this.account = account;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getPhonenumber() {
+        return phonenumber;
+    }
+
+    public void setPhonenumber(String phonenumber) {
+        this.phonenumber = phonenumber;
+    }
+
+    public Integer getSex() {
+        return sex;
+    }
+
+    public void setSex(Integer sex) {
+        this.sex = sex;
+    }
+
+    public String getPasswd() {
+        return passwd;
+    }
+
+    public void setPasswd(String passwd) {
+        this.passwd = passwd;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public String getUserToken() {
+        return userToken;
+    }
+    public void setUserToken(String userToken) {
+        this.userToken = userToken;
+    }
+}

+ 26 - 0
src/main/java/cn/chinaunicom/omniFlowNetCompute/mapper/SysUserMapper.java

@@ -0,0 +1,26 @@
+package cn.chinaunicom.omniFlowNetCompute.mapper;
+
+import cn.chinaunicom.omniFlowNetCompute.domain.SysUser;
+
+import java.util.List;
+
+/**
+ * 用户信息Mapper接口
+ *
+ */
+public interface SysUserMapper
+{
+
+    /**
+     * 查询用户信息列表
+     *
+     * @param sysUser 用户信息
+     * @return 用户信息集合
+     */
+    public List<SysUser> selectSysUserList(SysUser sysUser);
+
+
+    SysUser selectSysUserByAccount(String account);
+
+    SysUser selectSysUserByAccountWithPasswd(String account);
+}

+ 212 - 0
src/main/java/cn/chinaunicom/omniFlowNetCompute/service/RsaService.java

@@ -0,0 +1,212 @@
+package cn.chinaunicom.omniFlowNetCompute.service;
+
+import org.apache.commons.codec.binary.Base64;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.openssl.PEMDecryptorProvider;
+import org.bouncycastle.openssl.PEMEncryptedKeyPair;
+import org.bouncycastle.openssl.PEMKeyPair;
+import org.bouncycastle.openssl.PEMParser;
+import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.stereotype.Service;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.security.*;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.KeySpec;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+
+/**
+ * RSA加密相关服务
+ *
+ * @author Kitty
+ * @date 2018-04-13
+ */
+@Service
+public class RsaService {
+
+    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RsaService.class);
+
+    private PrivateKey privateKey = null;
+    private PublicKey publicKey = null;
+    private static final String PEM_FILE_NAME = "private_key.pem";
+    private static final char[] PEM_FILE_PASSWORD = "123456".toCharArray();
+
+    private PublicKey getPublicKey() {
+        if (null == this.publicKey) {
+            this.initKey();
+        }
+        return this.publicKey;
+    }
+
+    private PrivateKey getPrivateKey() {
+        if (null == this.privateKey) {
+            this.initKey();
+        }
+        return this.privateKey;
+    }
+
+    private void initKey() {
+        KeyPair keyPair = null;
+        PEMParser pemParser = null;
+        try {
+            Security.addProvider(new BouncyCastleProvider());
+            // private key file in PEM format
+            pemParser = new PEMParser(new InputStreamReader(new ClassPathResource(PEM_FILE_NAME).getInputStream(), "UTF-8"));
+            Object object = pemParser.readObject();
+            PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(PEM_FILE_PASSWORD);
+            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
+            if (object instanceof PEMEncryptedKeyPair) {
+                System.out.println("Encrypted key - we will use provided password");
+                keyPair = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decryptorProvider));
+            } else {
+                System.out.println("Unencrypted key - no password needed");
+                keyPair = converter.getKeyPair((PEMKeyPair) object);
+            }
+        } catch (IOException ex) {
+            LOGGER.error(ex.getMessage(), ex);
+        } finally {
+            if (null != pemParser) {
+                try {
+                    pemParser.close();
+                } catch (IOException ex) {
+                    LOGGER.error(ex.getMessage(), ex);
+                }
+            }
+        }
+
+        if (null != keyPair) {
+            try {
+                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+                KeySpec publicKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
+                this.publicKey = keyFactory.generatePublic(publicKeySpec);
+                KeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
+                this.privateKey = keyFactory.generatePrivate(privateKeySpec);
+            } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
+                LOGGER.error(ex.getMessage(), ex);
+            }
+        }
+    }
+
+    /**
+     * 进行签名
+     *
+     * @param data
+     * @return
+     */
+    public String sign(byte[] data) {
+        String result = null;
+        if (null != this.getPrivateKey()) {
+            Signature signature;
+            try {
+                signature = Signature.getInstance("MD5withRSA");
+                signature.initSign(this.getPrivateKey());
+                signature.update(data);
+                result = Base64.encodeBase64String(signature.sign());
+            } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
+                LOGGER.error(ex.getMessage(), ex);
+            }
+        }
+        return result;
+    }
+
+    private byte[] doFinal(Cipher cipher, byte[] source, int length) throws BadPaddingException, IllegalBlockSizeException, IOException {
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        int offset = 0;
+        while (offset < source.length) {
+            if (source.length < offset + length) {
+                length = source.length - offset;
+            }
+            outputStream.write(cipher.doFinal(source, offset, length));
+            offset += length;
+        }
+        return outputStream.toByteArray();
+    }
+
+    /**
+     * 数据加密
+     *
+     * @param data
+     * @return
+     */
+    public String encrypt(String data) {
+        String result = null;
+        try {
+            result = this.encrypt(data.getBytes("UTF-8"));
+        } catch (UnsupportedEncodingException ex) {
+            LOGGER.error(ex.getMessage(), ex);
+        }
+        return result;
+    }
+
+    /**
+     * 数据加密
+     *
+     * @param data
+     * @return
+     */
+    public String encrypt(byte[] data) {
+        String result = null;
+        if (null != this.getPublicKey()) {
+            Cipher cipher;
+            try {
+                cipher = Cipher.getInstance("RSA");
+                cipher.init(Cipher.ENCRYPT_MODE, this.getPublicKey());
+                result = Base64.encodeBase64String(this.doFinal(cipher, data, 117));
+            } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | IOException ex) {
+                LOGGER.error(ex.getMessage(), ex);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 数据解密
+     *
+     * @param data
+     * @return
+     */
+    public String decrypt(String data) {
+        return this.decrypt(Base64.decodeBase64(data));
+    }
+
+    /**
+     * 数据解密
+     *
+     * @param data
+     * @return
+     */
+    public String decrypt(byte[] data) {
+        String result = null;
+        if (null != this.getPrivateKey()) {
+            Cipher cipher;
+            try {
+                cipher = Cipher.getInstance("RSA");
+                cipher.init(Cipher.DECRYPT_MODE, this.getPrivateKey());
+                result = new String(this.doFinal(cipher, data, 128), "UTF-8");
+            } catch (BadPaddingException | IllegalBlockSizeException | IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException ex) {
+                LOGGER.error(ex.getMessage(), ex);
+            }
+        }
+        return result;
+    }
+    
+    public static void main(String[] args) {
+    	RsaService rsa = new RsaService();
+    	String encrypt = rsa.encrypt("test1");
+    	System.out.println(encrypt);
+		
+		String password = rsa.decrypt("KqPTcY4x7/jHq1otgdFiGLJGZDYH1719usXH02m5sP8E5AMEfryG3J7Lx9VVIbezgqQeGuyQzJaTCYMQD7cX8HxMmXbzElwij2hCX8GswVTeBagcVynwnckoL1ge4KBm5VfiUAnKbmiHqXHOSclneUqk3bN/Mdmfm0+haqPf2KY=");
+		System.out.println(password);
+	}
+}

+ 14 - 1
src/main/java/cn/chinaunicom/omniFlowNetCompute/until/MD5.java

@@ -32,12 +32,25 @@ public class MD5 {
 		return false;
 	}
 
+	// 根据传入的密钥进行验证
+	public static boolean verify2(String text, String md5)
+			throws Exception {
+		String md5str = md52(text);
+		if (md5str.equalsIgnoreCase(md5)) {
+			System.out.println("MD5验证通过");
+			return true;
+		}
+		return false;
+	}
+
 	// 测试
 	public static void main(String[] args) throws Exception {
 		String appId = "C0001";//appId
 		String appSecret = "";
 		String accessToken = "";
-		MD5.md52("C00011c8d8c5d86004656a1b93978a03f86c61758249019474");
+		MD5.md52("666888");
 		//System.out.println(UUID.randomUUID().toString().replace("-", ""));
+		System.out.println(verify("Welcome1#", null, "1a820c8488de239f05fb302e0bcf0d10"));
+
 	}
 }

+ 50 - 0
src/main/resources/mapper/omni/SysUserMapper.xml

@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper
+        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="cn.chinaunicom.omniFlowNetCompute.mapper.SysUserMapper">
+
+    <resultMap type="cn.chinaunicom.omniFlowNetCompute.domain.SysUser" id="SysUserResult">
+        <result property="id" column="id"/>
+        <result property="account" column="account"/>
+        <result property="passwd" column="passwd"/>
+        <result property="name" column="name"/>
+        <result property="sex" column="sex"/>
+        <result property="phonenumber" column="phonenumber"/>
+    </resultMap>
+
+    <sql id="selectSysUserVo">
+        select id,
+               name,
+               sex,
+               phonenumber
+        from sys_user
+    </sql>
+
+    <select id="selectSysUserList" parameterType="cn.chinaunicom.omniFlowNetCompute.domain.SysUser"
+            resultMap="SysUserResult">
+        <include refid="selectSysUserVo"/>
+        <where>
+            <if test="account != null  and account != ''">and account = #{account}</if>
+            <if test="name != null  and name != ''">and name like concat('%', #{name}, '%')</if>
+            <if test="sex != null ">and sex = #{sex}</if>
+            <if test="phonenumber != null  and name != ''">and phonenumber like concat('%', #{phonenumber}, '%')</if>
+        </where>
+    </select>
+
+    <select id="selectSysUserByAccount" resultMap="SysUserResult">
+        <include refid="selectSysUserVo"/>
+        where account = #{account}
+    </select>
+
+    <select id="selectSysUserByAccountWithPasswd" resultMap="SysUserResult">
+        select id,
+               name,
+               passwd,
+               sex,
+               phonenumber
+        from sys_user
+        where account = #{account}
+    </select>
+
+</mapper>

+ 15 - 0
src/main/resources/private_key.pem

@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWgIBAAKBgEmLg1maj2xOSCgFYvQjHgc/542YVz4zSPsY/ngzlQNZqPVT+zUS
+uwTqIMxn4NapspQdfRpuOVNfe8ZJep7H8zvOt78tk31CA7Uz3konemuaLc96w+Gh
+UVivH6CMavYGjWAZdHUVtfnmOiUZQEAtrGQZRluAPKCsWfpQuEQZ3XKVAgMBAAEC
+gYAbPOBYvzV/Fz8CE3yijp8AcFqBxnoJP1U4KfmU6wW1R++bbI8NCPLazxt2mMJc
+vly1HnbG4yu4BRUCSxRu2f7rMcT4U4oI74nY9wbM/6r/+O5HWZ33xKnz8PB9M3K+
+1Gvm+1FUWggpKG6hOfk7TDf7ji2hihsmOs86ngqR+xsKAQJBAJFyBXnmG+jBOAzO
+Sjw9XJYYA5iuELk0iPvpLlK9sFyQ13PoGtvnwRhmxq7QomycMphBiwad6rXdjNm9
+QowMlL0CQQCBcoHsWo8mGQ3vNRVITnGyFs5UyCyuYWdLjQljMOBWAKHiNkqUoc5Q
+W/Uw8wUkl/VczvwZzXO/lViRa5CY/C65AkB8AT7yA2LgO3zSTj+0xIxf2/GVBzNy
+9Huma9T27oujIErRo57ixuE3MMlM2szg1Pu+HIOwDIvEqzQfoOFQDpnxAkBfaz30
+MKj2h19rJbEDdLeAdCkx+8Bb5nbTDSqPUHb9TkgGTMjbGQ7Q04hAxdLTr6Pw/q58
+gqLA5WC9CRI0gygZAkAvio4NlzPhRsg4YoyWFakSshoqp3ARYqdg+RfsHZJuY1+S
+gWKUp7XWFVeoPxn/jajySSBhBU4JZo/4FMxU5p1G
+-----END RSA PRIVATE KEY-----