提交 a30f7eca 编写于 作者: O o2null

Merge branch 'feature/java11' into 'develop'

encrypt password

See merge request o2oa/o2oa!1635
......@@ -276,22 +276,4 @@ public class ScriptFactory {
return list;
}
public static Object evalIfScriptText(String text) throws ScriptException {
if (StringUtils.isEmpty(text)) {
return text;
}
Matcher matcher = StringTools.SCRIPTTEXT_REGEX.matcher(text);
if (matcher.matches()) {
String eval = functionalization(StringEscapeUtils.unescapeJson(matcher.group(1)));
ScriptContext scriptContext = new SimpleScriptContext();
return ScriptFactory.scriptEngine.eval(eval, scriptContext);
} else {
return text;
}
}
public static String evalIfScriptTextAsString(String text) throws Exception {
return asString(evalIfScriptText(text));
}
}
\ No newline at end of file
......@@ -4,33 +4,43 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Objects;
import java.util.regex.Matcher;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import com.x.base.core.project.script.ScriptFactory;
public class Crypto {
private static final String utf8 = "UTF-8";
private final static String DES = "DES";
//private final static String CIPHER_INIT = "DES";
private final static String RSA = "RSA";
private static final String DES = "DES";
//private final static SecureRandom sr = new SecureRandom();
private static final String RSA = "RSA";
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
......@@ -53,7 +63,7 @@ public class Crypto {
return cipher.doFinal(data);
}
public static String decrypt(String data, String key) throws IOException, Exception {
public static String decrypt(String data, String key) throws Exception {
if (StringUtils.isEmpty(data)) {
return null;
}
......@@ -119,4 +129,76 @@ public class Crypto {
public static final String TEST_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWcVZIS57VeOUzi8c01WKvwJK9uRe6hrGTUYmF6J/pI6/UvCbdBWCoErbzsBZOElOH8Sqal3vsNMVLjPYClfoDyYDaUlakP3ldfnXJzAFJVVubF53KadG+fwnh9ZMvxdh7VXVqRL3IQBDwGgzX4rmSK+qkUJjc3OkrNJPB7LLD8QIDAQAB";
public static final String TEST_PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJZxVkhLntV45TOLxzTVYq/Akr25F7qGsZNRiYXon+kjr9S8Jt0FYKgStvOwFk4SU4fxKpqXe+w0xUuM9gKV+gPJgNpSVqQ/eV1+dcnMAUlVW5sXncpp0b5/CeH1ky/F2HtVdWpEvchAEPAaDNfiuZIr6qRQmNzc6Ss0k8HsssPxAgMBAAECgYAWtRy05NUgm5Lc6Og0jVDL/mEnydxPBy2ectwzHh2k7wIHNi8XhUxFki2TMqzrM9Dv3/LySpMl4AE3mhs34LNPy6F+MwyF5X7j+2Y6MflJyeb9HNyT++viysQneoOEiOk3ghxF2/GPjpiEF79wSp+1YKTxRAyq7ypV3t35fGOOEQJBANLDPWl8b5c3lrcz/dTamMjHbVamEyX43yzQOphzkhYsz4pruATzTxU+z8/zPdEqHcWWV39CP3xu3EYNcAhxJW8CQQC2u7PF5Xb1xYRCsmIPssFxil64vvdUadSxl7GLAgjQ9ULyYWB24KObCEzLnPcT8Pf2Q0YQOixxa/78FuzmgbyfAkA7ZFFV/H7lugB6t+f7p24OhkRFep9CwBMD6dnZRBgSr6X8d8ZvfrD2Z7DgBMeSva+OEoOtlNmXExZ3lynO9zN5AkAVczEmIMp3DSl6XtAuAZC9kD2QODJ2QToLYsAfjiyUwsWKCC43piTuVOoW2KUUPSwOR1VZIEsJQWEcHGDQqhgHAkAeZ7a6dVRZFdBwKA0ADjYCufAW2cIYiVDQBJpgB+kiLQflusNOCBK0FT3lg8BdUSy2D253Ih6l3lbaM/4M7DFQ";
private static final String KEY_AES = "AES";
public static String aesEncrypt(String src) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] raw = "hangzhouzhejiang".getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src.getBytes());
return byte2hex(encrypted);
}
public static String aesDecrypt(String src) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] raw = "hangzhouzhejiang".getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(src);
byte[] original = cipher.doFinal(encrypted1);
return new String(original);
}
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return new byte[0];
}
int l = strhex.length();
if (l % 2 == 1) {
return new byte[0];
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
}
return b;
}
public static String byte2hex(byte[] b) {
StringBuilder sb = new StringBuilder();
String tmp = "";
for (int n = 0; n < b.length; n++) {
tmp = (Integer.toHexString(b[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0" + tmp);
} else {
sb.append(tmp);
}
}
return sb.toString().toUpperCase();
}
public static String plainTextPassword(String text) throws ScriptException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
if (StringUtils.isEmpty(text)) {
return text;
}
Matcher matcher = StringTools.SCRIPTTEXT_REGEX.matcher(text);
if (matcher.matches()) {
String value = StringEscapeUtils.unescapeJson(matcher.group(1));
if (StringUtils.startsWithIgnoreCase(value, "ENCRYPT:")) {
String de = StringUtils.substringAfter(value, ":");
return aesDecrypt(de);
} else {
String eval = ScriptFactory.functionalization(StringEscapeUtils.unescapeJson(value));
ScriptContext scriptContext = new SimpleScriptContext();
return Objects.toString(ScriptFactory.scriptEngine.eval(eval, scriptContext));
}
} else {
return text;
}
}
}
......@@ -33,6 +33,7 @@ import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.tools.ClassLoaderTools;
import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.ListTools;
import com.x.server.console.node.EventQueueExecutor;
......@@ -97,7 +98,7 @@ public class ResourceFactory {
dataSource.setDriverClass(ds.getDriverClassName());
dataSource.setPreferredTestQuery(SlicePropertiesBuilder.validationQueryOfUrl(ds.getUrl()));
dataSource.setUser(ds.getUsername());
dataSource.setPassword(ScriptFactory.evalIfScriptTextAsString(ds.getPassword()));
dataSource.setPassword(Crypto.plainTextPassword(ds.getPassword()));
dataSource.setMaxPoolSize(ds.getMaxTotal());
dataSource.setMinPoolSize(ds.getMaxIdle());
// 增加校验
......@@ -130,10 +131,10 @@ public class ResourceFactory {
dataSource.setDriverClass(SlicePropertiesBuilder.driver_h2);
dataSource.setPreferredTestQuery(SlicePropertiesBuilder.validationQueryOfUrl(url));
dataSource.setUser("sa");
dataSource.setPassword(Config.token().getPassword());
dataSource.setPassword(Crypto.plainTextPassword(Config.token().getPassword()));
dataSource.setMaxPoolSize(entry.getValue().getMaxTotal());
dataSource.setMinPoolSize(entry.getValue().getMaxIdle());
dataSource.setAcquireIncrement(0);
dataSource.setAcquireIncrement(2);
if (BooleanUtils.isTrue(entry.getValue().getStatEnable())) {
dataSource.setFilters(entry.getValue().getStatFilter());
Properties properties = new Properties();
......
......@@ -45,6 +45,7 @@ public class ActionControl extends ActionBase {
private static final String CMD_DDL = "ddl";
private static final String CMD_RST = "rst";
private static final String CMD_SC = "sc";
private static final String CMD_EN = "en";
private static final int REPEAT_MAX = 100;
private static final int REPEAT_MIN = 1;
......@@ -83,6 +84,8 @@ public class ActionControl extends ActionBase {
rst(cmd);
} else if (cmd.hasOption(CMD_SC)) {
sc(cmd);
} else if (cmd.hasOption(CMD_EN)) {
en(cmd);
} else {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("control command", options);
......@@ -108,6 +111,7 @@ public class ActionControl extends ActionBase {
options.addOption(ddlOption());
options.addOption(rstOption());
options.addOption(scOption());
options.addOption(enOption());
return options;
}
......@@ -149,21 +153,11 @@ public class ActionControl extends ActionBase {
.desc("导出数据库服务器的数据转换成json格式保存到本地文件.").build();
}
// private static Option dsOption() {
// return Option.builder("ds").longOpt("dumpStorage").argName("path").hasArg().optionalArg(true)
// .desc("导出存储服务器的文件数据转换成json格式保存到本地文件.").build();
// }
private static Option rdOption() {
return Option.builder("rd").longOpt("restoreData").argName("path or date").hasArg()
.desc("将导出的json格式数据恢复到数据库服务器.").build();
}
// private static Option rsOption() {
// return Option.builder("rs").longOpt("restoreStorage").argName("path or date").hasArg()
// .desc("将导出的json格式文件数据恢复到存储服务器.").build();
// }
private static Option ufOption() {
return Option.builder("uf").longOpt("updateFile").argName("path").hasArg().desc("升级服务器,升级前请注意备份.").build();
}
......@@ -182,6 +176,10 @@ public class ActionControl extends ActionBase {
return Option.builder("sc").longOpt("showCluster").desc("显示集群信息.").build();
}
private static Option enOption() {
return Option.builder("en").longOpt("encrypt password text.").desc("密码文本加密.").build();
}
private void ec(CommandLine cmd) throws Exception {
if (BooleanUtils.isNotTrue(Config.currentNode().getEraseContentEnable())) {
logger.print("erase content is disabled.");
......@@ -303,6 +301,12 @@ public class ActionControl extends ActionBase {
sc.execute();
}
private void en(CommandLine cmd) throws Exception {
String text = Objects.toString(cmd.getOptionValue(CMD_EN), "");
Encrypt en = new Encrypt();
en.execute(text);
}
private Integer getArgInteger(CommandLine cmd, String opt, Integer defaultValue) {
Integer repeat = defaultValue;
String r = cmd.getOptionValue(opt);
......
package com.x.server.console.action;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.Crypto;
public class Encrypt {
private static Logger logger = LoggerFactory.getLogger(Encrypt.class);
public boolean execute(String text) throws Exception {
logger.print("encrypt text:(ENCRYPT:{})", Crypto.aesEncrypt(text));
return true;
}
}
\ No newline at end of file
......@@ -9,6 +9,7 @@ import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.DataServer;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.Crypto;
public class DataServerTools {
......@@ -19,7 +20,7 @@ public class DataServerTools {
FileUtils.forceMkdir(dataBaseDir);
Server tcpServer = null;
Server webServer = null;
String password = Config.token().getPassword();
String password = Crypto.plainTextPassword(Config.token().getPassword());
String[] tcps = new String[9];
tcps[0] = "-tcp";
tcps[1] = "-tcpAllowOthers";
......
......@@ -36,16 +36,16 @@ class ActionCaptchaLogin extends BaseAction {
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
String credential = wi.getCredential();
String password = wi.getPassword();
String isEncrypted = wi.getIsEncrypted();
//RSA解秘
// RSA解秘
if (!StringUtils.isEmpty(isEncrypted)) {
if(isEncrypted.trim().equalsIgnoreCase("y")) {
password = this.decryptRSA(password);
if (isEncrypted.trim().equalsIgnoreCase("y")) {
password = this.decryptRSA(password);
}
}
String captcha = wi.getCaptcha();
String captchaAnswer = wi.getCaptchaAnswer();
if (StringUtils.isEmpty(credential)) {
......@@ -64,7 +64,7 @@ class ActionCaptchaLogin extends BaseAction {
}
}
if (Config.token().isInitialManager(credential)) {
if (!StringUtils.equals(Config.token().getPassword(), password)) {
if (!StringUtils.equals(Crypto.plainTextPassword(Config.token().getPassword()), password)) {
throw new ExceptionPersonNotExistOrInvalidPassword();
}
wo = this.manager(request, response, business, Wo.class);
......@@ -74,20 +74,20 @@ class ActionCaptchaLogin extends BaseAction {
if (StringUtils.isEmpty(personId)) {
throw new ExceptionPersonNotExistOrInvalidPassword();
}
Person o = null;
//处理同中文问题
if(personId.indexOf(",") > -1) {
// 处理同中文问题
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;
}
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);
} else {
o = emc.find(personId, Person.class);
}
if (BooleanUtils.isTrue(Config.person().getSuperPermission())
......@@ -105,8 +105,7 @@ class ActionCaptchaLogin extends BaseAction {
}
}
}
wo = this.user(request, response, business, o, Wo.class);
audit.log(o.getDistinguishedName(), "登录");
}
......@@ -115,60 +114,60 @@ class ActionCaptchaLogin extends BaseAction {
}
}
//用户登入解密
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;
// 用户登入解密
public String decryptRSA(String strDecrypt) {
String privateKey;
String decrypt = null;
try {
privateKey = getPrivateKey();
decrypt = Crypto.rsaDecrypt(strDecrypt, privateKey);
} catch (Exception e) {
e.printStackTrace();
}
//转成Base64
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;
return decrypt;
}
// 转成Base64
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();
}
//转成Base64
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;
return encrypt;
}
// 转成Base64
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();
}
//转成Base64
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;
return publicKey;
}
// 转成Base64
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 {
@FieldDescribe("凭证")
......@@ -185,7 +184,7 @@ class ActionCaptchaLogin extends BaseAction {
@FieldDescribe("是否启用加密,默认不加密,启用(y)。注意:使用加密先要在服务器运行 create encrypt key")
private String isEncrypted;
public String getPassword() {
return password;
}
......@@ -217,6 +216,7 @@ class ActionCaptchaLogin extends BaseAction {
public void setCaptchaAnswer(String captchaAnswer) {
this.captchaAnswer = captchaAnswer;
}
public String getIsEncrypted() {
return isEncrypted;
}
......
......@@ -43,7 +43,7 @@ class ActionLogin extends BaseAction {
throw new ExceptionPasswordEmpty();
}
if (Config.token().isInitialManager(credential)) {
if (!StringUtils.equals(Config.token().getPassword(), password)) {
if (!StringUtils.equals(Crypto.plainTextPassword(Config.token().getPassword()), password)) {
throw new ExceptionPersonNotExistOrInvalidPassword();
}
wo = this.manager(request, response, business, Wo.class);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册