需要引入jar包:commons-codec-1.7.jar
package com.gnet.mis.util;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gnet.mis.framework.util.Consts;
/**
* 密码工具类。
*
*/
public class CryptoUtils {
protected static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
public static void main(String[] args) {
byte[] key = generatorKey(CryptoType.AES);
System.out.println(Base64.encodeBase64String(key));
try {
String str = "1";
String cr = encrypt(str, Consts.COOKIE_KEY, CryptoType.AES);
System.out.println("cr=" + cr);
String de = decrypt(cr, Consts.COOKIE_KEY, CryptoType.AES);
System.out.println("de=" + de);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 使用信息摘要加密算法加密
*
* @param type
* @param content
* @return
* @throws NoSuchAlgorithmException
*/
public final static byte[] messageDigest(MessageDigestType type, String content) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(type.name());
md.update(content.getBytes());
return md.digest();
}
/**
* 加密数据
*
* @param data 待加密数据
* @param key 密钥
* @param type 加密类型
* @return
* @throws Exception
*/
public static String encrypt(String data, String key, CryptoType type) throws Exception {
Key k = toKey(Base64.decodeBase64(key), type); // 还原密钥
// 使用PKCS7Padding填充方式,这里就得这么写了(即调用BouncyCastle组件实现)
// Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
Cipher cipher = Cipher.getInstance(type.name()); // 实例化Cipher对象,它用于完成实际的加密操作
cipher.init(Cipher.ENCRYPT_MODE, k); // 初始化Cipher对象,设置为加密模式
return Base64.encodeBase64String(cipher.doFinal(data.getBytes())); // 执行加密操作。加密后的结果通常都会用Base64编码进行传输
}
/**
* 解密数据
*
* @param data 待解密数据
* @param key 密钥
* @param type 解密类型
* @return
* @throws Exception
*/
public static String decrypt(String data, String key, CryptoType type) throws Exception {
Key k = toKey(Base64.decodeBase64(key), type);
Cipher cipher = Cipher.getInstance(type.name());
cipher.init(Cipher.DECRYPT_MODE, k); // 初始化Cipher对象,设置为解密模式
return new String(cipher.doFinal(Base64.decodeBase64(data))); // 执行解密操作
}
/**
* 转换密钥
*/
public static Key toKey(byte[] key, CryptoType type) throws Exception {
return new SecretKeySpec(key, type.name());
}
/**
* @param type
* @return
*/
public static byte[] generatorKey(CryptoType type) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(type.name());
kgen.init(128, new SecureRandom());
return kgen.generateKey().getEncoded();
}
catch (NoSuchAlgorithmException e) {
logger.error("generator key error", e);
e.printStackTrace();
}
return null;
}
/**
* 使用128位解密
*
* @param type 解密算法
* @param data
* @param key
* @return
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static byte[] decrypt(CryptoType type, byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
SecretKey secretKey = new SecretKeySpec(key, type.name());
return decrypt(type, data, secretKey);
}
/**
* 使用128位解密
*
* @param type 解密算法
* @param data
* @param password
* @return
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static byte[] decrypt(CryptoType type, byte[] data, String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return decrypt(type, data, password.getBytes());
}
/**
* 使用128位解密
*
* @param type 解密算法
* @param content
* @param password
* @return
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static byte[] decrypt(CryptoType type, String content, String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return decrypt(type, content.getBytes(), password.getBytes());
}
/**
* 解密
*
* @param type 解密算法
* @param data
* @param secretKey
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
private static byte[] decrypt(CryptoType type, byte[] data, SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// 得到解密器
Cipher cipher = Cipher.getInstance(type.name());
// 用指定的密钥和模式初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// 解密
return cipher.doFinal(data);
}
/**
* 使用128位机密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt(CryptoType type, String content, byte[] key) {
return encrypt(type, content.getBytes(), key);
}
/**
* 使用128位加密
*
* @param data 需要加密的内容
* @param key 加密密码
* @return
*/
public static byte[] encrypt(CryptoType type, byte[] data, byte[] key) {
SecretKeySpec sks = new SecretKeySpec(key, type.name());
// 加密随机数生成器 (RNG)
// SecureRandom sr = new SecureRandom(key);
return encrypt(type, data, sks); // 加密
}
/**
* 使用128位机密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt(CryptoType type, String content, String password) {
return encrypt(type, content.getBytes(), password.getBytes()); // 加密
}
/**
* 加密
*
* @param type
* @param data
* @param secretKey
* @return
*/
public static byte[] encrypt(CryptoType type, byte[] data, SecretKey secretKey) {
// SecretKey sk = new DESedeKeySpec();
// SecretKeyFactory sk = SecretKeyFactory.getInstance(type.name());
// SecretKeySpec sks = new SecretKeySpec(secretKey.getEncoded(), type.name());
SecureRandom sr = new SecureRandom();
try {
Cipher cipher = Cipher.getInstance(type.name());// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);// 初始化
return cipher.doFinal(data); // 加密
}
catch (NoSuchAlgorithmException e) {
logger.error("encrypt error", e);
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
logger.error("encrypt error", e);
e.printStackTrace();
}
catch (InvalidKeyException e) {
logger.error("encrypt error", e);
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
logger.error("encrypt error", e);
e.printStackTrace();
}
catch (BadPaddingException e) {
logger.error("encrypt error", e);
e.printStackTrace();
}
return null;
}
public enum CryptoType {
AES, DES;
}
public enum MessageDigestType {
MD5, SHA
}
}
package com.gnet.mis.util;
import com.gnet.mis.framework.util.Consts;
import com.gnet.mis.util.CryptoUtils.CryptoType;
/**
* 加密解密算法
*
*/
public class SyncInterfaceUtil {
public SyncInterfaceUtil() {
}
/**
* 解析密钥
* passwordCode生成规则:使用dsc加密算法,将时间的转化为长整型(从1970年1月1日起的毫秒的数量表示日期)+“MIS”+MIS操作人员loginID
* @param passwordCode
* @return
*
*/
public static boolean isValidPasswordCode(String base64_passwordCode) {
try {
if(base64_passwordCode == null || "".equals(base64_passwordCode)){
return false;
}
//key
byte[] key = ByteUtils.toByteArray(Consts.SYNC_INTERFACE_PWD_REPLACE_KEY);
byte[] data = ByteUtils.toByteArray(base64_passwordCode);
String passwordCode = "";
try {
passwordCode = new String(CryptoUtils.decrypt(CryptoType.AES, data, key));
System.out.println(passwordCode);
}
catch (Exception e) {
// e.printStackTrace();
return false;
}
}
catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 加密密钥
/ * passwordCode生成规则:使用dsc加密算法,将时间的转化为长整型(从1970年1月1日起的毫秒的数量表示日期)+“ROADSHOW”+路演操作人员loginID
* @param passwordCode
* @return base64_passwordCode
*/
public static String encryptPasswordCode(String passwordCode){
String base64_passwordCode = "";
try {
//key
byte[] key = ByteUtils.toByteArray(Consts.SYNC_INTERFACE_PWD_REPLACE_KEY);
byte[] data = CryptoUtils.encrypt(CryptoType.AES, passwordCode, key);
base64_passwordCode = ByteUtils.toHexString(data);
}
catch (Exception e) {
e.printStackTrace();
}
return base64_passwordCode;
}
}
package com.gnet.mis.util;
import org.apache.commons.codec.binary.Base64;
/**
* 处理byte工具类
*
*/
public class ByteUtils {
/**
* 将byte[]转换16进制数
*
* @param bytes 字节数组
* @return
*/
public static String toHexString(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* 将base64字符串转换为数组
*
* @param base64String
* @return
*/
public static byte[] toByteArray(String base64String) {
return Base64.decodeBase64(base64String);
}
}