一、代码如下:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.net.util.Base64;
import sun.misc.BASE64Decoder;
public class Decrypt {
private static SimpleDateFormat dateFormat;
/** 安全密钥 */
//private static String keyData = "ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstwxyz0123456789-_.";
private static String keyData = "20190809";
public synchronized static String formatAll(Date date,String timeType) {
dateFormat=new SimpleDateFormat(timeType);
return dateFormat.format(date);
}
public synchronized static Date formatDate(String date,String timeType)throws Exception {
dateFormat=new SimpleDateFormat(timeType);
return dateFormat.parse(date);
}
//static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
final static byte[] IV = new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
/**
* 解密方法
*
* @param data
* 解密前字符串
* @return 解密后字符串
*
*/
public static String decryptKey(String data) throws Exception
{
// DES 解密阶段
Date date = new Date();
String dateTime = formatAll(date,"yyyyMMdd");
// 秘钥暂定当前日期
String key = dateTime;//这个秘钥在这我用的是从配置文件中读取的,你们可以直接用字符串代替,如:20190809
// BASE64解码
//byte[] datasource = new BASE64Decoder().decodeBuffer(data);
byte[] datasource = safeUrlBase64Decode(data);
//秘钥暂定当前日期
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
byte[] str = cipher.doFinal(datasource);
return new String(str, "UTF-8");
}
/**
* 加密方法
*
* @param data
* 加密前字符串
* @return 加密后字符串
*
*/
public static String encryptKey(String data) throws Exception
{
// DES 解密阶段
Date date = new Date();
String dateTime = formatAll(date,"yyyyMMdd");
String key = dateTime;// 秘钥
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
byte[] desBytes = cipher.doFinal(data.getBytes("UTF-8"));
//BASE64编码阶段
//return Base64.encodeBase64String (desBytes);
return safeUrlBase64Encode(desBytes);
}
public static String encrypt(String encryptString, String encryptKey) throws Exception
{
// DES 解密阶段
Date date = new Date();
String dateTime =formatAll(date,"yyyyMMdd");
SecretKeySpec key = new SecretKeySpec(dateTime.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/noPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
return Base64.encodeBase64String(encryptedData);
}
public static String safeUrlBase64Encode(byte[] data){
String encodeBase64 = Base64.encodeBase64String(data);
String safeBase64Str = encodeBase64.replace('+', '-');
safeBase64Str = safeBase64Str.replace('/', '_');
safeBase64Str = safeBase64Str.replaceAll("=", "");
safeBase64Str = safeBase64Str.replaceAll("[\\s*\t\n\r]", "");
return safeBase64Str;
}
public static byte[] safeUrlBase64Decode(String safeBase64Str) throws IOException{
String base64Str = safeBase64Str.replace('-', '+');
base64Str = base64Str.replace('_', '/');
int mod4 = base64Str.length()%4;
if(mod4 > 0){
base64Str = base64Str + "====".substring(mod4);
}
return new BASE64Decoder().decodeBuffer(base64Str);
}
/* public static String encrypt(String data) throws Exception
{
// 秘钥暂定为当前日期
// DES 解密阶段
Date date = new Date();
String dateTime =formatAll(date,"yyyyMMdd");
// DES 解密阶段
dateTime = df.format(date).toString();
String key = "abc123";
KeyGenerator k = KeyGenerator.getInstance("DES");
k.init(56);
SecretKey sk = k.generateKey();
byte[] bytes = sk.getEncoded();
SecretKey cs = new SecretKeySpec(bytes, "DES");
Cipher ci = Cipher.getInstance("DES/ECB/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, cs);
byte[] desBytes = ci.doFinal(data.getBytes("UTF-8"));
return Base64.encodeBase64String(desBytes);
}*/
}
二、注意事项:客户端加密,服务端解密,但是有的人写的文章的话,加密后会生成各种==、+、换行的字符,在传递过程中容易丢失跟转译,所以在此写了 safeUrlBase64Encode()、safeUrlBase64Decode()这两个方法来规避这种问题
三、测试类代码:
public static void main(String[] args) throws Exception {
//System.out.println("ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstwxyz0123456789-_.".length());
StringBuffer sbuffer = new StringBuffer();
sbuffer.append("1asdfasdf");
String str = "";
try {
str = Decrypt.encryptKey(sbuffer.toString());
System.out.println("用密钥[20190809]进行加密后的密文为\n[" + str + "]");
} catch (Exception e1) {
e1.printStackTrace();
}
// 需解密
String data = null;
// 开始解密文件
try {
data = Decrypt.decryptKey(str);
System.out.println("解密后的文件内容:\n[" + data + "]");
} catch (Exception e) {
System.out.println("解密文件时出现异常,异常信息为[" + e.getMessage() + "]");
}
}
四、运行结果如下: