package com.spring.sec.util; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * 项目名称:**** * 类名称:3DESEncryptUtil * 类描述: 3des 加密工具类 * */ public class 3DESEncryptUtil { //key 根据实际情况对应的修改 private final static byte[] keybyte="123456788765432112345678".getBytes(); //keybyte为加密密钥,长度为24字节 private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish private static SecretKey deskey; ///生成密钥 static{ deskey = new SecretKeySpec(keybyte, Algorithm); } //加密 public static String encrypt(byte[] data){ try { Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, deskey); byte[] encryptedByteArray = cipher.doFinal(data); // 加密运算之后 将byte[]转化为base64的String BASE64Encoder enc = new BASE64Encoder(); return enc.encode(encryptedByteArray); } catch (Exception ex) { //加密失败,打日志 ex.printStackTrace(); } return null; } //解密 public static byte[] decrypt(String data){ try { Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE,deskey); BASE64Decoder dec = new BASE64Decoder(); byte[] encryptedByteArray = dec.decodeBuffer(data); return cipher.doFinal(encryptedByteArray); } catch (Exception ex) { //解密失败,打日志 ex.printStackTrace(); } return null; } public static void main(String[] args) throws Exception { //DESEncryptUtil des=new DESEncryptUtil(); String req ="ASLKSDGLA古惑世界杯中罭蠛西藏天边 槿七七葬花任免11!@¥!%!¥!1"; String toreq =toHexString(req); System.err.println("十六进制报文===="+toreq); byte [] srcData=req.toString().getBytes("utf-8"); String encryptData=DESEncryptUtil.encrypt(srcData); System.out.println("密文:"+encryptData); System.out.println(""); byte[] decryptData=DESEncryptUtil.decrypt(encryptData); System.out.println("明文:"+new String(decryptData)); } // 转化字符串为十六进制编码 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; } }
注意:本文归作者所有,未经作者允许,不得转载