3des加解密CBC




import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Arrays;


public class ThreeDesCbc {
     

    // 向量
    private final static String iv = "87654321";
    // 加解密统一使用的编码方式
    private final static String encoding = "UTF-8";

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String encode(String plainText, String secretKey) throws Exception {
     
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");

        SecureRandom randomSecureRandom = new SecureRandom();
        byte[] iv = new byte[cipher.getBlockSize()];
        randomSecureRandom.nextBytes(iv);
        IvParameterSpec ips = new IvParameterSpec(iv);

//        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
        return HexToStrUtil.bytesToHex(encryptData);

    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static byte[] decode(String encryptText, String secretKey) throws Exception {
     
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] unenc_bytes = cipher.doFinal(HexToStrUtil.hexToByteArray(encryptText));
        // 丢弃前8个字节,由于加密iv随机的,解密后前8个字节也随机,故丢弃,加密时先在明文前随便补8个字节
        return Arrays.copyOfRange(unenc_bytes, 8, unenc_bytes.length);
    }


    public static void main(String[] args) throws Exception {
     

//        String text = "AAABBBCC我是明文秘钥";
//        String key = "PR3tmPJqcH5RE0iGsW4qiN5VYtjX7sVU";
//        String encryptData = encode(text, key);
//        String decryptorData = new String(decode(encryptData, key));
//        System.out.println("原始字符串=" + text);
//        System.out.println("加密后的值=" + encryptData);
//        System.out.println("解密后的值=" + decryptorData);


    }

}

你可能感兴趣的:(加密解密)