DES加密生成的是byte[]数组,我们直接new String()转换为String,然后传输到后台,后台解密是将该String字符串使用getBytes()方法转化为byte[],再DES解密,这个过程会使解密失败,工程紧遇到的坑。
为此,我们在加密过程中采用base64编码生成密文String,然后后端base64解码再解密,即可正确的获得明文。
import sun.misc.BASE64Encoder;
import org.junit.Test;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
/**
* @author zhoujin
* @date 2018-07-04
*/
public class DESEncryptUtil {
/**
* 加密以及解密(对称性加密算法)
* @param datasource byte[] 加密内容
* @param password String 加密钥匙
* @return String 返回加密后结果
*/
public static String encrypt(byte[] datasource, String password) {
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
//正式执行加密操作
byte[] bytes=cipher.doFinal(datasource);
//base64编码
return new BASE64Encoder().encode(bytes);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param src byte[] 密文
* @param password String 解密钥匙
* @return String 解密后结果
* @throws Exception
*/
public static String decrypt(byte[] src, String password){
try {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
byte[] bytes= cipher.doFinal(src);
return new String(bytes);
} catch (Throwable e){
e.getStackTrace();
}
return null;
}
@Test
public void test() throws IOException {
Corporation corporation=new Corporation();
corporation.setOrganizationCodeURL("http://www.baidu.com");
String s1=DESEncryptUtil.encrypt(corporation.getOrganizationCodeURL().getBytes(),"9588888888880288");
String s2=DESEncryptUtil.decrypt(new BASE64Decoder().decodeBuffer(s1),"9588888888880288");
}
}