Browse Source

'1.用户密码增加RSA加密2.增加解决组织中两个中文同名登入问题3.createencryptkey错误修改'

o2wwx 5 years ago
parent
commit
b8aa5787cc

+ 463 - 0
o2server/x_base_core_project/src/main/java/com/x/base/core/project/tools/RSAUtils.java

@@ -0,0 +1,463 @@
+package com.x.base.core.project.tools;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyFactory;
+import java.security.KeyPairGenerator;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.NoSuchAlgorithmException;
+import java.security.InvalidParameterException;
+import java.security.interfaces.RSAPublicKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.spec.RSAPublicKeySpec;
+import java.security.spec.RSAPrivateKeySpec;
+import java.security.spec.InvalidKeySpecException;
+import java.util.Date;
+ 
+import javax.crypto.Cipher;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.time.DateFormatUtils;
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.binary.Hex;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+ 
+
+ 
+/**
+ * RSA算法加密/解密工具类。
+ * 公钥和私钥保存在__RSA_PAIR.txt文件中,如果此文件不存在就会生成公钥和私钥保存在RSA_PAIR.txt文件中并缓存
+ * __RSA_PAIR.txt文件存在时公钥和私钥是不变的
+ * RSA速度  :
+ * 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。  
+ * 速度一直是RSA的缺陷。一般来说只用于少量数据 加密。
+ * 当你需要更改公钥和私钥时,请删除__RSA_PAIR.txt,以及修改generateKeyPair()方法中的
+ * new SecureRandom()构造数字生成器
+ */
+public abstract class RSAUtils {
+ 
+    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
+ 
+    /** 算法名称 */
+    private static final String ALGORITHOM = "RSA";
+    /**保存生成的密钥对的文件名称。 */
+    private static final String RSA_PAIR_FILENAME = "/RSA_PAIR.txt";
+    /** 密钥大小 */
+    private static final int KEY_SIZE = 1024;
+    /** 默认的安全服务提供者 */
+    private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
+ 
+    private static KeyPairGenerator keyPairGen = null;
+    private static KeyFactory keyFactory = null;
+    /** 缓存的密钥对。 */
+    private static KeyPair oneKeyPair = null;
+ 
+    private static File rsaPairFile = null;
+ 
+    static {
+        try {
+            keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
+            keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
+        } catch (NoSuchAlgorithmException ex) {
+            LOGGER.error(ex.getMessage());
+        }
+        rsaPairFile = new File(getRSAPairFilePath());
+    }
+ 
+    private RSAUtils() {
+    }
+ 
+    /**
+     * 生成并返回RSA密钥对。
+     */
+    private static synchronized KeyPair generateKeyPair() {
+        try {
+        	//KEY_SIZE表示KEY_SIZE,new SecureRandom()表示构造随机数字生成器,当这个生成器不变时,所形成的公钥和私钥是不变的。
+            keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(),"yyyyMMdd").getBytes()));
+        	//keyPairGen.initialize(KEY_SIZE, new SecureRandom("r0o5wyt4s70g".getBytes()));
+            oneKeyPair = keyPairGen.generateKeyPair();
+            saveKeyPair(oneKeyPair);
+            return oneKeyPair;
+        } catch (InvalidParameterException ex) {
+            LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
+        } catch (NullPointerException ex) {
+            LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.",
+                    ex);
+        }
+        return null;
+    }
+ 
+    /**
+     * 返回生成/读取的密钥对文件的路径。
+     */
+    private static String getRSAPairFilePath() {
+    	//E:/apache-tomcat-8.0.22/wtpwebapps/rsaDemo/WEB-INF/classes/
+        String urlPath = RSAUtils.class.getResource("/").getPath();
+        //getParent()到父目录:E:/apache-tomcat-8.0.22/wtpwebapps/rsaDemo/WEB-INF/
+        System.out.println(new File(urlPath).getParent() + RSA_PAIR_FILENAME);
+        return (new File(urlPath).getParent() + RSA_PAIR_FILENAME);
+       // return (urlPath+ RSA_PAIR_FILENAME);
+    }
+ 
+    /**
+     * 若需要创建新的密钥对文件,则返回 {@code true},否则 {@code false}。
+     */
+    private static boolean isCreateKeyPairFile() {
+        // 是否创建新的密钥对文件
+        boolean createNewKeyPair = false;
+        if (!rsaPairFile.exists() || rsaPairFile.isDirectory()) {
+            createNewKeyPair = true;
+        }
+        return createNewKeyPair;
+    }
+ 
+    /**
+     * 将指定的RSA密钥对以文件形式保存。
+     * 
+     * @param keyPair 要保存的密钥对。
+     */
+    private static void saveKeyPair(KeyPair keyPair) {
+        FileOutputStream fos = null;
+        ObjectOutputStream oos = null;
+        try {
+            fos = FileUtils.openOutputStream(rsaPairFile);
+            oos = new ObjectOutputStream(fos);
+            oos.writeObject(keyPair);
+        } catch (Exception ex) {
+            ex.printStackTrace();
+        } finally {
+            IOUtils.closeQuietly(oos);
+            IOUtils.closeQuietly(fos);
+        }
+    }
+ 
+    /**
+     * 返回RSA密钥对。
+     */
+    public static KeyPair getKeyPair() {
+        // 首先判断是否需要重新生成新的密钥对文件
+        if (isCreateKeyPairFile()) {
+            // 直接强制生成密钥对文件,并存入缓存。
+            return generateKeyPair();
+        }
+        if (oneKeyPair != null) {
+            return oneKeyPair;
+        }
+        return readKeyPair();
+    }
+     
+    // 同步读出保存的密钥对
+    private static KeyPair readKeyPair() {
+        FileInputStream fis = null;
+        ObjectInputStream ois = null;
+        try {
+            fis = FileUtils.openInputStream(rsaPairFile);
+            ois = new ObjectInputStream(fis);
+            oneKeyPair = (KeyPair) ois.readObject();
+            return oneKeyPair;
+        } catch (Exception ex) {
+            ex.printStackTrace();
+        } finally {
+            IOUtils.closeQuietly(ois);
+            IOUtils.closeQuietly(fis);
+        }
+        return null;
+    }
+ 
+    /**
+     * 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
+     * 
+     * @param modulus 系数。
+     * @param publicExponent 专用指数。
+     * @return RSA专用公钥对象。
+     */
+    public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
+        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus),
+                new BigInteger(publicExponent));
+        try {
+            return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
+        } catch (InvalidKeySpecException ex) {
+            LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
+        } catch (NullPointerException ex) {
+            LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
+        }
+        return null;
+    }
+ 
+    /**
+     * 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
+     * 
+     * @param modulus 系数。
+     * @param privateExponent 专用指数。
+     * @return RSA专用私钥对象。
+     */
+    public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
+        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus),
+                new BigInteger(privateExponent));
+        try {
+            return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
+        } catch (InvalidKeySpecException ex) {
+            LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
+        } catch (NullPointerException ex) {
+            LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
+        }
+        return null;
+    }
+     
+    /**
+     * 根据给定的16进制系数和专用指数字符串构造一个RSA专用的私钥对象。
+     * 
+     * @param modulus 系数。
+     * @param privateExponent 专用指数。
+     * @return RSA专用私钥对象。
+     */
+    public static RSAPrivateKey getRSAPrivateKey(String hexModulus, String hexPrivateExponent) {
+        if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPrivateExponent)) {
+            if(LOGGER.isDebugEnabled()) {
+                LOGGER.debug("hexModulus and hexPrivateExponent cannot be empty. RSAPrivateKey value is null to return.");
+            }
+            return null;
+        }
+        byte[] modulus = null;
+        byte[] privateExponent = null;
+        try {
+            modulus = Hex.decodeHex(hexModulus.toCharArray());
+            privateExponent = Hex.decodeHex(hexPrivateExponent.toCharArray());
+        } catch(DecoderException ex) {
+            LOGGER.error("hexModulus or hexPrivateExponent value is invalid. return null(RSAPrivateKey).");
+        }
+        if(modulus != null && privateExponent != null) {
+            return generateRSAPrivateKey(modulus, privateExponent);
+        }
+        return null;
+    }
+     
+    /**
+     * 根据给定的16进制系数和专用指数字符串构造一个RSA专用的公钥对象。
+     * 
+     * @param modulus 系数。
+     * @param publicExponent 专用指数。
+     * @return RSA专用公钥对象。
+     */
+    public static RSAPublicKey getRSAPublidKey(String hexModulus, String hexPublicExponent) {
+        if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPublicExponent)) {
+            if(LOGGER.isDebugEnabled()) {
+                LOGGER.debug("hexModulus and hexPublicExponent cannot be empty. return null(RSAPublicKey).");
+            }
+            return null;
+        }
+        byte[] modulus = null;
+        byte[] publicExponent = null;
+        try {
+            modulus = Hex.decodeHex(hexModulus.toCharArray());
+            publicExponent = Hex.decodeHex(hexPublicExponent.toCharArray());
+        } catch(DecoderException ex) {
+            LOGGER.error("hexModulus or hexPublicExponent value is invalid. return null(RSAPublicKey).");
+        }
+        if(modulus != null && publicExponent != null) {
+            return generateRSAPublicKey(modulus, publicExponent);
+        }
+        return null;
+    }
+ 
+    /**
+     * 使用指定的公钥加密数据。
+     * 
+     * @param publicKey 给定的公钥。
+     * @param data 要加密的数据。
+     * @return 加密后的数据。
+     */
+    public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
+        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
+        ci.init(Cipher.ENCRYPT_MODE, publicKey);
+        return ci.doFinal(data);
+    }
+ 
+    /**
+     * 使用指定的私钥解密数据。
+     * 
+     * @param privateKey 给定的私钥。
+     * @param data 要解密的数据。
+     * @return 原数据。
+     */
+    public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
+        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
+        ci.init(Cipher.DECRYPT_MODE, privateKey);
+        return ci.doFinal(data);
+    }
+ 
+    /**
+     * 使用给定的公钥加密给定的字符串。
+     * <p />
+     * 若 {@code publicKey} 为 {@code null},或者 {@code plaintext} 为 {@code null} 则返回 {@code
+     * null}。
+     * 
+     * @param publicKey 给定的公钥。
+     * @param plaintext 字符串。
+     * @return 给定字符串的密文。
+     */
+    public static String encryptString(PublicKey publicKey, String plaintext) {
+        if (publicKey == null || plaintext == null) {
+            return null;
+        }
+        byte[] data = plaintext.getBytes();
+        try {
+            byte[] en_data = encrypt(publicKey, data);
+            return new String(Hex.encodeHex(en_data));
+        } catch (Exception ex) {
+            LOGGER.error(ex.getCause().getMessage());
+        }
+        return null;
+    }
+     
+    /**
+     * 使用默认的公钥加密给定的字符串。
+     * <p />
+     * 若{@code plaintext} 为 {@code null} 则返回 {@code null}。
+     * 
+     * @param plaintext 字符串。
+     * @return 给定字符串的密文。
+     */
+    public static String encryptString(String plaintext) {
+        if(plaintext == null) {
+            return null;
+        }
+        byte[] data = plaintext.getBytes();
+        KeyPair keyPair = getKeyPair();
+        try {
+            byte[] en_data = encrypt((RSAPublicKey)keyPair.getPublic(), data);
+            return new String(Hex.encodeHex(en_data));
+        } catch(NullPointerException ex) {
+            LOGGER.error("keyPair cannot be null.");
+        } catch(Exception ex) {
+            LOGGER.error(ex.getCause().getMessage());
+        }
+        return null;
+    }
+ 
+    /**
+     * 使用给定的私钥解密给定的字符串。
+     * <p />
+     * 若私钥为 {@code null},或者 {@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
+     * 私钥不匹配时,返回 {@code null}。
+     * 
+     * @param privateKey 给定的私钥。
+     * @param encrypttext 密文。
+     * @return 原文字符串。
+     */
+    public static String decryptString(PrivateKey privateKey, String encrypttext) {
+        if (privateKey == null || StringUtils.isBlank(encrypttext)) {
+            return null;
+        }
+        try {
+            byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
+            byte[] data = decrypt(privateKey, en_data);
+            return new String(data);
+        } catch (Exception ex) {
+            LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getCause().getMessage()));
+        }
+        return null;
+    }
+     
+    /**
+     * 使用默认的私钥解密给定的字符串。
+     * <p />
+     * 若{@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
+     * 私钥不匹配时,返回 {@code null}。
+     * 
+     * @param encrypttext 密文。
+     * @return 原文字符串。
+     */
+    public static String decryptString(String encrypttext) {
+        if(StringUtils.isBlank(encrypttext)) {
+            return null;
+        }
+        KeyPair keyPair = getKeyPair();
+        try {
+            byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
+            byte[] data = decrypt((RSAPrivateKey)keyPair.getPrivate(), en_data);
+            return new String(data);
+        } catch(NullPointerException ex) {
+            LOGGER.error("keyPair cannot be null.");
+        } catch (Exception ex) {
+            LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getMessage()));
+        }
+        return null;
+    }
+     
+    /**
+     * 使用默认的私钥解密由JS加密(使用此类提供的公钥加密)的字符串。
+     * 
+     * @param encrypttext 密文。
+     * @return {@code encrypttext} 的原文字符串。
+     */
+    public static String decryptStringByJs(String encrypttext) {
+        String text = decryptString(encrypttext);
+        if(text == null) {
+            return null;
+        }
+        return StringUtils.reverse(text);//字符串倒转
+    }
+     
+    /** 返回已初始化的默认的公钥。*/
+    public static RSAPublicKey getDefaultPublicKey() {
+        KeyPair keyPair = getKeyPair();
+        if(keyPair != null) {
+            return (RSAPublicKey)keyPair.getPublic();
+        }
+        return null;
+    }
+     
+    /** 返回已初始化的默认的私钥。*/
+    public static RSAPrivateKey getDefaultPrivateKey() {
+        KeyPair keyPair = getKeyPair();
+        if(keyPair != null) {
+            return (RSAPrivateKey)keyPair.getPrivate();
+        }
+        return null;
+    }
+     
+    public static PublicKeyMap getPublicKeyMap() {
+        PublicKeyMap publicKeyMap = new PublicKeyMap();
+        RSAPublicKey rsaPublicKey = getDefaultPublicKey();
+        publicKeyMap.setModulus(new String(Hex.encodeHex(rsaPublicKey.getModulus().toByteArray())));//系数
+        publicKeyMap.setExponent(new String(Hex.encodeHex(rsaPublicKey.getPublicExponent().toByteArray())));//指数
+        return publicKeyMap;
+    }
+    
+    public static class PublicKeyMap{
+    	
+    	 private String modulus;
+    	 private String exponent;
+    	 
+    	 public String getModulus() {
+    	  return modulus;
+    	 }
+    	 public void setModulus(String modulus) {
+    	  this.modulus = modulus;
+    	 }
+    	 public String getExponent() {
+    	  return exponent;
+    	 }
+    	 public void setExponent(String exponent) {
+    	  this.exponent = exponent;
+    	 }
+    	 @Override
+    	 public String toString() {
+    	  return "PublicKeyMap [modulus=" + modulus + ", exponent=" + exponent
+    	    + "]";
+    	 }
+     }
+}
+

+ 4 - 2
o2server/x_console/src/main/java/com/x/server/console/CommandFactory.java

@@ -17,9 +17,11 @@ public class CommandFactory {
 
 
 	public static final Pattern test_pattern = Pattern.compile("^ {0,}test {0,}$", Pattern.CASE_INSENSITIVE);
 	public static final Pattern test_pattern = Pattern.compile("^ {0,}test {0,}$", Pattern.CASE_INSENSITIVE);
 
 
-	public static final Pattern create_encrypt_key_pattern = Pattern.compile("^ {0,}create encrypt key {0,}$",
+	//public static final Pattern create_encrypt_key_pattern = Pattern.compile("^ {0,}create encrypt key {0,}$",Pattern.CASE_INSENSITIVE);
+	
+	public static final Pattern create_encrypt_key_pattern = Pattern.compile("^ {0,}create encrypt key (.+)$",
 			Pattern.CASE_INSENSITIVE);
 			Pattern.CASE_INSENSITIVE);
-
+	
 	public static final Pattern start_pattern = Pattern
 	public static final Pattern start_pattern = Pattern
 			.compile("^ {0,}start {0,}(data|storage|center|application|web|all|) {0,}$", Pattern.CASE_INSENSITIVE);
 			.compile("^ {0,}start {0,}(data|storage|center|application|web|all|) {0,}$", Pattern.CASE_INSENSITIVE);
 
 

+ 46 - 1
o2server/x_console/src/main/java/com/x/server/console/action/ActionCreateEncryptKey.java

@@ -1,6 +1,11 @@
 package com.x.server.console.action;
 package com.x.server.console.action;
 
 
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
 import java.security.KeyPair;
 import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.KeyPairGenerator;
 import java.util.Date;
 import java.util.Date;
@@ -9,6 +14,8 @@ import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.StringUtils;
 
 
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
 import com.x.base.core.project.config.Config;
 import com.x.base.core.project.config.Config;
 import com.x.base.core.project.logger.Logger;
 import com.x.base.core.project.logger.Logger;
 import com.x.base.core.project.logger.LoggerFactory;
 import com.x.base.core.project.logger.LoggerFactory;
@@ -37,10 +44,48 @@ public class ActionCreateEncryptKey extends ActionBase {
 		File privateKeyFile = new File(Config.base(), "config/private.key");
 		File privateKeyFile = new File(Config.base(), "config/private.key");
 		FileUtils.write(publicKeyFile, Base64.encodeBase64URLSafeString(pair.getPublic().getEncoded()),
 		FileUtils.write(publicKeyFile, Base64.encodeBase64URLSafeString(pair.getPublic().getEncoded()),
 				DefaultCharset.charset, false);
 				DefaultCharset.charset, false);
+		
 		FileUtils.write(privateKeyFile, Base64.encodeBase64URLSafeString(pair.getPrivate().getEncoded()),
 		FileUtils.write(privateKeyFile, Base64.encodeBase64URLSafeString(pair.getPrivate().getEncoded()),
 				DefaultCharset.charset, false);
 				DefaultCharset.charset, false);
-		System.out.println("public key: config/public.key, private key: config/private.key, create key success!");
+		
+		//为前端提供publicKey,为密码加密
+		this.writeConfigFile(new String(Base64.encodeBase64(pair.getPublic().getEncoded())));
+		
 		return true;
 		return true;
 	}
 	}
+	
+	public static void main(String[] args) throws Exception {
+		ActionCreateEncryptKey actionCreateEncryptKey = new ActionCreateEncryptKey();
+		actionCreateEncryptKey.writeConfigFile("ssxx");
+	}
+
+	public  boolean writeConfigFile(String publicKey) {
+	    File dir;
+		StringBuffer stringBuffer = new StringBuffer();
+		try {
+			dir = new File(Config.base(), "servers/webServer/x_desktop/res/config");
+			FileUtils.forceMkdir(dir);
+			File fileConfig = new File(dir, "config.json");
+			
+			BufferedReader bufferedReader = 
+					new BufferedReader(new InputStreamReader(new FileInputStream(fileConfig), "UTF-8"));
+			String line;
+			while((line=bufferedReader.readLine()) != null) {
+				stringBuffer.append(line);
+			}
+			
+			JsonObject jsonObject = (JsonObject) new JsonParser().parse(stringBuffer.toString());
+			jsonObject.addProperty("publicKey", publicKey);
 
 
+			 FileUtils.write(fileConfig, jsonObject.toString(),DefaultCharset.charset, false);
+					
+		} catch (FileNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	   return true;
+  }
 }
 }

+ 11 - 1
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/factory/PersonFactory.java

@@ -123,7 +123,17 @@ public class PersonFactory extends AbstractFactory {
 		List<String> list = em.createQuery(cq.where(p).distinct(true)).getResultList();
 		List<String> list = em.createQuery(cq.where(p).distinct(true)).getResultList();
 		if (list.size() == 1) {
 		if (list.size() == 1) {
 			return list.get(0);
 			return list.get(0);
-		} else {
+		}else if(list.size() > 1){
+			String temp = "";
+			for (int i = 0; i < list.size(); i++) {
+				if(temp.equalsIgnoreCase("")) {
+					temp = list.get(i);
+				}else{
+					temp = temp + "," + list.get(i);
+				}
+			}
+		    return temp;
+		}else {
 			return null;
 			return null;
 		}
 		}
 	}
 	}

+ 96 - 2
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/authentication/ActionCaptchaLogin.java

@@ -3,6 +3,7 @@ package com.x.organization.assemble.authentication.jaxrs.authentication;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpServletResponse;
 
 
+import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.lang3.BooleanUtils;
 import org.apache.commons.lang3.BooleanUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.StringUtils;
 
 
@@ -35,6 +36,16 @@ class ActionCaptchaLogin extends BaseAction {
 			Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
 			Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
 			String credential = wi.getCredential();
 			String credential = wi.getCredential();
 			String password = wi.getPassword();
 			String password = wi.getPassword();
+			
+			String isEncrypted = wi.getIsEncrypted();
+			
+			//RSA解秘
+			if (!StringUtils.isEmpty(isEncrypted)) {
+				if(isEncrypted.trim().equalsIgnoreCase("y")) {
+			    	password = decryptRSA(password);
+				}
+			}
+			
 			String captcha = wi.getCaptcha();
 			String captcha = wi.getCaptcha();
 			String captchaAnswer = wi.getCaptchaAnswer();
 			String captchaAnswer = wi.getCaptchaAnswer();
 			if (StringUtils.isEmpty(credential)) {
 			if (StringUtils.isEmpty(credential)) {
@@ -58,12 +69,27 @@ class ActionCaptchaLogin extends BaseAction {
 				}
 				}
 				wo = this.manager(request, response, business, Wo.class);
 				wo = this.manager(request, response, business, Wo.class);
 			} else {
 			} else {
-				/* 普通用户登录,也有可能拥有管理员角色 */
+				/* 普通用户登录,也有可能拥有管理员角色.增加同中文的认证 */
 				String personId = business.person().getWithCredential(credential);
 				String personId = business.person().getWithCredential(credential);
 				if (StringUtils.isEmpty(personId)) {
 				if (StringUtils.isEmpty(personId)) {
 					throw new ExceptionPersonNotExistOrInvalidPassword();
 					throw new ExceptionPersonNotExistOrInvalidPassword();
 				}
 				}
-				Person o = emc.find(personId, Person.class);
+				
+				Person o = null;
+				//处理同中文问题
+				if(personId.indexOf(",") > -1) {
+					String[] arrPersion = personId.split(",");
+					for(int i =0 ; i<arrPersion.length ; i++) {
+						 personId = arrPersion[i];
+						 o = emc.find(personId, Person.class);
+						 if (StringUtils.equals(Crypto.encrypt(password, Config.token().getKey()), o.getPassword())) {
+							 break;
+						 }
+					}
+				}else {
+					 o = emc.find(personId, Person.class);
+				}
+
 				if (BooleanUtils.isTrue(Config.person().getSuperPermission())
 				if (BooleanUtils.isTrue(Config.person().getSuperPermission())
 						&& StringUtils.equals(Config.token().getPassword(), password)) {
 						&& StringUtils.equals(Config.token().getPassword(), password)) {
 					logger.warn("user: {} use superPermission.", credential);
 					logger.warn("user: {} use superPermission.", credential);
@@ -79,6 +105,8 @@ class ActionCaptchaLogin extends BaseAction {
 						}
 						}
 					}
 					}
 				}
 				}
+				
+				
 				wo = this.user(request, response, business, o, Wo.class);
 				wo = this.user(request, response, business, o, Wo.class);
 				audit.log(o.getDistinguishedName(), "登录");
 				audit.log(o.getDistinguishedName(), "登录");
 			}
 			}
@@ -87,6 +115,63 @@ class ActionCaptchaLogin extends BaseAction {
 		}
 		}
 	}
 	}
 
 
+	 //加密
+		public String encryptRSA(String strEncrypt) {
+			String encrypt = null;
+			try {
+				 String publicKey = Config.publicKey();
+				 byte[] publicKeyB = Base64.decodeBase64(publicKey);
+				 
+				encrypt = Crypto.rsaEncrypt(strEncrypt,new String(Base64.encodeBase64(publicKeyB)));
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		
+			return encrypt;
+		}
+		
+		//解密
+		public String decryptRSA(String strDecrypt) {
+			String privateKey;
+			String decrypt = null;
+			try {
+				privateKey = getPrivateKey();
+			    decrypt = Crypto.rsaDecrypt(strDecrypt, privateKey);
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		
+			return decrypt;
+		}
+		
+		//获取PublicKey
+		public String  getPublicKey() {
+			String publicKey = "";
+			 try {
+				 publicKey = Config.publicKey();
+				 byte[] publicKeyB = Base64.decodeBase64(publicKey);
+				 publicKey = new String(Base64.encodeBase64(publicKeyB));
+				 
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return publicKey;
+		}
+		
+		
+		//获取privateKey
+		public String  getPrivateKey() {
+			 String privateKey = "";
+			 try {
+				 privateKey = Config.privateKey();
+				 byte[] privateKeyB = Base64.decodeBase64(privateKey);
+				 privateKey = new String(Base64.encodeBase64(privateKeyB));
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return privateKey;
+		}
+		
 	public static class Wi extends GsonPropertyObject {
 	public static class Wi extends GsonPropertyObject {
 
 
 		@FieldDescribe("凭证")
 		@FieldDescribe("凭证")
@@ -101,6 +186,9 @@ class ActionCaptchaLogin extends BaseAction {
 		@FieldDescribe("图片认证码")
 		@FieldDescribe("图片认证码")
 		private String captchaAnswer;
 		private String captchaAnswer;
 
 
+		@FieldDescribe("是否启用加密,默认不加密,启用(y)。注意:使用加密先要在服务器运行 create encrypt key")
+		private String isEncrypted;
+		
 		public String getPassword() {
 		public String getPassword() {
 			return password;
 			return password;
 		}
 		}
@@ -132,7 +220,13 @@ class ActionCaptchaLogin extends BaseAction {
 		public void setCaptchaAnswer(String captchaAnswer) {
 		public void setCaptchaAnswer(String captchaAnswer) {
 			this.captchaAnswer = captchaAnswer;
 			this.captchaAnswer = captchaAnswer;
 		}
 		}
+		public String getIsEncrypted() {
+			return isEncrypted;
+		}
 
 
+		public void setIsEncrypted(String isEncrypted) {
+			this.isEncrypted = isEncrypted;
+		}
 	}
 	}
 
 
 	public static class Wo extends AbstractWoAuthentication {
 	public static class Wo extends AbstractWoAuthentication {

+ 71 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/authentication/ActionCaptchaLoginRSAPublicKey.java

@@ -0,0 +1,71 @@
+package com.x.organization.assemble.authentication.jaxrs.authentication;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.codec.binary.Base64;
+import com.x.base.core.project.annotation.FieldDescribe;
+import com.x.base.core.project.config.Config;
+import com.x.base.core.project.gson.GsonPropertyObject;
+import com.x.base.core.project.http.ActionResult;
+import com.x.base.core.project.http.EffectivePerson;
+import com.x.base.core.project.logger.Logger;
+import com.x.base.core.project.logger.LoggerFactory;
+
+
+public class ActionCaptchaLoginRSAPublicKey extends BaseAction{
+	private static Logger logger = LoggerFactory.getLogger(ActionCaptchaLoginRSAPublicKey.class);
+
+	ActionResult<Wo> execute(HttpServletRequest request, HttpServletResponse response, EffectivePerson effectivePerson) throws Exception {
+			ActionResult<Wo> result = new ActionResult<>();
+			Wo wo = new Wo();
+			wo.setPublicKey(getPublicKey());
+			result.setData(wo);
+			return result;
+		}
+
+	//获取PublicKey
+	public String  getPublicKey() {
+		String publicKey = "";
+		 try {
+			 publicKey = Config.publicKey();
+			 byte[] publicKeyB = Base64.decodeBase64(publicKey);
+			 publicKey = new String(Base64.encodeBase64(publicKeyB));
+			 //logger.info("publicKey=" + publicKey);
+			 
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return publicKey;
+	}
+	
+	
+	//获取privateKey
+	public String  getPrivateKey() {
+		 String privateKey = "";
+		 try {
+			 privateKey = Config.privateKey();
+			 byte[] privateKeyB = Base64.decodeBase64(privateKey);
+			 privateKey = new String(Base64.encodeBase64(privateKeyB));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return privateKey;
+	}
+	
+
+	public static class Wo  extends GsonPropertyObject {
+
+		@FieldDescribe("RSA公钥")
+		private String publicKey;
+
+		public String getPublicKey() {
+			return publicKey;
+		}
+
+		public void setPublicKey(String publicKey) {
+			this.publicKey = publicKey;
+		}
+	}
+
+}

+ 20 - 1
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/authentication/AuthenticationAction.java

@@ -140,7 +140,7 @@ public class AuthenticationAction extends StandardJaxrsAction {
 		}
 		}
 		asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
 		asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
 	}
 	}
-
+	
 	@JaxrsMethodDescribe(value = "获取图片验证码.", action = ActionCaptcha.class)
 	@JaxrsMethodDescribe(value = "获取图片验证码.", action = ActionCaptcha.class)
 	@GET
 	@GET
 	@Path("captcha/width/{width}/height/{height}")
 	@Path("captcha/width/{width}/height/{height}")
@@ -160,6 +160,25 @@ public class AuthenticationAction extends StandardJaxrsAction {
 		asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
 		asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
 	}
 	}
 
 
+
+	@JaxrsMethodDescribe(value = "获取公钥publicKey", action = ActionCaptchaLoginRSAPublicKey.class)
+	@GET
+	@Path("captchaRSAPublicKey")
+	@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
+	@Consumes(MediaType.APPLICATION_JSON)
+	public void captchaRSAPublicKey(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
+			@Context HttpServletResponse response) {
+		ActionResult<ActionCaptchaLoginRSAPublicKey.Wo> result = new ActionResult<>();
+		EffectivePerson effectivePerson = this.effectivePerson(request);
+		try {
+			result = new ActionCaptchaLoginRSAPublicKey().execute(request, response, effectivePerson);
+		} catch (Exception e) {
+			logger.error(e, effectivePerson, request, null);
+			result.error(e);
+		}
+		asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
+	}
+	
 	@JaxrsMethodDescribe(value = "用户登录.credential=xxxx,codeAnswer=xxxx,使用短信验证码登录.", action = ActionCodeLogin.class)
 	@JaxrsMethodDescribe(value = "用户登录.credential=xxxx,codeAnswer=xxxx,使用短信验证码登录.", action = ActionCodeLogin.class)
 	@POST
 	@POST
 	@Path("code")
 	@Path("code")