1、3DES加解密
代码语言:javascript复制/**
* Author:jianbo
*
* <p>* Create Time:2019/7/5 17:16
*
* <p>* Email:1245092675@qq.com
*
* <p>* Describe:3DES加解密
*
* <p>* eg: String msg = "3DES加密解密案例";
* <p>
* System.out.println("【加密前】:" msg);
* <p>
* //-----加密------
* <p>
* byte[] secretArr = SecretUtils.encryptMode(msg.getBytes());
* <p>
* System.out.println("【加密后】:" new String(secretArr));
* <p>
* //-----解密------
* <p>
* byte[] myMsgArr = SecretUtils.decryptMode(secretArr);
* <p>
* System.out.println("【解密后】:" new String(myMsgArr));
*/
public class SecretUtils {
//定义加密算法,有DES、DESede(即3DES)、Blowfish
private static final String Algorithm = "DESede";
private static final String PASSWORD_CRYPT_KEY = "V7OIDy10yhwnfLI10yutvtgjUYPewVZQ";
//编码
private static final String CHARSET = "UTF-8";
/**
* 加密方法
*
* @param src 源数据的字节数组
* @return
*/
public static byte[] encryptMode(byte[] src) {
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
//实例化负责加密/解密的Cipher工具类
Cipher c1 = Cipher.getInstance(Algorithm);
//初始化为加密模式
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
/**
* 解密函数
*
* @param src 密文的字节数组
* @return
*/
public static byte[] decryptMode(byte[] src) {
try {
SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
//初始化为解密模式
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
/*
* 根据字符串生成密钥字节数组
* @param keyStr 密钥字符串
* @return
* @throws UnsupportedEncodingException
*/
public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
//声明一个24位的字节数组,默认里面都是0
byte[] key = new byte[24];
//将字符串转成字节数组
byte[] temp = keyStr.getBytes(CHARSET);
/*
* 执行数组拷贝
* System.arraycopy(源数组,从源数组哪里开始拷贝,目标数组,拷贝多少位)
*/
if (key.length > temp.length) {
//如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
System.arraycopy(temp, 0, key, 0, temp.length);
} else {
//如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
System.arraycopy(temp, 0, key, 0, key.length);
}
return key;
}
}