加解密的扩展类:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
加密 密钥:
private static final String keyStr = "safetyprod";//加密密钥
private static final String algorithm = "DESede"; ///定义加密算法,有DES、DESede(即3DES)、Blowfish
将加密密钥转为3des加解密所必须的24字节码:
/**
* 将加密密钥转为为字节数组
* 3des加密的密钥必须要24字节
* @param keyStr 加密密钥字符串
* @return
*/
public static byte[] build3DesKeyByte(String keyStr){
byte []keyByte = new byte[24];//默认数据为0
try {
byte []temp = keyStr.getBytes("UTF-8");
/*
* 执行数组拷贝
* System.arraycopy(源数组,从源数组哪里开始拷贝,目标数组,拷贝多少位)
*/
if(keyByte.length > temp.length){
//如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
System.arraycopy(temp, 0, keyByte, 0, temp.length);
}else{
//如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
System.arraycopy(temp, 0, keyByte, 0, keyByte.length);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keyByte;
}
3des加密
/**
* 3DES加密
* @param srcStr 将加密的字符串
* @return
*
*/
public static byte[] encrypt3Des(byte[] srcStrByte) {
byte[] keyByte = build3DesKeyByte(keyStr);
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keyByte, algorithm);
// 加密
Cipher c1 = Cipher.getInstance(algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(srcStrByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3des解密
/**
* 3des解密
* @param srcStr
* @return
*/
public static byte[] decrypt3Des(byte[] srcStrByte) {
byte[] keyByte = build3DesKeyByte(keyStr);
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keyByte, algorithm);
// 加密
Cipher c1 = Cipher.getInstance(algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(srcStrByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}