- 加密解密工具类
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;
}
}