Java加解密之DES3

Java加解密之DES3(十六进制的密钥长度为32位时,字节长度只有16位,3DES密钥长度需要24位字节长度)
上篇为DES加解密处理,这篇为DES3加解密!
需要注意3DES加解密转换类型。
PKCS5Padding会自动补齐字节长度为8的倍数。
NoPadding需要自己进行处理。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class DES3Util {

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

    private final static String KEY = "";
    private static final String KEY_ALGORITHM = "DESede";
    private static final String DEFAULT_ALGORITHM_TYPE = "DESede/ECB/NoPadding";
    //private static final String DEFAULT_ALGORITHM_TYPE = "DESede/ECB/PKCS5Padding";

    /**
     *  生成密钥
     * @return
     */
    private static SecretKey getSecretKey() {

        byte[] keybyte = promotion16To24(hexToByte(KEY));
        SecretKey secretKey = new SecretKeySpec(keybyte, KEY_ALGORITHM);

        return secretKey;
    }

    /**
     *  将密钥转为16位字节
     * @param hex
     * @return
     */
    public static byte[] hexToByte(String hex){
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }

    /**
     *  16位字节密钥转为24位
     * @param inputKey
     * @return
     * @throws IllegalArgumentException
     */
    public static byte[] promotion16To24(byte[] inputKey)
            throws IllegalArgumentException {
        if (inputKey == null || inputKey.length != 16) {
            throw new IllegalArgumentException("input error");
        }
        byte[] outputKey = new byte[24];
        System.arraycopy(inputKey, 0, outputKey, 0, 16);
        System.arraycopy(inputKey, 0, outputKey, 16, 8);
        return outputKey;
    }

    /**
     *  算法转换类型为NoPadding,所以加密时需要进行补充
     * @param bytes
     * @return
     */
    public static byte[] supplementByte8(byte[] bytes){
        byte[] resByte;
        if (bytes.length % 8 != 0) {
            int len = 8 - bytes.length % 8;
            resByte = new byte[bytes.length + len];
            System.arraycopy(bytes, 0, resByte, 0, bytes.length);
            for (int i = 0; i < len; i++) {
                resByte[bytes.length + i] = 0x00;
            }
        } else {
            resByte = bytes;
        }
        return resByte;
    }

    /**
     *  进行3DES加密
     * @param content
     * @return
     */
//    public static String encrypt(String content) {
//        try {
//            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
//            byte[] byteContent = content.getBytes("utf-8");
//            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
//            byte[] result = cipher.doFinal(supplementByte8(byteContent));
//            return new String(result);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return null;
//    }

    public static byte[] encrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
            byte[] result = cipher.doFinal(supplementByte8(byteContent));
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String encrypt(byte[] content) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
            byte[] result = cipher.doFinal(supplementByte8(content));
            return new String(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 进行3DES解密
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
            byte[] result = cipher.doFinal(content.getBytes("utf-8"));
            return new String(result, "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

//    public static byte[] decrypt(String content) {
//        try {
//            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
//            cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
//            byte[] result = cipher.doFinal(content.getBytes("utf-8"));
//            return result;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return null;
//    }

    public static String decrypt(byte[] content) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
            byte[] result = cipher.doFinal(content);
            return new String(result, "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中实现3DES加密解密可以使用JCE(Java Cryptography Extension)提供的API。下面是一个简单的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import java.nio.charset.StandardCharsets; import java.security.spec.KeySpec; public class TripleDesExample { public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; String secretKey = "0123456789ABCDEFGHIGKLMN"; byte[] encryptedBytes = encrypt(plainText, secretKey); String encryptedText = new String(encryptedBytes, StandardCharsets.UTF_8); System.out.println("Encrypted text: " + encryptedText); byte[] decryptedBytes = decrypt(encryptedBytes, secretKey); String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println("Decrypted text: " + decryptedText); } public static byte[] encrypt(String plainText, String secretKey) throws Exception { byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8); byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); KeySpec keySpec = new DESedeKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plainBytes); } public static byte[] decrypt(byte[] encryptedBytes, String secretKey) throws Exception { byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); KeySpec keySpec = new DESedeKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(encryptedBytes); } } ``` 在上面的示例代码中,我们使用了`DESede`算法实现了3DES加密解密。需要注意的是,密钥的长度必须是24个字节(即192位),因此我们在示例中使用了一个24个字符的字符串作为密钥。在实际应用中,我们可以使用更加安全的方式生成密钥,例如使用`KeyGenerator`类生成密钥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值