DES/3DES/AES 三種對稱加密算法實現(xiàn)

1. 簡單介紹

3DES(或稱為Triple DES)是三重數(shù)據(jù)加密算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當(dāng)于是對每個數(shù)據(jù)塊應(yīng)用三次DES加密算法。由于計算機運算能力的增強,原版DES密碼的密鑰長度變得容易被暴力破解;3DES即是設(shè)計用來提供一種相對簡單的方法,即通過增加DES的密鑰長度來避免類似的攻擊,而不是設(shè)計一種全新的塊密碼算法。

2. 對稱加密

2.1 介紹

對稱密碼算法是當(dāng)今應(yīng)用范圍最廣,使用頻率最高的加密算法。它不僅應(yīng)用于軟件行業(yè),在硬件行業(yè)同樣流行。各種基礎(chǔ)設(shè)施凡是涉及到安全需求,都會優(yōu)先考慮對稱加密算法。對稱密碼算法的加密密鑰和解密密鑰相同,對于大多數(shù)對稱密碼算法,加解密過程互逆。

  • 特點:算法公開、計算量小、加密速度快、加密效率高。

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

對稱密碼有流密碼和分組密碼兩種,但是現(xiàn)在普遍使用的是分組密碼:

2.2 分組密碼工作模式

  • ECB:電子密碼本(最常用的,每次加密均產(chǎn)生獨立的密文分組,并且對其他的密文分組不會產(chǎn)生影響,也就是相同的明文加密后產(chǎn)生相同的密文)
  • CBC:密文鏈接(常用的,明文加密前需要先和前面的密文進行異或運算,也就是相同的明文加密后產(chǎn)生不同的密文)
  • CFB:密文反饋
  • OFB:輸出反饋
  • CTR:計數(shù)器

2.3 常用對稱密碼:

  • DES(Data Encryption Standard,數(shù)據(jù)加密標(biāo)準(zhǔn))
  • 3DES(Triple DES、DESede,進行了三重DES加密的算法)
  • AES(Advanced Encryption Standard,高級數(shù)據(jù)加密標(biāo)準(zhǔn),AES算法可以有效抵制針對DES的攻擊算法

3. DES / 3DES / AES 三種算法實現(xiàn)

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

import com.newland.csf.common.business.IBusinessComponent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 
 * 
 * 
 */
public class TripleDes  {

    //指定要使用的算法  DES / 3DES / AES 分別對應(yīng)的 值為: DES / DESede / AES
    public static final String ALGORITHM_3DES = "DESede";

    /**
     * 解密算法
     * @param hexString 密文手機號
     * @param skString  密鑰
     * @return
     * @throws Exception
     */
    public static String tripleDesDecrypt(String skString, String hexString) throws Exception {
        SecretKey secretKey = new SecretKeySpec(fromHexString(skString), ALGORITHM_3DES);
        byte[] input = fromHexString(hexString);
        byte[] output = tripleDesDecryptBytes(secretKey, input);
        return new String(output, StandardCharsets.UTF_8);
    }

    /**
     * 加密算法
     * @param hexString 明文手機號
     * @param skString 密鑰
     * @return
     * @throws Exception
     */
    public static String tripleDesEncrypt(String skString, String hexString) throws Exception {
        SecretKey secretKey = new SecretKeySpec(fromHexString(skString), ALGORITHM_3DES);
        byte[] output = tripleDesEncryptBytes(secretKey, hexString.getBytes(StandardCharsets.UTF_8));
        return bytes2Hex(output, false);
    }

    public static String bytes2Hex(byte[] bytes, boolean upperCase) {
        if (bytes == null || bytes.length <= 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return upperCase ? sb.toString().toUpperCase() : sb.toString();
    }

    public static byte[] fromHexString(final String hexString) {
        if ((hexString.length() % 2) != 0) {
            throw new IllegalArgumentException(
                    "hexString.length not is an even number");
        }

        final byte[] result = new byte[hexString.length() / 2];
        final char[] enc = hexString.toCharArray();
        StringBuilder sb = new StringBuilder(2);
        for (int i = 0; i < enc.length; i += 2) {
            sb.delete(0, sb.length());
            sb.append(enc[i]).append(enc[i + 1]);
            result[i / 2] = (byte) Integer.parseInt(sb.toString(), 16);
        }
        return result;
    }

    public static byte[] tripleDesEncryptBytes(SecretKey secretKey, byte[] src) throws Exception {
        Cipher c1 = Cipher.getInstance(ALGORITHM_3DES);
        c1.init(Cipher.ENCRYPT_MODE, secretKey);
        return c1.doFinal(src);
    }

    public static byte[] tripleDesDecryptBytes(SecretKey secretKey, byte[] src) throws Exception {
        Cipher c1 = Cipher.getInstance(ALGORITHM_3DES);
        c1.init(Cipher.DECRYPT_MODE, secretKey);
        return c1.doFinal(src);
    }

    /**
     * 加密文件
     * @param skString
     * @param srcFilePath
     * @param desFilePath
     * @throws Exception
     */
    public static void tripleDesEncryptFile(String skString,String srcFilePath,String desFilePath) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_3DES);
        SecretKey secretKey = new SecretKeySpec(fromHexString(skString), ALGORITHM_3DES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        writeFile(cipher,srcFilePath,desFilePath);
    }

    /**
     * 解密文件
     * @param skString
     * @param srcFilePath
     * @param desFilePath
     * @throws Exception
     */
    public static void tripleDesDecryptFile(String skString,String srcFilePath,String desFilePath) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_3DES);
        SecretKey secretKey = new SecretKeySpec(fromHexString(skString), ALGORITHM_3DES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        writeFile(cipher,srcFilePath,desFilePath);
    }

    private static void writeFile(Cipher cipher,String srcFilePath,String desFilePath) throws Exception{
        byte[] buff = new byte[512];
        byte[] temp = null;
        int len = 0;
        try (FileInputStream fis = new FileInputStream(new File(srcFilePath));
             FileOutputStream fos = new FileOutputStream(new File(desFilePath))) {
            while ((len = fis.read(buff)) > 0) {
                temp = cipher.update(buff, 0, len);
                fos.write(temp);
            }
            temp = cipher.doFinal();
            if (temp != null) {
                fos.write(temp);
            }
        }
    }
}

本文由AnonyStar 發(fā)布,可轉(zhuǎn)載但需聲明原文出處。
仰慕「優(yōu)雅編碼的藝術(shù)」 堅信熟能生巧,努力改變?nèi)松?br> 歡迎關(guān)注微信公賬號 :云棲簡碼 獲取更多優(yōu)質(zhì)文章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容