最近做手机银行需要加密一些东西,需要用到3DES加密,简单的了解了一下。
涉及的几个概念
原文:需要加密的内容,加密时需要转换成字符数组
密文:加密后的内容,3DES加密后产生的是每8位一个单元的二进制字符数组
加密算法:加密时使用的算法,3DES加密使用的是DESede算法
加密秘钥:长度为24字节的字符数组,是否保密就看秘钥保存的是否隐蔽
前准备:
3DES加密秘钥如果不是24位会报异常,为了解决这个问题,统一一下秘钥长度
/*
* 根据 密钥字符串生成密钥字节数组
*
* @param keyStr 密钥字符串
*
* @return
*
* @throws UnsupportedEncodingException
*/
public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
byte[] key = new byte[24]; // 声明一个24位的字节数组,默认里面都是0
byte[] temp = keyStr.getBytes("UTF-8"); // 将字符串转成字节数组
/*
* 执行数组拷贝 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;
}
加密
/**
* 加密方法
*
* @param originalText
* 源数据的字节数组
* @return
*/
public static byte[] encryptMode(byte[] originalText) {
try {
SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm); // 生成密钥
Cipher cipher = Cipher.getInstance(Algorithm); // 实例化负责加密/解密的Cipher工具类
cipher.init(Cipher.ENCRYPT_MODE, deskey); // 初始化为加密模式
return cipher.doFinal(originalText);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2