JAVA加密算法(3)- 對稱加密算法(DES、3DES、AES)

對稱加密算法概念

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

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

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

經常使用對稱加密算法

  • DES(Data Encryption Standard)加密

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

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

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)ci

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[]類型結果。get

代碼示例

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));
    }
}
相關文章
相關標籤/搜索