在项目上很多时候都需要加密和解密,这时候就来了加密的方式我了解的加密方式有apache自带的Base64加密方式和Base64Encode一般只用第一种加密方式。以下就是加密方式的代码
/**
* @Title: GCloudBase64Util.java
* @Package com.lc.gcloud.framework.util
* @Description: TODO(用一句话描述该文件做什么)
* @author Thinkpad
* @date 2015年6月25日 上午8:43:40
* @version V1.0
*/
package com.lc.gcloud.framework.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
/**
* @ClassName: GCloudBase64Util
* @Description: Base64加密解密帮助类(默认编码为utf-8)
* @author wangwx
* @date 2015年6月25日 上午8:43:40
*
*/
public class GCloudBase64Util {
// 日志
private static Log log = LogFactory.getLog(GCloudBase64Util.class);
private static GCloudBase64Util base64Util = null;
// 加密键
private static final String key = "apps2015";
public static synchronized GCloudBase64Util getInstance() {
if (base64Util == null) {
base64Util = new GCloudBase64Util();
}
return base64Util;
}
/**
*
* BASE64加密 (默认编码为utf-8)
*
* @param key
* 加密的字符串
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptBASE64(String key) {
byte[] strForByte = null;
String encryptStr = null;
if (key != null && key != "") {
try {
strForByte = key.getBytes("utf-8");
encryptStr = new String(Base64.encodeBase64(strForByte));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
}
return encryptStr;
}
/**
*
* BASE64解密 (默认编码为utf-8)
*
* @param key
* @return
* @throws Exception
*/
public static String decryptBASE64(String key) {
String encodeValue = null;
if (key != null && key != "") {
try {
byte[] keyForByte = key.getBytes("UTF-8");
byte[] decodeResult = Base64.decodeBase64(keyForByte);
encodeValue = new String(decodeResult, "UTF-8");
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
}
return encodeValue;
}
/**
*
* BASE64加密
*
* @param key
* 加密的字符串
* @param charset
* 要加密的编码格式
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptBASE64(String key, String charset) {
String encryptStr = null;
// 默认编码格式为urf-8
if (charset.isEmpty()) {
charset = "utf-8";
}
if (key != null && key != "") {
try {
byte[] strForByte = key.getBytes(charset);
encryptStr = new String(Base64.encodeBase64(strForByte));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
}
return encryptStr;
}
/**
*
* BASE64解密
*
* @param key
* 解密的字符串
* @param charset
* 解密的编码格式
* @return
* @throws Exception
*/
public static String decryptBASE64(String key, String charset) {
String encodeValue = null;
// 默认编码格式为urf-8
if (charset.isEmpty()) {
charset = "utf-8";
}
try {
byte[] keyForByte = key.getBytes(charset);
byte[] decodeResult = Base64.decodeBase64(keyForByte);
encodeValue = new String(decodeResult, charset);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
return encodeValue;
}
}