package com.google.cryptology;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @ClassName: SecUtil
* @Description: 加密 解密 数据库信息
* @version V1.0
*/
public class SecUtil {
private static final Logger logger = LoggerFactory.getLogger(SecUtil.class);
/**
* 自定义 KEY
*/
private static final byte[] keybytes = UUID.randomUUID().toString().getBytes();
public static void main(String[] args) {
BufferedReader reader;
try {
String st = "";
do{
if("".equals(st)) {
logger.info("AES加密与解密操作:");
logger.info("\"E\":加密 \t\"D\":解密\t\t\"Q\":退出");
logger.info("请输入操作代码:");
}
reader = new BufferedReader(new InputStreamReader(System.in));
st = reader.readLine();
if("E".equalsIgnoreCase(st)) {
logger.info("请输入待加密字符串:");
st = reader.readLine();
if(!"".equals(st.trim())) {
logger.info("加密前:" + st.trim());
logger.info("加密后:" + encrypt(st.trim()) + "\n\n");
}
st = "";
}else if("D".equalsIgnoreCase(st)) {
logger.info("请输入待解密字符串:");
st = reader.readLine();
if(!"".equals(st.trim())) {
logger.info("解密前:" + st.trim());
logger.info("解密后:" + decrypt(st.trim()) + "\n\n");
}
st = "";
}
} while(!st.equalsIgnoreCase("Q"));
} catch (Exception e) {
logger.error("main() Exception", e);
}
}
/**
* @Title: encrypt
* @author yunlin.liu
* @Description: 加密
* @param @param value
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String encrypt(String value) {
String s = null;
int mode = Cipher.ENCRYPT_MODE;
try {
Cipher cipher = initCipher(mode);
byte[] outBytes = cipher.doFinal(value.getBytes());
s = String.valueOf(Hex.encodeHex(outBytes));
} catch (Exception e) {
logger.error("encrypt() Exception", e);
}
return s;
}
/**
* @Title: decrypt
* @author yunlin.liu
* @Description: 解密
* @param @param value
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String decrypt(String value) {
String s = null;
int mode = Cipher.DECRYPT_MODE;
try {
Cipher cipher = initCipher(mode);
byte[] outBytes = cipher.doFinal(Hex.decodeHex(value.toCharArray()));
s = new String(outBytes);
} catch (Exception e) {
logger.error("decrypt() Exception", e);
}
return s;
}
/**
* @Title: initCipher
* @author yunlin.liu
* @Description: 初始化密码
* @param @param mode
* @param @return
* @param @throws NoSuchAlgorithmException
* @param @throws NoSuchPaddingException
* @param @throws InvalidKeyException 设定文件
* @return Cipher 返回类型
* @throws
*/
private static Cipher initCipher(int mode) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Key key = new SecretKeySpec(keybytes, "AES");
cipher.init(mode, key);
return cipher;
}
}