基于java类库的3DES加密算法实现

本文转自https://blog.csdn.net/super_cui/article/details/70821138

别看3DES的代码很复杂,其实和DES代码一样,核心代码就那么几行

加密部分的核心
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
return cipher.doFinal(data);

解密部分的核心
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,deskey);
return cipher.doFinal(data);

完整代码

package DES;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class ThreeDESUtil {

   //key 根据实际情况对应的修改
   private final byte[] keybyte="123456788765432112345678".getBytes(); //keybyte为加密密钥,长度为24字节
   private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish
   private SecretKey deskey;
   //生成密钥
   public ThreeDESUtil(){
       deskey = new SecretKeySpec(keybyte, Algorithm);
   }
   //加密
   public byte[] encrypt(byte[] data){
        try {
            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, deskey);
            return cipher.doFinal(data);
        } catch (Exception ex) {
            //加密失败,打日志
            ex.printStackTrace();
        } 
        return null;
   }
   //解密
   public byte[] decrypt(byte[] data){
       try {
            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,deskey);
            return cipher.doFinal(data);
        } catch (Exception ex) {
            //解密失败,打日志
            ex.printStackTrace();
        } 
        return null;
   }

   public static void main(String[] args) throws Exception {
       ThreeDESUtil des=new ThreeDESUtil();
       String req ="cryptology";

       String toreq  = toHexString(req);
       System.err.println("十六进制报文=="+toreq);
       byte[] srcData=req.toString().getBytes("utf-8");
       byte[] encryptData=des.encrypt(srcData);
       System.out.println("密文:");
       if(encryptData!=null){
           for(int i=0;i<encryptData.length;i++){
               String hex=Integer.toHexString(encryptData[i]);
               if(hex.length()>1)
                System.out.print(hex.substring(hex.length()-2)+" ");
               else
                System.out.print("0"+hex+" ");
           }
       }
       System.out.println("");
       System.out.println("明文:"+req);
   }

   // 转化字符串为十六进制编码
   public static String toHexString(String s) {
       String str = "";
       for (int i = 0; i < s.length(); i++) {
           int ch = (int) s.charAt(i);
           String s4 = Integer.toHexString(ch);
           str = str + s4;
       }
       return str;
   }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值