对称加密算法之 Java 3DES算法应用 附可用工具类

欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!!

  3DES算法简介

  3DES又称Triple DES,是DES加密算法的一种模式,它使用两条不同的56位密钥对数据进行三次加密。

  DES使用56位密钥和密码块的方法,而在密码块的方法中,文本被分成64位大小的文本块然后再进行加密。相对DES,3DES更为安全。

  3DES是DES向AES过渡的加密算法,其具体实现如下:

  设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,M代表明文,C代表密文,这样:

   · 3DES加密过程为:C=Ek3(Dk2(Ek1(M)))。

   · 3DES解密过程为:M=Dk1(Ek2(Dk3©))。

  关于3DES概念性的内容不做过多介绍,大家可以自行百度。

  Maven 依赖

  工具类对于加密后使用Base64进行编码,所以需要依赖Apache Commons Codec。

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  工具类实现

  DES3Util提供了针对文本内容、字节数组内容的加解密实现,DES3Util工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.des;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 * @author Securitit.
 * @note 3DES加密算法实现.
 */
public class DES3Util {
    
    

    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(DES3Util.class);

    /**
     * 数据编码.
     */
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 算法编号.
     */
    public static final String DES3_NAME = "DESEDE";

    /**
     * CBC模式串.
     */
    public static final String DES3_NAME_ECB = "desede/CBC/PKCS5Padding";

    /**
     * 初始向量.
     */
    public static final byte[] DES3_KEY_IV = {
    
     1, 2, 3, 4, 5, 6, 7, 8 };

    /**
     * 根据密码生成Key.要求:密码长度不得小于24.
     * @param des3KeyPwd 密码字符串.
     * @return 3DES密钥.
     * @throws Exception 可能异常.
     */
    public static String generateDes3Key(String des3KeyPwd) throws Exception {
    
    
        DESedeKeySpec des3KeySpec = null;
        SecretKeyFactory keyFactory = null;
        byte[] keyBytes = null;

        des3KeySpec = new DESedeKeySpec(des3KeyPwd.getBytes(CHARSET_UTF8));
        keyFactory = SecretKeyFactory.getInstance(DES3_NAME);
        keyBytes = keyFactory.generateSecret(des3KeySpec).getEncoded();
        return Base64.encodeBase64String(keyBytes);
    }

    /**
     * 对文本内容进行加密.
     * @param plainText 待加密明文内容.
     * @param des3Key 3DES密钥.
     * @return 加密的密文.
     */
    public static String encodeText(String plainText, String des3Key) throws Exception {
    
    
        byte[] des3KeyBytes = null;
        byte[] plainBytes = null;
        byte[] cipherBytes = null;

        try {
    
    
            des3KeyBytes = Base64.decodeBase64(des3Key);
            plainBytes = plainText.getBytes(CHARSET_UTF8);
            cipherBytes = encodeByCbc(plainBytes, des3KeyBytes, DES3_KEY_IV);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
    
    
            logger.error("DES3Util.encodeText.", ex);
            return "";
        }
    }

    /**
     * 对文本密文进行解密.
     * @param cipherText 待解密密文.
     * @param des3Key 3DES密钥.
     * @return 解密的明文.
     */
    public static String decodeText(String cipherText, String des3Key) throws Exception {
    
    
        byte[] des3KeyBytes = null;
        byte[] cipherBytes = null;
        byte[] plainBytes = null;

        try {
    
    
            des3KeyBytes = Base64.decodeBase64(des3Key);
            cipherBytes = Base64.decodeBase64(cipherText);
            plainBytes = decodeByCbc(cipherBytes, des3KeyBytes, DES3_KEY_IV);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.decodeText.", ex);
            return "";
        }
    }

    /**
     * 对字节数组内容进行加密.
     * @param plainText 待加密明文内容.
     * @param dseKey 3DES密钥.
     * @return 加密的密文.
     */
    public static byte[] encodeBytes(byte[] plainBytes, String des3Key) throws Exception {
    
    
        byte[] desKeyBytes = null;
        byte[] cipherBytes = null;

        try {
    
    
            desKeyBytes = Base64.decodeBase64(des3Key);
            cipherBytes = encodeByCbc(plainBytes, desKeyBytes, DES3_KEY_IV);
            return cipherBytes;
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.encodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * 对字节数组密文进行解密.
     * @param cipherText 待解密密文.
     * @param des3Key 3DES密钥.
     * @return 解密的明文.
     */
    public static byte[] decodeBytes(byte[] cipherBytes, String des3Key) throws Exception {
    
    
        byte[] desKeyBytes = null;
        byte[] plainBytes = null;

        try {
    
    
            desKeyBytes = Base64.decodeBase64(des3Key);
            plainBytes = decodeByCbc(cipherBytes, desKeyBytes, DES3_KEY_IV);
            return plainBytes;
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.decodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * 3DES算法使用CBC模式进行加密.
     * @param plainBytes 原文内容.
     * @param des3Key 3DES密钥.
     * @param keyIv 3DES初始向量.
     * @return 加密后的内容.
     * @throws Exception .
     */
    public static byte[] encodeByCbc(byte[] plainBytes, byte[] des3Key, byte[] keyIv) throws Exception {
    
    
        Key deskey = null;
        DESedeKeySpec desSpec = null;
        SecretKeyFactory keyFactory = null;
        Cipher cipher = null;
        IvParameterSpec ivSpec = null;
        byte[] cipherOut = null;

        desSpec = new DESedeKeySpec(des3Key);
        keyFactory = SecretKeyFactory.getInstance(DES3_NAME);
        deskey = keyFactory.generateSecret(desSpec);
        cipher = Cipher.getInstance(DES3_NAME_ECB);
        ivSpec = new IvParameterSpec(keyIv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ivSpec);
        cipherOut = cipher.doFinal(plainBytes);
        return cipherOut;
    }

    /**
     * 3DES算法使用CBC模式进行解密.
     * @param plainBytes 密文内容.
     * @param des3Key 3DES密钥.
     * @param keyIv 3DES初始向量.
     * @return 解密后的内容.
     * @throws Exception .
     */
    public static byte[] decodeByCbc(byte[] plainBytes, byte[] des3Key, byte[] keyIv) throws Exception {
    
    
        Key deskey = null;
        DESedeKeySpec desSpec = null;
        SecretKeyFactory keyFactory = null;
        Cipher cipher = null;
        IvParameterSpec ivSpec = null;
        byte[] cipherOut = null;

        desSpec = new DESedeKeySpec(des3Key);
        keyFactory = SecretKeyFactory.getInstance(DES3_NAME);
        deskey = keyFactory.generateSecret(desSpec);
        cipher = Cipher.getInstance(DES3_NAME_ECB);
        ivSpec = new IvParameterSpec(keyIv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ivSpec);
        cipherOut = cipher.doFinal(plainBytes);
        return cipherOut;
    }

}

  工具类测试

package com.arhorchin.securitit.enordecryption.des;

import java.util.Arrays;

/**
 * @author Securitit.
 * @note TripleDES3Util测试类.
 */
public class DES3UtilTester {
    
    

    public static void main(String[] args) throws Exception {
    
    
        String desKeyPwd = "123456788765432112345678";
        String desKey = null;
        String plainText = "This is 一段明文内容!";
        String cipherText = null;

        System.out.println("----------------------- 获取DES秘钥 -------------------------");
        desKey = DES3Util.generateDes3Key(desKeyPwd);
        System.out.println("秘钥:" + desKey);
        System.out.println();
        // 文本加解密测试.
        System.out.println("----------------------- 文本加解密测试 -------------------------");
        System.out.println("明文:" + plainText);
        cipherText = DES3Util.encodeText(plainText, desKey);
        System.out.println("密文:" + cipherText);
        plainText = DES3Util.decodeText(cipherText, desKey);
        System.out.println("解密明文:" + plainText);
        System.out.println();
        System.out.println("----------------------- 字节数组加解密测试 -------------------------");
        byte[] plainBytes = plainText.getBytes("UTF-8");
        byte[] cipherBytes = null;
        System.out.println("明文:" + Arrays.toString(plainBytes));
        cipherBytes = DES3Util.encodeBytes(plainBytes, desKey);
        System.out.println("密文:" + Arrays.toString(cipherBytes));
        plainBytes = DES3Util.decodeBytes(cipherBytes, desKey);
        System.out.println("解密明文:" + Arrays.toString(plainBytes));
        System.out.println();
    }

}

  控制台输出

  查看Console中的控制台内容,明文和解密后明文对比,可以确认DES3Util可以正常工作,控制台如下图:

----------------------- 获取DES秘钥 -------------------------
秘钥:MTIyNDQ3Nzg4Nzc0NDIyMTEyMjQ0Nzc4

----------------------- 文本加解密测试 -------------------------
明文:This is 一段明文内容!
密文:JxYMtG6qIvxci4gDOtBSV4YG4FQhDatKk5k8edb2res=
解密明文:This is 一段明文内容!

----------------------- 字节数组加解密测试 -------------------------
明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]
密文:[39, 22, 12, -76, 110, -86, 34, -4, 92, -117, -120, 3, 58, -48, 82, 87, -122, 6, -32, 84, 33, 13, -85, 74, -109, -103, 60, 121, -42, -10, -83, -21]
解密明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]

  总结

  算法实现都很类似,本文只是对算法实现做了整理,在Maven依赖引入的情况下,DES3Util已经做了简单测试,可以直接使用。

  若文中存在错误和不足,欢迎指正!

本博微信公众号“超哥说码”,欢迎大家订阅,公众号正在完善中,会及时将更优质的博文推送于您!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/securitit/article/details/108203509