JAVA DES加密/解密

  • 加密解密工具类

         

package com.sinosoft.lis.midplat.channel.security.ICBC;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;

public class CodeUtil {
	private static Logger log = Logger.getLogger(CodeUtil.class);
	/**
	 * 加密
	 * @param input 输入字节数据
	 * @param key 密钥
	 * @return
	 */
	public static byte[] encode(byte[] input, byte[] key){
		SecretKey secretKey =  new SecretKeySpec(key,"DES");
		log.info("加密前的内容:"+new String(input));
		byte[] out = null;
		try {
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			
			out = cipher.doFinal(input);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("加密后的内容:"+new String(out));
		return out;
	}
	
	/**
	 * 
	 * @param input 输入字节数据
	 * @param key 密钥
	 * @return
	 */
	public static byte[] decode(byte[] input, byte[] key){
		SecretKey secretKey =  new SecretKeySpec(key,"DES");
		log.info("解密前的内容:"+new String(input));
		byte[] out = null;
		try {
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			
			out = cipher.doFinal(input);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("解密后的内容:"+new String(out));
		return out;
	}
}

 

  • 测试类

   

package com.sinosoft.lis.midplat.channel.security.ICBC;
/**
 * 测试
 * @author Administrator
 *
 */
public class CodeUtilTest {
	public static void main(String[] args) {
		String srcKey = "4f9d6426865d0461";//16进制字符串
		byte[] key = toByteArray(srcKey);
		String strStr = "Hello world!";
		
		byte[] descStr = CodeUtil.encode(strStr.getBytes(), key);
		
		CodeUtil.decode(descStr, key);
	
	}
	// 将16进制字符串转换成字节码
	private static byte[] toByteArray(String srcKey) {
		byte[] descKey = new byte[8];
		if (srcKey == null || srcKey.length() != 16) {
			return null;
		}

		for (int nIndex = 0; nIndex < 8; nIndex++) {
			int n = Integer.parseInt(srcKey.substring(nIndex * 2,nIndex * 2 + 2), 16);
			descKey[nIndex] = (byte) n;
		}

		return descKey;
	}
	
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值