Commit f07cde2a by java-李谡

代码规范

parent 3f43a184
package com.baidu.ueditor.define;
public enum ActionState {
UNKNOW_ERROR
}
package com.baidu.ueditor.hunter; package com.baidu.ueditor.hunter;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import com.baidu.ueditor.core.PathFormat; import com.baidu.ueditor.core.PathFormat;
import com.baidu.ueditor.define.AppInfo; import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState; import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState; import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State; import com.baidu.ueditor.define.State;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
public class FileManager { public class FileManager {
...@@ -19,102 +18,101 @@ public class FileManager { ...@@ -19,102 +18,101 @@ public class FileManager {
private String rootPath = null; private String rootPath = null;
private String[] allowFiles = null; private String[] allowFiles = null;
private int count = 0; private int count = 0;
public FileManager ( Map<String, Object> conf ) { public FileManager(Map<String, Object> conf) {
this.rootPath = (String)conf.get( "rootPath" ); this.rootPath = (String) conf.get("rootPath");
this.dir = this.rootPath + (String)conf.get( "dir" ); this.dir = this.rootPath + (String) conf.get("dir");
this.allowFiles = this.getAllowFiles( conf.get("allowFiles") ); this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
this.count = (Integer)conf.get( "count" ); this.count = (Integer) conf.get("count");
} }
public State listFile ( int index ) { public State listFile(int index) {
File dir = new File( this.dir ); File dir = new File(this.dir);
State state = null; State state = null;
if ( !dir.exists() ) { if (!dir.exists()) {
return new BaseState( false, AppInfo.NOT_EXIST ); return new BaseState(false, AppInfo.NOT_EXIST);
} }
if ( !dir.isDirectory() ) { if (!dir.isDirectory()) {
return new BaseState( false, AppInfo.NOT_DIRECTORY ); return new BaseState(false, AppInfo.NOT_DIRECTORY);
} }
Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true ); Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
if ( index < 0 || index > list.size() ) { if (index < 0 || index > list.size()) {
state = new MultiState( true ); state = new MultiState(true);
} else { } else {
Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count ); Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count);
state = this.getState( fileList ); state = this.getState(fileList);
} }
state.putInfo( "start", index ); state.putInfo("start", index);
state.putInfo( "total", list.size() ); state.putInfo("total", list.size());
return state; return state;
} }
private State getState ( Object[] files ) { private State getState(Object[] files) {
MultiState state = new MultiState( true ); MultiState state = new MultiState(true);
BaseState fileState = null; BaseState fileState = null;
File file = null; File file = null;
for ( Object obj : files ) { for (Object obj : files) {
if ( obj == null ) { if (obj == null) {
break; break;
} }
file = (File)obj; file = (File) obj;
fileState = new BaseState( true ); fileState = new BaseState(true);
// fileState.putInfo( "url", PathFormat.format( this.getPathFormat( file ) ) ); fileState.putInfo("url", this.getPathFormat(file));
fileState.putInfo( "url", this.getPathFormat( file ) ); state.addState(fileState);
state.addState( fileState );
} }
return state; return state;
} }
private String getPathFormat ( File file ) { private String getPathFormat(File file) {
String path = file.getAbsolutePath(); String path = file.getAbsolutePath();
path = PathFormat.format(path); path = PathFormat.format(path);
if(this.rootPath.startsWith("/")){ if (this.rootPath.startsWith("/")) {
if(path.startsWith("/") == false){// 解决Windows下路径问题 // 解决Windows下路径问题
path = "/"+path; if (path.startsWith("/") == false) {
path = "/" + path;
} }
} }
// System.out.println(this.rootPath+"=="+path); return path.replace(this.rootPath, "/");
return path.replace( this.rootPath, "/" );
} }
private String[] getAllowFiles ( Object fileExt ) { private String[] getAllowFiles(Object fileExt) {
String[] exts = null; String[] exts = null;
String ext = null; String ext = null;
if ( fileExt == null ) { if (fileExt == null) {
return new String[ 0 ]; return new String[0];
} }
exts = (String[])fileExt; exts = (String[]) fileExt;
for ( int i = 0, len = exts.length; i < len; i++ ) { for (int i = 0, len = exts.length; i < len; i++) {
ext = exts[ i ]; ext = exts[i];
exts[ i ] = ext.replace( ".", "" ); exts[i] = ext.replace(".", "");
} }
return exts; return exts;
} }
} }
...@@ -21,7 +21,7 @@ import org.springframework.web.servlet.HandlerInterceptor; ...@@ -21,7 +21,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.ejweb.core.conf.GConstants; import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.LoadExceptions; import com.ejweb.core.utils.LoadException;
/** /**
...@@ -43,7 +43,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -43,7 +43,7 @@ public class URLInterceptor implements HandlerInterceptor {
if(fileSize > maxFileSize) if(fileSize > maxFileSize)
{ {
throw new LoadExceptions("文件大小超出限制,请改正!"); throw new LoadException("文件大小超出限制,请改正!");
} }
...@@ -114,7 +114,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -114,7 +114,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -125,8 +125,8 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -125,8 +125,8 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -141,7 +141,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -141,7 +141,7 @@ public class URLInterceptor implements HandlerInterceptor {
||queryString.contains("user.name"))){ ||queryString.contains("user.name"))){
continue; continue;
} }
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -152,7 +152,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -152,7 +152,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -163,7 +163,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -163,7 +163,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
......
...@@ -47,7 +47,6 @@ public abstract class DataEntity<T> extends BaseEntity<T> { ...@@ -47,7 +47,6 @@ public abstract class DataEntity<T> extends BaseEntity<T> {
// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID // 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
if (!this.isNewRecord){ if (!this.isNewRecord){
setId(IdGen.uuid()); setId(IdGen.uuid());
// setId(IdGen.uuid());
} }
User user = UserUtils.getUser(); User user = UserUtils.getUser();
if (StringUtils.isNotBlank(user.getId())){ if (StringUtils.isNotBlank(user.getId())){
......
...@@ -18,7 +18,6 @@ public class DerbyDialect implements Dialect { ...@@ -18,7 +18,6 @@ public class DerbyDialect implements Dialect {
@Override @Override
public String getLimitString(String sql, int offset, int limit) { public String getLimitString(String sql, int offset, int limit) {
// return getLimitString(sql,offset,Integer.toString(offset),limit,Integer.toString(limit));
throw new UnsupportedOperationException("paged queries not supported"); throw new UnsupportedOperationException("paged queries not supported");
} }
...@@ -37,8 +36,8 @@ public class DerbyDialect implements Dialect { ...@@ -37,8 +36,8 @@ public class DerbyDialect implements Dialect {
* @param limitPlaceholder 分页纪录条数占位符号 * @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql * @return 包含占位符的分页sql
*/ */
public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) { public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException( "paged queries not supported" ); throw new UnsupportedOperationException("paged queries not supported");
} }
} }
package com.ejweb.core.security; package com.ejweb.core.security;
import java.io.UnsupportedEncodingException; import org.apache.commons.codec.digest.DigestUtils;
import java.security.Security;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import org.apache.commons.codec.digest.DigestUtils;
public class DES3Utils { public class DES3Utils {
// public static final String ALGORITHM = "DES"; // public static final String ALGORITHM = "DES";
private static final String Algorithm = "DESede"; // 定义加密算法,可用 private static final String Algorithm = "DESede"; // 定义加密算法,可用
// DES,DESede,Blowfish // DES,DESede,Blowfish
static { static {
...@@ -65,7 +63,7 @@ public class DES3Utils { ...@@ -65,7 +63,7 @@ public class DES3Utils {
String f = DigestUtils.md5Hex(username); String f = DigestUtils.md5Hex(username);
byte[] bkeys = new String(f).getBytes(); byte[] bkeys = new String(f).getBytes();
byte[] enk = new byte[24]; byte[] enk = new byte[24];
for (int i = 0; i < 24 && i< bkeys.length; i++) { for (int i = 0; i < 24 && i < bkeys.length; i++) {
enk[i] = bkeys[i]; enk[i] = bkeys[i];
} }
return enk; return enk;
...@@ -96,7 +94,7 @@ public class DES3Utils { ...@@ -96,7 +94,7 @@ public class DES3Utils {
c1.init(Cipher.ENCRYPT_MODE, deskey); c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(data);// 在单一方面的加密或解密 return c1.doFinal(data);// 在单一方面的加密或解密
} catch (Exception e) { } catch (Exception e) {
} }
return null; return null;
} }
...@@ -121,17 +119,7 @@ public class DES3Utils { ...@@ -121,17 +119,7 @@ public class DES3Utils {
byte[] decrypted = c1.doFinal(data); byte[] decrypted = c1.doFinal(data);
return new String(decrypted, "UTF-8"); return new String(decrypted, "UTF-8");
} catch (Exception e) { } catch (Exception e) {
// e3.printStackTrace();
} }
return null; return null;
} }
public static void main(String[] args) throws UnsupportedEncodingException {
// byte[] ened = encrypt("我是中国人".getBytes(), "123456");
// String en = Base64.encode(ened);
System.out.println(encrypt("我是中国人", "782790337169117184"));
System.out.println(decrypt("fc564cedfd08e11664e33d4ddf381997", "782790337169117184"));
// System.out.println(decrypt(ened, "123456"));
}
} }
/** /**
* *
*/ */
package com.ejweb.core.utils; package com.ejweb.core.utils;
import java.util.HashMap;
import com.ejweb.core.conf.GConstants; import com.ejweb.core.conf.GConstants;
import java.util.HashMap;
/** /**
* 文件安全扫描过滤 * 文件安全扫描过滤
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @time 2016年11月5日 * @team IT Team
* @time 2016年11月5日
*/ */
public class FileManipulation { public class FileManipulation {
public static String Manipulation(String path){ public static String Manipulation(String path) {
HashMap<String, String> map = new HashMap<String, String>(); HashMap<String, String> map = new HashMap<String, String>();
map.put("a", "a"); map.put("a", "a");
map.put("b", "b"); map.put("b", "b");
map.put("c", "c"); map.put("c", "c");
map.put("d", "d"); map.put("d", "d");
map.put("e", "e"); map.put("e", "e");
map.put("f", "f"); map.put("f", "f");
map.put("g", "g"); map.put("g", "g");
map.put("h", "h"); map.put("h", "h");
map.put("i", "i"); map.put("i", "i");
map.put("j", "j"); map.put("j", "j");
map.put("k", "k"); map.put("k", "k");
map.put("l", "l"); map.put("l", "l");
map.put("m", "m"); map.put("m", "m");
map.put("n", "n"); map.put("n", "n");
map.put("o", "o"); map.put("o", "o");
map.put("p", "p"); map.put("p", "p");
map.put("q", "q"); map.put("q", "q");
map.put("r", "r"); map.put("r", "r");
map.put("s", "s"); map.put("s", "s");
map.put("t", "t"); map.put("t", "t");
map.put("u", "u"); map.put("u", "u");
map.put("v", "v"); map.put("v", "v");
map.put("w", "w"); map.put("w", "w");
map.put("x", "x"); map.put("x", "x");
map.put("y", "y"); map.put("y", "y");
map.put("z", "z"); map.put("z", "z");
map.put("A", "A"); map.put("A", "A");
map.put("B", "B"); map.put("B", "B");
map.put("C", "C"); map.put("C", "C");
map.put("D", "D"); map.put("D", "D");
map.put("E", "E"); map.put("E", "E");
map.put("F", "F"); map.put("F", "F");
map.put("G", "G"); map.put("G", "G");
map.put("H", "H"); map.put("H", "H");
map.put("I", "I"); map.put("I", "I");
map.put("J", "J"); map.put("J", "J");
map.put("K", "K"); map.put("K", "K");
map.put("L", "L"); map.put("L", "L");
map.put("M", "M"); map.put("M", "M");
map.put("N", "N"); map.put("N", "N");
map.put("O", "O"); map.put("O", "O");
map.put("P", "P"); map.put("P", "P");
map.put("Q", "Q"); map.put("Q", "Q");
map.put("R", "R"); map.put("R", "R");
map.put("S", "S"); map.put("S", "S");
map.put("T", "T"); map.put("T", "T");
map.put("U", "U"); map.put("U", "U");
map.put("V", "V"); map.put("V", "V");
map.put("W", "W"); map.put("W", "W");
map.put("X", "X"); map.put("X", "X");
map.put("Y", "Y"); map.put("Y", "Y");
map.put("Z", "Z"); map.put("Z", "Z");
map.put(":", ":");
map.put("/", "/");
map.put("\\", "\\");
map.put(":", ":"); String temp = "";
map.put("/", "/"); for (int i = 0; i < path.length(); i++) {
map.put("\\", "\\");
String temp = "";
for (int i = 0; i < path.length(); i++) {
if (map.get(path.charAt(i)+"")!=null) { if (map.get(path.charAt(i) + "") != null) {
temp += map.get(path.charAt(i)+""); temp += map.get(path.charAt(i) + "");
}
} }
} path = temp;
path = temp; return path;
return path; }
}
/**
*
* 黑名单验证
* @author zhanglg
* @time 2016年11月5日
* @return
*/
public static String validateFile(String filename){
String[] extesions=new String[]{"%",";"};
for(String extesion:extesions){
if(filename.contains(extesion)){
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename);
}
}
/* String extesionName = Util.getExtensionName(filename);
// if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL
// throw new LoadExceptions("无法获取文件扩展名:"+filename);
// }
/**
String exd=".png;.jpg;.gif;.jpeg;.xls;.xlsx;.bmp;.ico;.swf;.psd;.apk;.doc;.docx;.txt;.sql;.xml;"; * 黑名单验证
if(!exd.contains(extesionName)){ *
throw new LoadExceptions("此类型文件不允许上传:"+filename); * @return
}*/ * @author zhanglg
/* if(GConstants.FILE_FILTERS.get(extesionName) == null){ * @time 2016年11月5日
throw new LoadExceptions("此类型文件不允许上传:"+filename); */
}*/ public static String validateFile(String filename) {
filename= filename.replaceAll("\\.\\./", "");
filename= filename.replaceAll("\\.\\.\\\\", ""); String[] extesions = new String[]{"%", ";"};
filename= filename.replaceAll("\\.\\.", ""); for (String extesion : extesions) {
return filename; if (filename.contains(extesion)) {
} throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
}
public static void check(String filename){ }
String extesionName = Util.getExtensionName(filename); filename = filename.replaceAll("\\.\\./", "");
if(GConstants.FILE_FILTERS.get(extesionName) == null){ filename = filename.replaceAll("\\.\\.\\\\", "");
throw new LoadExceptions("此类型文件不允许上传:"+filename); filename = filename.replaceAll("\\.\\.", "");
} return filename;
String[] extesions=new String[]{"%",";"}; }
for(String extesion:extesions){
if(filename.contains(extesion)){ public static void check(String filename) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename); String extesionName = Util.getExtensionName(filename);
} if (GConstants.FILE_FILTERS.get(extesionName) == null) {
} throw new LoadException("此类型文件不允许上传:" + filename);
} }
String[] extesions = new String[]{"%", ";"};
/** for (String extesion : extesions) {
* if (filename.contains(extesion)) {
* 黑名单验证2 throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
* @author zhanglg }
* @time 2016年11月5日 }
* @return }
*/
public static String validateFile2(String filename){ /**
String[] extesions=new String[]{".xmls",".propertiey",".jsons"}; * 黑名单验证2
for(String extesion:extesions){ *
if(filename.contains(extesion)){ * @return
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件"); * @author zhanglg
} * @time 2016年11月5日
} */
return filename; public static String validateFile2(String filename) {
} String[] extesions = new String[]{".xmls", ".propertiey", ".jsons"};
for (String extesion : extesions) {
if (filename.contains(extesion)) {
throw new LoadException("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件");
}
}
return filename;
}
} }
/** /**
* *
*/ */
package com.ejweb.core.utils; package com.ejweb.core.utils;
/** /**
* 上传下载非法的异常抛出 * 上传下载非法的异常抛出
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @time 2016年11月6日 * @team IT Team
* @time 2016年11月6日
*/ */
public class LoadExceptions extends RuntimeException { public class LoadException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String retCd ; //异常对应的返回码 /**
private String msgDes; //异常对应的描述信息 *异常对应的返回码
*/
public LoadExceptions() { private String retCd;
/**
*异常对应的描述信息
*/
private String msgDes;
public LoadException() {
super(); super();
} }
public LoadExceptions(String message) { public LoadException(String message) {
super(message); super(message);
msgDes = message; msgDes = message;
} }
public LoadExceptions(String retCd, String msgDes) { public LoadException(String retCd, String msgDes) {
super(); super();
this.retCd = retCd; this.retCd = retCd;
this.msgDes = msgDes; this.msgDes = msgDes;
} }
public String getRetCd() { public String getRetCd() {
return retCd; return retCd;
} }
public String getMsgDes() { public String getMsgDes() {
return msgDes; return msgDes;
} }
......
...@@ -44,39 +44,35 @@ public class CKFinderConnectorServlet extends ConnectorServlet { ...@@ -44,39 +44,35 @@ public class CKFinderConnectorServlet extends ConnectorServlet {
try { try {
Principal principal = (Principal) UserUtils.getPrincipal(); Principal principal = (Principal) UserUtils.getPrincipal();
if (principal == null){ if (principal == null) {
return; return;
} }
String command = request.getParameter("command"); String command = request.getParameter("command");
String type = request.getParameter("type"); String type = request.getParameter("type");
if ("Init".equals(command)){// 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹 // 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹
String startupPath = request.getParameter("startupPath");// 当前文件夹可指定为模块名 if ("Init".equals(command)) {
if (startupPath!=null){ // 当前文件夹可指定为模块名
String startupPath = request.getParameter("startupPath");
if (startupPath != null) {
String[] ss = startupPath.split(":"); String[] ss = startupPath.split(":");
if (ss.length==2){ if (ss.length == 2) {
// String realPath = GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL
// + principal + "/" + ss[0] + ss[1];
// FileUtils.createDirectory(FileUtils.path(realPath));
String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1]; String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1];
realPath= FileManipulation.validateFile(realPath); realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath)); File fileRealPath = new File(FileManipulation.validateFile(realPath));
if(fileRealPath.exists() == false){ if (fileRealPath.exists() == false) {
fileRealPath.mkdirs(); fileRealPath.mkdirs();
} }
} }
} }
} else if ("QuickUpload".equals(command) && type != null){// 快捷上传,自动创建当前文件夹,并上传到该路径 // 快捷上传,自动创建当前文件夹,并上传到该路径
String currentFolder = request.getParameter("currentFolder");// 当前文件夹可指定为模块名 } else if ("QuickUpload".equals(command) && type != null) {
// String realPath = GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL // 当前文件夹可指定为模块名
// + principal + "/" + type + (currentFolder != null ? currentFolder : ""); String currentFolder = request.getParameter("currentFolder");
// FileUtils.createDirectory(FileUtils.path(realPath));
String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : ""); String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : "");
// 验证文件安全 // 验证文件安全
realPath= FileManipulation.validateFile(realPath); realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath)); File fileRealPath = new File(FileManipulation.validateFile(realPath));
if(fileRealPath.exists() == false){ if (fileRealPath.exists() == false) {
fileRealPath.mkdirs(); fileRealPath.mkdirs();
} }
} }
......
...@@ -2,23 +2,22 @@ package com.ejweb.modules.airline.entity; ...@@ -2,23 +2,22 @@ package com.ejweb.modules.airline.entity;
import com.ejweb.core.persistence.DataEntity; import com.ejweb.core.persistence.DataEntity;
//import com.ejweb.modules.sys.entity.Area;
/** /**
*
* Verify Entity * Verify Entity
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @time 2016年8月30日 * @team IT Team
* @time 2016年8月30日
*/ */
public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneable{ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String id; private String id;
private String flightNo; private String flightNo;
...@@ -27,10 +26,10 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl ...@@ -27,10 +26,10 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl
private String arrIata; private String arrIata;
private String IsMain; private String IsMain;
private String verifId; private String verifId;
public String getId() { public String getId() {
return id; return id;
} }
...@@ -79,7 +78,5 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl ...@@ -79,7 +78,5 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl
this.verifId = verifId; this.verifId = verifId;
} }
} }
\ No newline at end of file
...@@ -16,18 +16,19 @@ import java.io.*; ...@@ -16,18 +16,19 @@ import java.io.*;
*/ */
@Service @Service
@Transactional(readOnly = true) @Transactional(readOnly = true)
public class FileService { public class FileService {
private static Logger LOG = Logger.getLogger(FileService.class); private static Logger LOG = Logger.getLogger(FileService.class);
private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}"); private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
public String upload(MultipartFile multipartFile,String originalFilename){
public String upload(MultipartFile multipartFile, String originalFilename) {
OutputStream os = null; OutputStream os = null;
String moduleName="image"; String moduleName = "image";
ByteArrayOutputStream baos = null; ByteArrayOutputStream baos = null;
try{ try {
String extesionName = Util.getExtensionName(originalFilename); String extesionName = Util.getExtensionName(originalFilename);
InputStream in=multipartFile.getInputStream(); InputStream in = multipartFile.getInputStream();
in = new BufferedInputStream(in); in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream(); baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE]; byte[] buf = new byte[GConstants.BUFFER_SIZE];
...@@ -37,33 +38,32 @@ public class FileService { ...@@ -37,33 +38,32 @@ public class FileService {
baos.write(buf, 0, size); baos.write(buf, 0, size);
size = in.read(buf); size = in.read(buf);
} }
byte[] data = baos.toByteArray(); byte[] data = baos.toByteArray();
// byte[] data = IOUtils.toByteArray(in);
// 待扩展名称的MOD5 // 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data)+extesionName; String md5 = DigestUtils.md5Hex(data) + extesionName;
if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL // 文件扩展名称不能为NULL
LOG.debug("无法获取文件扩展名:"+originalFilename); if (extesionName == null || extesionName.length() == 0) {
LOG.debug("无法获取文件扩展名:" + originalFilename);
} }
// 文件保存路径:基本路径+模块名称+日期 // 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis()); String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
String basePath = moduleName+GConstants.FS+extesionName.replaceAll("\\.", "")+GConstants.FS; String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// 上传文件基本地址 // 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath); File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath);
if(!baseUploadDir.exists()){// 如果文件夹不存在则创建 if (!baseUploadDir.exists()) {
baseUploadDir.mkdirs(); baseUploadDir.mkdirs();
} }
// 文件保存地址 // 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5); File uploadFilePath = new File(baseUploadDir, md5);
LOG.info("原文件服务器绝对路径:"+uploadFilePath); LOG.info("原文件服务器绝对路径:" + uploadFilePath);
// 将数据保存到指定文件 // 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath); os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os); os = new BufferedOutputStream(os);
os.write(data); os.write(data);
os.flush(); os.flush();
return baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5; return baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath + md5;
}catch (IOException ex){ } catch (IOException ex) {
return "error"+ex.getMessage(); return "error" + ex.getMessage();
} }
} }
......
...@@ -34,7 +34,6 @@ public class FileUploadController extends BaseController { ...@@ -34,7 +34,6 @@ public class FileUploadController extends BaseController {
try { try {
request.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html"); response.setHeader("Content-Type", "text/html");
// String fileName = file.getOriginalFilename();
// 转换为文件类型的request // 转换为文件类型的request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
......
...@@ -3,10 +3,7 @@ ...@@ -3,10 +3,7 @@
*/ */
package com.ejweb.modules.sys.security; package com.ejweb.modules.sys.security;
import javax.servlet.ServletRequest; import com.ejweb.core.utils.StringUtils;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.IncorrectCredentialsException;
...@@ -14,10 +11,13 @@ import org.apache.shiro.authc.UnknownAccountException; ...@@ -14,10 +11,13 @@ import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils; import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.ejweb.core.utils.StringUtils; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/** /**
* 表单验证(包含验证码)过滤类 * 表单验证(包含验证码)过滤类
*
* @author ThinkGem * @author ThinkGem
* @version 2014-5-19 * @version 2014-5-19
*/ */
...@@ -35,11 +35,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -35,11 +35,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String username = getUsername(request); String username = getUsername(request);
String password = getPassword(request); String password = getPassword(request);
if (password==null){ if (password == null) {
password = ""; password = "";
} }
boolean rememberMe = isRememberMe(request); boolean rememberMe = isRememberMe(request);
String host = StringUtils.getRemoteAddr((HttpServletRequest)request); String host = StringUtils.getRemoteAddr((HttpServletRequest) request);
String captcha = getCaptcha(request); String captcha = getCaptcha(request);
boolean mobile = isMobileLogin(request); boolean mobile = isMobileLogin(request);
return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile); return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile);
...@@ -56,31 +56,26 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -56,31 +56,26 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
public String getMobileLoginParam() { public String getMobileLoginParam() {
return mobileLoginParam; return mobileLoginParam;
} }
protected boolean isMobileLogin(ServletRequest request) { protected boolean isMobileLogin(ServletRequest request) {
return WebUtils.isTrue(request, getMobileLoginParam()); return WebUtils.isTrue(request, getMobileLoginParam());
} }
public String getMessageParam() { public String getMessageParam() {
return messageParam; return messageParam;
} }
/** /**
* 登录成功之后跳转URL * 登录成功之后跳转URL
*/ */
public String getSuccessUrl() { public String getSuccessUrl() {
return super.getSuccessUrl(); return super.getSuccessUrl();
} }
@Override @Override
protected void issueSuccessRedirect(ServletRequest request, protected void issueSuccessRedirect(ServletRequest request,
ServletResponse response) throws Exception { ServletResponse response) throws Exception {
// Principal p = UserUtils.getPrincipal(); WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
// if (p != null && !p.isMobileLogin()){
WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
// }else{
// super.issueSuccessRedirect(request, response);
// }
} }
/** /**
...@@ -88,16 +83,14 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -88,16 +83,14 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
*/ */
@Override @Override
protected boolean onLoginFailure(AuthenticationToken token, protected boolean onLoginFailure(AuthenticationToken token,
AuthenticationException e, ServletRequest request, ServletResponse response) { AuthenticationException e, ServletRequest request, ServletResponse response) {
String className = e.getClass().getName(), message = ""; String className = e.getClass().getName(), message = "";
if (IncorrectCredentialsException.class.getName().equals(className) if (IncorrectCredentialsException.class.getName().equals(className)
|| UnknownAccountException.class.getName().equals(className)){ || UnknownAccountException.class.getName().equals(className)) {
message = "用户或密码错误, 请重试."; message = "用户或密码错误, 请重试.";
} } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")) {
else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
message = StringUtils.replace(e.getMessage(), "msg:", ""); message = StringUtils.replace(e.getMessage(), "msg:", "");
} } else {
else{
message = "系统出现点问题,请稍后再试!"; message = "系统出现点问题,请稍后再试!";
e.printStackTrace(); // 输出到控制台 e.printStackTrace(); // 输出到控制台
} }
...@@ -105,5 +98,5 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -105,5 +98,5 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
request.setAttribute(getMessageParam(), message); request.setAttribute(getMessageParam(), message);
return true; return true;
} }
} }
\ No newline at end of file
...@@ -3,11 +3,14 @@ ...@@ -3,11 +3,14 @@
*/ */
package com.ejweb.modules.sys.web; package com.ejweb.modules.sys.web;
import java.util.List; import com.ejweb.core.base.BaseController;
import java.util.Map; import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.StringUtils;
import javax.servlet.http.HttpServletResponse; import com.ejweb.modules.sys.entity.Area;
import com.ejweb.modules.sys.service.AreaService;
import com.ejweb.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -18,17 +21,13 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -18,17 +21,13 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists; import javax.servlet.http.HttpServletResponse;
import com.google.common.collect.Maps; import java.util.List;
import com.ejweb.core.conf.GConstants; import java.util.Map;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.base.BaseController;
import com.ejweb.modules.sys.entity.Area;
import com.ejweb.modules.sys.service.AreaService;
import com.ejweb.modules.sys.utils.UserUtils;
/** /**
* 区域Controller * 区域Controller
*
* @author ThinkGem * @author ThinkGem
* @version 2013-5-15 * @version 2013-5-15
*/ */
...@@ -38,12 +37,12 @@ public class AreaController extends BaseController { ...@@ -38,12 +37,12 @@ public class AreaController extends BaseController {
@Autowired @Autowired
private AreaService areaService; private AreaService areaService;
@ModelAttribute("area") @ModelAttribute("area")
public Area get(@RequestParam(required=false) String id) { public Area get(@RequestParam(required = false) String id) {
if (StringUtils.isNotBlank(id)){ if (StringUtils.isNotBlank(id)) {
return areaService.get(id); return areaService.get(id);
}else{ } else {
return new Area(); return new Area();
} }
} }
...@@ -58,74 +57,54 @@ public class AreaController extends BaseController { ...@@ -58,74 +57,54 @@ public class AreaController extends BaseController {
@RequiresPermissions("sys:area:view") @RequiresPermissions("sys:area:view")
@RequestMapping(value = "form") @RequestMapping(value = "form")
public String form(Area area, Model model) { public String form(Area area, Model model) {
if (area.getParent()==null||area.getParent().getId()==null){ if (area.getParent() == null || area.getParent().getId() == null) {
area.setParent(UserUtils.getUser().getOffice().getArea()); area.setParent(UserUtils.getUser().getOffice().getArea());
} }
if(area.getParent() != null){ if (area.getParent() != null) {
area.setParent(areaService.get(area.getParent().getId())); area.setParent(areaService.get(area.getParent().getId()));
} }
// // 自动获取排序号
// if (StringUtils.isBlank(area.getId())){
// int size = 0;
// List<Area> list = areaService.findAll();
// for (int i=0; i<list.size(); i++){
// Area e = list.get(i);
// if (e.getParent()!=null && e.getParent().getId()!=null
// && e.getParent().getId().equals(area.getParent().getId())){
// size++;
// }
// }
// area.setCode(area.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size : 1), 4, "0"));
// }
model.addAttribute("area", area); model.addAttribute("area", area);
return "modules/sys/areaForm"; return "modules/sys/areaForm";
} }
@RequiresPermissions("sys:area:edit") @RequiresPermissions("sys:area:edit")
@RequestMapping(value = "save") @RequestMapping(value = "save")
public String save(Area area, Model model, RedirectAttributes redirectAttributes) { public String save(Area area, Model model, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area"; return "redirect:" + adminPath + "/sys/area";
} }
if (!beanValidator(model, area)){ if (!beanValidator(model, area)) {
return form(area, model); return form(area, model);
} }
// if(StringUtils.isBlank(area.getId())){
// area.setIsNewRecord(true);
// }
areaService.save(area); areaService.save(area);
addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功"); addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
return "redirect:" + adminPath + "/sys/area/"; return "redirect:" + adminPath + "/sys/area/";
} }
@RequiresPermissions("sys:area:edit") @RequiresPermissions("sys:area:edit")
@RequestMapping(value = "delete") @RequestMapping(value = "delete")
public String delete(Area area, RedirectAttributes redirectAttributes) { public String delete(Area area, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area"; return "redirect:" + adminPath + "/sys/area";
} }
// if (Area.isRoot(id)){ areaService.delete(area);
// addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空"); addMessage(redirectAttributes, "删除区域成功");
// }else{
areaService.delete(area);
addMessage(redirectAttributes, "删除区域成功");
// }
return "redirect:" + adminPath + "/sys/area/"; return "redirect:" + adminPath + "/sys/area/";
} }
@RequiresPermissions("user") @RequiresPermissions("user")
@ResponseBody @ResponseBody
@RequestMapping(value = "treeData") @RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) { public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList(); List<Map<String, Object>> mapList = Lists.newArrayList();
List<Area> list = areaService.findAll(); List<Area> list = areaService.findAll();
for (int i=0; i<list.size(); i++){ for (int i = 0; i < list.size(); i++) {
Area e = list.get(i); Area e = list.get(i);
if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){ if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) {
Map<String, Object> map = Maps.newHashMap(); Map<String, Object> map = Maps.newHashMap();
map.put("id", e.getId()); map.put("id", e.getId());
map.put("pId", e.getParentId()); map.put("pId", e.getParentId());
......
...@@ -175,9 +175,6 @@ public class FormController extends BaseController { ...@@ -175,9 +175,6 @@ public class FormController extends BaseController {
@RequiresPermissions("vrf:design:view") @RequiresPermissions("vrf:design:view")
@RequestMapping(value = "preview") @RequestMapping(value = "preview")
public String view(HttpServletRequest request,FormEntity formEntity, Model model){ public String view(HttpServletRequest request,FormEntity formEntity, Model model){
/* if(formEntity!=null){
formEntity.setFormText(formEntity.getFormText().replaceAll("<table","<table class='table table-bordered' "));
}*/
String parse_form= request.getParameter("parse_form"); String parse_form= request.getParameter("parse_form");
if(StringUtils.isNoneBlank(parse_form)){ if(StringUtils.isNoneBlank(parse_form)){
parse_form= parse_form.replaceAll("\\{\\|\\-", ""); parse_form= parse_form.replaceAll("\\{\\|\\-", "");
......
package com.hnatourism.b2b.util; package com.hnatourism.b2b.util;
import javax.crypto.Cipher;
import java.security.Key; import java.security.Key;
import java.security.Security; import java.security.Security;
import javax.crypto.Cipher;
/** /**
* 加密解密 * 加密解密
*/ */
public class DESPlus public class DESPlus {
{
private static String strDefaultKey = "so$so_"; // 默认密钥 private static String strDefaultKey = "so$so_"; // 默认密钥
...@@ -19,187 +17,156 @@ public class DESPlus ...@@ -19,187 +17,156 @@ public class DESPlus
/** /**
* 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程 * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程
* *
* @param arrB * @param arrB 需要转换的byte数组
* 需要转换的byte数组
* @return 转换后的字符串 * @return 转换后的字符串
* @throws Exception * @throws Exception 本方法不处理任何异常,所有异常全部抛出
* 本方法不处理任何异常,所有异常全部抛出
*/ */
public static String byteArr2HexStr(byte[] arrB) throws Exception public static String byteArr2HexStr(byte[] arrB) throws Exception {
{
int iLen = arrB.length; int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer( iLen * 2 ); StringBuffer sb = new StringBuffer(iLen * 2);
for ( int i = 0; i < iLen; i++ ) for (int i = 0; i < iLen; i++) {
{
int intTmp = arrB[i]; int intTmp = arrB[i];
// 把负数转换为正数 // 把负数转换为正数
while ( intTmp < 0 ) while (intTmp < 0) {
{
intTmp = intTmp + 256; intTmp = intTmp + 256;
} }
// 小于0F的数需要在前面补0 // 小于0F的数需要在前面补0
if ( intTmp < 16 ) if (intTmp < 16) {
{ sb.append("0");
sb.append( "0" );
} }
sb.append( Integer.toString( intTmp, 16 ) ); sb.append(Integer.toString(intTmp, 16));
} }
return sb.toString(); return sb.toString();
} }
/** /**
* 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 互为可逆的转换过程 * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 互为可逆的转换过程
* *
* @param strIn * @param strIn 需要转换的字符串
* 需要转换的字符串
* @return 转换后的byte数组 * @return 转换后的byte数组
* @throws Exception * @throws Exception 本方法不处理任何异常,所有异常全部抛出
* 本方法不处理任何异常,所有异常全部抛出
* @author <a href="mailto:leo841001@163.com">LiGuoQing</a> * @author <a href="mailto:leo841001@163.com">LiGuoQing</a>
*/ */
public static byte[] hexStr2ByteArr(String strIn) throws Exception public static byte[] hexStr2ByteArr(String strIn) throws Exception {
{
byte[] arrB = strIn.getBytes(); byte[] arrB = strIn.getBytes();
int iLen = arrB.length; int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2]; byte[] arrOut = new byte[iLen / 2];
for ( int i = 0; i < iLen; i = i + 2 ) for (int i = 0; i < iLen; i = i + 2) {
{ String strTmp = new String(arrB, i, 2);
String strTmp = new String( arrB, i, 2 ); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
arrOut[i / 2] = (byte) Integer.parseInt( strTmp, 16 );
} }
return arrOut; return arrOut;
} }
/** /**
* 默认构造方法,使用默认密钥 * 默认构造方法,使用默认密钥
* *
* @throws Exception * @throws Exception
*/ */
public DESPlus() throws Exception public DESPlus() throws Exception {
{ this(strDefaultKey);
this( strDefaultKey );
} }
/** /**
* 指定密钥构造方法 * 指定密钥构造方法
* *
* @param strKey * @param strKey 指定的密钥
* 指定的密钥
* @throws Exception * @throws Exception
*/ */
public DESPlus(String strKey) throws Exception public DESPlus(String strKey) throws Exception {
{
Security.addProvider(new com.sun.crypto.provider.SunJCE()); Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey( strKey.getBytes() ); Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance( "DES" ); encryptCipher = Cipher.getInstance("DES");
encryptCipher.init( Cipher.ENCRYPT_MODE, key ); encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance( "DES" ); decryptCipher = Cipher.getInstance("DES");
decryptCipher.init( Cipher.DECRYPT_MODE, key ); decryptCipher.init(Cipher.DECRYPT_MODE, key);
} }
/** /**
* 加密字节数组 * 加密字节数组
* *
* @param arrB * @param arrB 需加密的字节数组
* 需加密的字节数组
* @return 加密后的字节数组 * @return 加密后的字节数组
* @throws Exception * @throws Exception
*/ */
public byte[] encrypt(byte[] arrB) throws Exception public byte[] encrypt(byte[] arrB) throws Exception {
{ return encryptCipher.doFinal(arrB);
return encryptCipher.doFinal( arrB );
} }
/** /**
* 加密字符串 * 加密字符串
* *
* @param strIn * @param strIn 需加密的字符串
* 需加密的字符串
* @return 加密后的字符串 * @return 加密后的字符串
* @throws Exception * @throws Exception
*/ */
public String encrypt(String strIn) throws Exception public String encrypt(String strIn) throws Exception {
{
return byteArr2HexStr( encrypt( strIn.getBytes() ) ); return byteArr2HexStr(encrypt(strIn.getBytes()));
} }
/** /**
* 解密字节数组 * 解密字节数组
* *
* @param arrB * @param arrB 需解密的字节数组
* 需解密的字节数组
* @return 解密后的字节数组 * @return 解密后的字节数组
* @throws Exception * @throws Exception
*/ */
public byte[] decrypt(byte[] arrB) throws Exception public byte[] decrypt(byte[] arrB) throws Exception {
{ return decryptCipher.doFinal(arrB);
return decryptCipher.doFinal( arrB );
} }
/** /**
* 解密字符串 * 解密字符串
* *
* @param strIn * @param strIn 需解密的字符串
* 需解密的字符串
* @return 解密后的字符串 * @return 解密后的字符串
* @throws Exception * @throws Exception
*/ */
public String decrypt(String strIn) throws Exception public String decrypt(String strIn) throws Exception {
{ return new String(decrypt(hexStr2ByteArr(strIn)));
return new String( decrypt( hexStr2ByteArr( strIn ) ) );
} }
/** /**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
* *
* @param arrBTmp * @param arrBTmp 构成该字符串的字节数组
* 构成该字符串的字节数组
* @return 生成的密钥 * @return 生成的密钥
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
private Key getKey(byte[] arrBTmp) throws Exception private Key getKey(byte[] arrBTmp) throws Exception {
{
// 创建一个空的8位字节数组(默认值为0) // 创建一个空的8位字节数组(默认值为0)
byte[] arrB = new byte[8]; byte[] arrB = new byte[8];
// 将原始字节数组转换为8位 // 将原始字节数组转换为8位
for ( int i = 0; i < arrBTmp.length && i < arrB.length; i++ ) for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
{
arrB[i] = arrBTmp[i]; arrB[i] = arrBTmp[i];
} }
// 生成密钥 // 生成密钥
Key key = new javax.crypto.spec.SecretKeySpec( arrB, "DES" ); Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key; return key;
} }
public static void main(String[] args) public static void main(String[] args) {
{
System.out.println("123".matches("\\d+")); System.out.println("123".matches("\\d+"));
System.exit(0); System.exit(0);
String test = "lgjdair123!@#"; String test = "lgjdair123!@#";
//String test="123456789@"+System.currentTimeMillis(); try {
// DESPlus des; System.out.println("加密前的字符:" + test);
try
{
// des = new DESPlus( );//定义密钥
System.out.println( "加密前的字符:" + test );
//String miwen = des.encrypt( test );
String miwen = "9affe36dba5385c41ac289290d7f86f8"; String miwen = "9affe36dba5385c41ac289290d7f86f8";
System.out.println( "加密后的字符:" + miwen ); System.out.println("加密后的字符:" + miwen);
DESPlus des1 = new DESPlus();//定义密钥 DESPlus des1 = new DESPlus();
System.out.println( "解密后的字符:" + des1.decrypt( miwen )); System.out.println("解密后的字符:" + des1.decrypt(miwen));
} catch ( Exception e ) } catch (Exception e) {
{
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -179,29 +179,4 @@ public class DESPlus ...@@ -179,29 +179,4 @@ public class DESPlus
return key; return key;
} }
public static void main(String[] args)
{
System.out.println("123".matches("\\d+"));
// System.exit(0);
String test = "foc_android";
//String test="123456789@"+System.currentTimeMillis();
// DESPlus des;
try
{
// des = new DESPlus( );//定义密钥
System.out.println( "加密前的字符:" + test );
//String miwen = des.encrypt( test );
String miwen = "9affe36dba5385c41ac289290d7f86f8";
System.out.println( "加密后的字符:" + miwen );
DESPlus des1 = new DESPlus();//定义密钥
System.out.println( "解密后的字符:" + des1.decrypt( miwen ));
} catch ( Exception e )
{
e.printStackTrace();
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment