3DES加密算法的JAVA实现

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

import org.apache.commons.codec.binary.Base64;
 
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.StandardCharsets;
 
public class TripleDESUtils {
    private static final String algorithm = "DESede";
 
    /**
     * 3DES ECB加密,key必须是长度大于等于 3*8 = 24 位
     *
     * @param src 要加密的字符串
     * @param key 密钥
     * @return 加密后的Base64编码字符串
     * @throws Exception
     */
    public static String encrypt(final String src, final String key) throws Exception {
        final DESedeKeySpec dks = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        final SecretKey secretKey = keyFactory.generateSecret(dks);
 
        // 加密
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        final byte[] result = cipher.doFinal(src.getBytes());
        return Base64.encodeBase64String(result);
    }
 
    /**
     * 3DES ECB解密,key必须是长度大于等于 3*8 = 24 位
     *
     * @param src 要解密的字符串
     * @param key 密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decrypt(final String src, final String key) throws Exception {
        final byte[] byteSrc = Base64.decodeBase64(src);
        // --解密的key
        final DESedeKeySpec dks = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        final SecretKey secretKey = keyFactory.generateSecret(dks);
 
        // 解密
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        final byte[] retByte = cipher.doFinal(byteSrc);
        return new String(retByte);
    }
}

测试加解密,这里对加密后的字符串进行Base64编码,否则是乱码。

public class Test {
    public static void main(String[] args) throws Exception {
        String str = "清风徐来,水波不兴";
        String key = "xUHdKxzVCbsgVIwTnc1jtpWn";
        String result = TripleDESUtils.encrypt(str, key);
        System.out.println("加密后的Base64编码字符串:" + result);
        System.out.println("解密后的字符串:" + TripleDESUtils.decrypt(result, key));
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部