DES+base64加密解密

一、代码如下:

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() + "]");

		}
		
	}

四、运行结果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值