Java對稱加密算法


對稱加密算法概念

  • 加密密鑰和解密密鑰相同,大部分算法加密揭秘過程互逆。

  • 特點:算法公開、(相比非對稱加密)計算量小、加密速度快、效率高。

  • 弱點:雙方都使用同樣的密鑰,安全性得不到保證。

常用對稱加密算法

  • DES(Data Encryption Standard)

  • 3DES(DES加強版,使用3次DES計算,Triple DES,DESede)

  • AES(Advanced Encryption Standard,3DES加強版)

JDK版DES/3DES/AES算法調用模板

1. 生成密鑰

//KeyGenerator,密鑰生成器 KeyGenerator keyGen = KeyGenerator.getInstance("DES");//算法:DES,DESede,AES //初始化密鑰生成器 keyGen.init(56); //各算法密鑰長度不同,參見說明 //生成密鑰 SecretKey secretKey = keyGen.generateKey(); //生產字節碼數據 byte[] key = secretKey.getEncoded();

說明:
1.通過「KeyGenerator.getInstance("DES")」生成密鑰,
2.參數為算法名稱:分別對應DES、DESede(即3DES)、AES
3.每種算法密鑰長度參數:DES(56),3DES(112,168),AES(192,256)

2.加/解密

//通過字節碼數據key 恢復密鑰 SecretKey secretKey = new SecretKeySpec(key, "DES"); //Cipher完成加密/解密工作 Cipher cipher = Cipher.getInstance("DES"); //根據密鑰,對Cipher初始化,並選擇加密還是解密 cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] result = cipher.doFinal(data);

1.加密或解密都通過cipher.init()設置,參數:ENCRYPT_MODE/DECRYPT_MODE
2.加密或解密都通過cipher.doFinal() 執行,獲得byte[]類型結果。

代碼示例

 
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class DESUtil { /* * 生成密鑰 */ public static byte[] initKey() throws Exception{ KeyGenerator keyGen = KeyGenerator.getInstance("DES"); keyGen.init(56); SecretKey secretKey = keyGen.generateKey(); return secretKey.getEncoded(); } /* * DES 加密 */ public static byte[] encrypt(byte[] data, byte[] key) throws Exception{ SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherBytes = cipher.doFinal(data); return cipherBytes; } /* * DES 解密 */ public static byte[] decrypt(byte[] data, byte[] key) throws Exception{ SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] plainBytes = cipher.doFinal(data); return plainBytes; } //Test public static void main(String[] args) throws Exception { byte[] desKey = DESUtil.initKey(); System.out.println("DES KEY : " + BytesToHex.fromBytesToHex(desKey)); byte[] desResult = DESUtil.encrypt(DATA.getBytes(), desKey); System.out.println(DATA + ">>>DES 加密結果>>>" + BytesToHex.fromBytesToHex(desResult)); byte[] desPlain = DESUtil.decrypt(desResult, desKey); System.out.println(DATA + ">>>DES 解密結果>>>" + new String(desPlain)); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM