单重DES加密较容易破解,为了提高安全性,3重DES加密就是在单重的基础上衍生出来的,一般3重DES用的比较频繁。加密过程为加密-解密-加密。
我一直想找用自己定义密钥的方法来做程序,网上找了很多都找不到,单重倒是有很多,因此只能自己研究研究了,现在拿出来给各位做java的分享
分享,希望各位喜欢。
/**
* 3重DES加密
* @param src
* @param DES_KEY 密钥长度不少于24的倍数位
* @return
*/
public static String EncryptBy3DES(String src,String DES_KEY){
String result=null;
try {
SecureRandom secureRandom=new SecureRandom();
DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes());
SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede");
SecretKey key=secretKeyFactory.generateSecret(sedeKeySpec);
Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key,secureRandom);
byte[] bytesresult=cipher.doFinal(src.getBytes());
result=new sun.misc.BASE64Encoder().encode(bytesresult);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 3重DES解密
* @param src
* @param DES_KEY
* @return
*/
public static String decryptBy3DES(String src,String DES_KEY){
String deresult=null;
try {
SecureRandom secureRandom=new SecureRandom();
DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes());
SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede");
SecretKey key = secretKeyFactory.generateSecret(sedeKeySpec);
Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,key,secureRandom);
byte[] bytesresult=cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(src));
deresult=new String(bytesresult);
} catch (Exception e) {
e.printStackTrace();
}
return deresult;
}
测试:
public class DES_3 {
//定义一个要加密的字符串
private static String src="imooc security 3des";
public static void main(String[] args) {
//调用加密的方法并打印查看结果 System.out.println(EncryptBy3DES(src,"123456781234567812345678"));
//将加密后的结果放入解密的方法,由于是对称加密,因此加解密的密钥都是同一个 System.out.println(decryptBy3DES("lA/dMJvyrb2Q/BtmUKPPEdNwn5+TwCxA","123456781234567812345678")); }
}