1. 程式人生 > >基於java類庫的3DES加密演算法實現

基於java類庫的3DES加密演算法實現

別看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; } }