java加解密之3重DES

    单重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")); }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值