【Java小工匠】对称加密--3DES

1、什么是3DES

  3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。


【Java小工匠】对称加密--3DES_第1张图片
image

2、3DES算法特点

(1)密钥长度增加到(112位或者168位)+3*8(24 个校验位),通过增加迭代此次提高安全性。
(2)缺点:处理速度慢、密钥计算时间较长、加密效率不高。

3、3DES算法实现

3.1 3DES的JDK 实现

(1)工作模式
ECB、CBC、PCBC、CTR、CTS、CFB、CFB8-CFB128、OFB、OFB8-OFB128.
(2) 填充模式
NoPadding、PKCS5Padding、ISO10126Padding
(3) 默认密钥长度 168 位
(4) 代码实现

package lzf.cipher.jdk;

import java.nio.charset.Charset;

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

/**
 * @author Java小工匠
 */
public class Jdk3DesUtils {

    public static final String ALGORITHM = "DESede";
    public static final String CIPHER_ALGORITHM = ALGORITHM + "/ECB/ISO10126Padding";

    // 获取 AES Key
    public static byte[] getAesKey() {
        try {
            // 1、创建密钥生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
            keyGenerator.init(168);
            // 2、产生密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 3、获取密钥
            byte[] key = secretKey.getEncoded();
            return key;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 加密
    public static byte[] encrypt(byte[] data, byte[] key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
            // 加工作模式和填充方式
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 解密
    public static byte[] decrypt(byte[] data, byte[] key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 数据准16进制编码
    public static String encodeHex(final byte[] data) {
        return encodeHex(data, true);
    }

    // 数据转16进制编码
    public static String encodeHex(final byte[] data, final boolean toLowerCase) {
        final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return new String(out);
    }

    public static void main(String[] args) {
        byte[] data = "java小工匠".getBytes(Charset.forName("UTF-8"));
        byte[] key = getAesKey();
        String hexKeyStr = encodeHex(key);
        System.out.println("加密密钥:" + hexKeyStr + ",length=" + hexKeyStr.length());
        byte[] encryptData = encrypt(data, key);
        System.out.println("加密数据:" + encodeHex(encryptData));
        byte[] decryptData = decrypt(encryptData, key);
        System.out.println("解密数据:" + new String(decryptData));
    }
}

3.2 3DES的BC实现

package lzf.cipher.bc;

import java.nio.charset.Charset;
import java.security.Security;

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

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

/**
 * @author Java小工匠
 */
public class BC3DesUtils {

    public static final String ALGORITHM = "DESede";
    public static final String CIPHER_ALGORITHM = ALGORITHM + "/ECB/ISO10126Padding";

    // 获取 Key
    public static byte[] getKey() {
        try {
            Security.addProvider(new BouncyCastleProvider());
            // 1、创建密钥生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM, "BC");
            keyGenerator.init(168);
            // 2、产生密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 3、获取密钥
            byte[] key = secretKey.getEncoded();
            return key;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 加密
    public static byte[] encrypt(byte[] data, byte[] key) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
            // 加工作模式和填充方式
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 解密
    public static byte[] decrypt(byte[] data, byte[] key) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
            // 加工作模式和填充方式
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        byte[] data = "java小工匠".getBytes(Charset.forName("UTF-8"));
        byte[] key = getKey();
        String hexKeyStr = Hex.toHexString(key);
        System.out.println("加密密钥:" + hexKeyStr + ",length=" + hexKeyStr.length());
        byte[] encryptData = encrypt(data, key);
        System.out.println("加密数据:" + Hex.toHexString(encryptData));
        byte[] decryptData = decrypt(encryptData, key);
        System.out.println("解密数据:" + new String(decryptData));
    }
}

如果读完觉得有收获的话,欢迎点赞、关注、加公众号【小工匠技术圈】

个人公众号,欢迎关注,查阅更多精彩历史!

image

你可能感兴趣的:(【Java小工匠】对称加密--3DES)