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 {
...@@ -20,96 +19,95 @@ public class FileManager { ...@@ -20,96 +19,95 @@ public class FileManager {
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(".", "");
} }
......
...@@ -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("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -126,7 +126,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -126,7 +126,7 @@ public class URLInterceptor implements HandlerInterceptor {
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.push; package com.ejweb.core.push;
import java.net.URLEncoder;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder;
public class MessagePayload { public class MessagePayload {
private final JSONObject _data = new JSONObject(); private final JSONObject _data = new JSONObject();
private To toPeople;// 默认通过设备号推送 /**
// 发送对象 ALL 发送给所有用户, BY_TOKEN 发送给指定TOKEN的用户,BY_ALIAS 发给也指定别名的用户,PRE_MESSAGE 预存数据,不发送 * 默认通过设备号推送
public enum To{ */
ALL,BY_TOKEN,BY_ALIAS,PRE_MESSAGE private To toPeople;
/**
* 发送对象 ALL 发送给所有用户, BY_TOKEN 发送给指定TOKEN的用户,BY_ALIAS 发给也指定别名的用户,PRE_MESSAGE 预存数据,不发送
*/
public enum To {
ALL, BY_TOKEN, BY_ALIAS, PRE_MESSAGE
} }
public MessagePayload() { public MessagePayload() {
_data.put("appkey", ""); _data.put("appkey", "");
_data.put("topeople", 3); _data.put("topeople", 3);
...@@ -32,6 +38,7 @@ public class MessagePayload { ...@@ -32,6 +38,7 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
public MessagePayload(String appkey, To toPeople, String secret) { public MessagePayload(String appkey, To toPeople, String secret) {
_data.put("appkey", appkey); _data.put("appkey", appkey);
...@@ -62,8 +69,8 @@ public class MessagePayload { ...@@ -62,8 +69,8 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
/** /**
*
* @param appkey APPKEY * @param appkey APPKEY
* @param toPeople 推送人群 * @param toPeople 推送人群
* @param secret 推送接口密码 * @param secret 推送接口密码
...@@ -103,20 +110,23 @@ public class MessagePayload { ...@@ -103,20 +110,23 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
/** /**
* 默认根据用户TOKEN进行推送 * 默认根据用户TOKEN进行推送
* *
* @return
* @author renmb * @author renmb
* @time 2016年8月15日 * @time 2016年8月15日
* @return
*/ */
public final static MessagePayload newPayload(){ public final static MessagePayload newPayload() {
final MessagePayload payload = new MessagePayload(); final MessagePayload payload = new MessagePayload();
payload.setToPeople(MessagePayload.To.BY_TOKEN); payload.setToPeople(MessagePayload.To.BY_TOKEN);
return payload; return payload;
} }
/** /**
* 发送已经生成的信息 * 发送已经生成的信息
*
* @param appkey * @param appkey
* @param toPeople * @param toPeople
* @param token * @param token
...@@ -144,16 +154,19 @@ public class MessagePayload { ...@@ -144,16 +154,19 @@ public class MessagePayload {
_data.put("token", secret); _data.put("token", secret);
_data.put("devices", new JSONArray()); _data.put("devices", new JSONArray());
} }
public MessagePayload setAppkey(String appkey) { public MessagePayload setAppkey(String appkey) {
_data.put("appkey", appkey); _data.put("appkey", appkey);
return this; return this;
} }
public MessagePayload setPushToken(String secret) { public MessagePayload setPushToken(String secret) {
_data.put("token", secret); _data.put("token", secret);
return this; return this;
} }
public MessagePayload setProduction(boolean production) { public MessagePayload setProduction(boolean production) {
if (production) { if (production) {
...@@ -163,6 +176,7 @@ public class MessagePayload { ...@@ -163,6 +176,7 @@ public class MessagePayload {
} }
return this; return this;
} }
public MessagePayload setToPeople(To toPeople) { public MessagePayload setToPeople(To toPeople) {
switch (toPeople) { switch (toPeople) {
...@@ -182,77 +196,81 @@ public class MessagePayload { ...@@ -182,77 +196,81 @@ public class MessagePayload {
this.toPeople = toPeople; this.toPeople = toPeople;
return this; return this;
} }
public To getToPeople() { public To getToPeople() {
return this.toPeople; return this.toPeople;
} }
public MessagePayload addMessageTitle(String title) { public MessagePayload addMessageTitle(String title) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("title", title); message.put("title", title);
return this; return this;
} }
public MessagePayload addMessageContent(String content){ public MessagePayload addMessageContent(String content) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("content", content); message.put("content", content);
return this; return this;
} }
public MessagePayload addMessageBeginTime(long beginTime){ public MessagePayload addMessageBeginTime(long beginTime) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("begin_time", beginTime); message.put("begin_time", beginTime);
return this; return this;
} }
public MessagePayload addMessageExpireTime(long expireTime){
public MessagePayload addMessageExpireTime(long expireTime) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("expire_time", expireTime); message.put("expire_time", expireTime);
return this; return this;
} }
public MessagePayload addMessageExtra(String key, Object value){ public MessagePayload addMessageExtra(String key, Object value) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.getJSONObject("extras").put(key, value); message.getJSONObject("extras").put(key, value);
return this; return this;
} }
public MessagePayload addDevices(String... devices){ public MessagePayload addDevices(String... devices) {
if(devices == null || devices.length == 0) if (devices == null || devices.length == 0)
return this; return this;
JSONArray d = _data.getJSONArray("devices"); JSONArray d = _data.getJSONArray("devices");
for(String device:devices){ for (String device : devices) {
d.add(device); d.add(device);
} }
return this; return this;
} }
public JSONObject getJSONMessage(String userId) { public JSONObject getJSONMessage(String userId) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return null; return null;
if(StringUtils.isBlank(userId)){ if (StringUtils.isBlank(userId)) {
message.put("user_id", ""); message.put("user_id", "");
} else { } else {
...@@ -261,11 +279,12 @@ public class MessagePayload { ...@@ -261,11 +279,12 @@ public class MessagePayload {
} }
return message; return message;
} }
public byte[] getMessagePayload(){
public byte[] getMessagePayload() {
try { try {
String c = "content="+URLEncoder.encode(_data.toJSONString(), "UTF-8"); String c = "content=" + URLEncoder.encode(_data.toJSONString(), "UTF-8");
return c.getBytes("UTF-8"); return c.getBytes("UTF-8");
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
......
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
...@@ -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;
...@@ -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"));
}
} }
...@@ -3,21 +3,22 @@ ...@@ -3,21 +3,22 @@
*/ */
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
* @team IT Team
* @time 2016年11月5日 * @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");
...@@ -81,73 +82,60 @@ public class FileManipulation { ...@@ -81,73 +82,60 @@ public class FileManipulation {
String temp = ""; String temp = "";
for (int i = 0; i < path.length(); i++) { 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;
} }
/** /**
*
* 黑名单验证 * 黑名单验证
*
* @return
* @author zhanglg * @author zhanglg
* @time 2016年11月5日 * @time 2016年11月5日
* @return
*/ */
public static String validateFile(String filename){ public static String validateFile(String filename) {
String[] extesions=new String[]{"%",";"}; String[] extesions = new String[]{"%", ";"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename); throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
} }
} }
/* String extesionName = Util.getExtensionName(filename); filename = filename.replaceAll("\\.\\./", "");
filename = filename.replaceAll("\\.\\.\\\\", "");
// if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL filename = filename.replaceAll("\\.\\.", "");
// 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);
}*/
/* if(GConstants.FILE_FILTERS.get(extesionName) == null){
throw new LoadExceptions("此类型文件不允许上传:"+filename);
}*/
filename= filename.replaceAll("\\.\\./", "");
filename= filename.replaceAll("\\.\\.\\\\", "");
filename= filename.replaceAll("\\.\\.", "");
return filename; return filename;
} }
public static void check(String filename){ public static void check(String filename) {
String extesionName = Util.getExtensionName(filename); String extesionName = Util.getExtensionName(filename);
if(GConstants.FILE_FILTERS.get(extesionName) == null){ if (GConstants.FILE_FILTERS.get(extesionName) == null) {
throw new LoadExceptions("此类型文件不允许上传:"+filename); throw new LoadException("此类型文件不允许上传:" + filename);
} }
String[] extesions=new String[]{"%",";"}; String[] extesions = new String[]{"%", ";"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename); throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
} }
} }
} }
/** /**
*
* 黑名单验证2 * 黑名单验证2
*
* @return
* @author zhanglg * @author zhanglg
* @time 2016年11月5日 * @time 2016年11月5日
* @return
*/ */
public static String validateFile2(String filename){ public static String validateFile2(String filename) {
String[] extesions=new String[]{".xmls",".propertiey",".jsons"}; String[] extesions = new String[]{".xmls", ".propertiey", ".jsons"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件"); throw new LoadException("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件");
} }
} }
return filename; return filename;
......
...@@ -5,28 +5,35 @@ package com.ejweb.core.utils; ...@@ -5,28 +5,35 @@ package com.ejweb.core.utils;
/** /**
* 上传下载非法的异常抛出 * 上传下载非法的异常抛出
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @team IT Team
* @time 2016年11月6日 * @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; //异常对应的描述信息 *异常对应的返回码
*/
private String retCd;
/**
*异常对应的描述信息
*/
private String msgDes;
public LoadExceptions() { 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;
......
...@@ -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,17 +2,16 @@ package com.ejweb.modules.airline.entity; ...@@ -2,17 +2,16 @@ 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
* @team IT Team
* @time 2016年8月30日 * @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;
...@@ -80,6 +79,4 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl ...@@ -80,6 +79,4 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl
} }
} }
\ No newline at end of file
...@@ -19,15 +19,16 @@ import java.io.*; ...@@ -19,15 +19,16 @@ import java.io.*;
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];
...@@ -38,32 +39,31 @@ public class FileService { ...@@ -38,32 +39,31 @@ public class FileService {
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);
...@@ -75,12 +75,7 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -75,12 +75,7 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
@Override @Override
protected void issueSuccessRedirect(ServletRequest request, protected void issueSuccessRedirect(ServletRequest request,
ServletResponse response) throws Exception { ServletResponse response) throws Exception {
// Principal p = UserUtils.getPrincipal();
// if (p != null && !p.isMobileLogin()){
WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true); WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
// }else{
// super.issueSuccessRedirect(request, response);
// }
} }
/** /**
...@@ -91,13 +86,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -91,13 +86,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
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(); // 输出到控制台
} }
......
...@@ -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
*/ */
...@@ -40,10 +39,10 @@ public class AreaController extends BaseController { ...@@ -40,10 +39,10 @@ public class AreaController extends BaseController {
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,27 +57,14 @@ public class AreaController extends BaseController { ...@@ -58,27 +57,14 @@ 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";
} }
...@@ -86,16 +72,13 @@ public class AreaController extends BaseController { ...@@ -86,16 +72,13 @@ public class AreaController extends BaseController {
@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/";
...@@ -104,28 +87,24 @@ public class AreaController extends BaseController { ...@@ -104,28 +87,24 @@ public class AreaController extends BaseController {
@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)){
// addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
// }else{
areaService.delete(area); areaService.delete(area);
addMessage(redirectAttributes, "删除区域成功"); 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_"; // 默认密钥
...@@ -20,31 +18,25 @@ public class DESPlus ...@@ -20,31 +18,25 @@ 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();
} }
...@@ -52,23 +44,19 @@ public class DESPlus ...@@ -52,23 +44,19 @@ public class DESPlus
/** /**
* 将表示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;
} }
...@@ -78,128 +66,107 @@ public class DESPlus ...@@ -78,128 +66,107 @@ public class DESPlus
* *
* @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