常用加密解密(2)——对称加密

原文链接:https://www.dubby.cn/detail.html?id=9123

文章目录

  • AES
  • DES
  • DESede
  • IDEA

本文主要介绍常用的对称加密算法的Java实现


    org.bouncycastle
    bcprov-jdk15on
    1.60


    org.bouncycastle
    bcpkix-jdk15on
    1.60

AES

我在《Java加密之IV》中提到过分组加密的几种方式,常见的工作模式包括,ECB、CBC、PCBC、CFB、OFB、CTR等。

其中ECB是不需要IV(初始化向量)的:

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @see javax.crypto.spec.SecretKeySpec
 */
public class AES {

    private static final String key_algorithm = "AES";

    private static final String cipher_algorithm = "AES/ECB/PKCS5Padding";

    public static byte[] encrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, IllegalBlockSizeException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        /**
         * 对于某些JDK不支持的工作方式,可以考虑 Cipher cipher = Cipher.getInstance(cipher_algorithm, "BC);
         * 其中BC是Bouncy Castle的简称
         */
        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }
}

单元测试:

import cn.dubby.encrypt.encoding.HexUtil;
import cn.dubby.symmetric.encryption.AES;
import cn.dubby.symmetric.encryption.DES;
import org.junit.Test;

import javax.crypto.*;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class AESTest {

    @Test
    public void encryptDecrypt() throws NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, InvalidKeySpecException, InvalidKeyException {
        String data = "Hello, world.";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        byte[] encryptBytes = AES.encrypt(keyBytes, data.getBytes(Charset.forName("UTF-8")));
        System.out.println(HexUtil.toHex(encryptBytes));

        byte[] decryptBytes = AES.decrypt(keyBytes, encryptBytes);
        System.out.println(new String(decryptBytes, Charset.forName("UTF-8")));
    }
}

而PCBC是需要IV的:

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @see SecretKeySpec
 */
public class AES_PCBC {

    private static final String key_algorithm = "AES";

    private static final String cipher_algorithm = "AES/PCBC/PKCS5Padding";

    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        /**
         * 对于某些JDK不支持的工作方式,可以考虑 Cipher cipher = Cipher.getInstance(cipher_algorithm, "BC);
         * 其中BC是Bouncy Castle的简称
         */
        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));
        return cipher.doFinal(data);
    }
}

单元测试:

import cn.dubby.encrypt.encoding.HexUtil;
import cn.dubby.symmetric.encryption.AES;
import cn.dubby.symmetric.encryption.AES_PCBC;
import org.junit.Test;

import javax.crypto.*;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class AES_PCBCTest {

    @Test
    public void encryptDecrypt() throws NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
        /**
         * iv必须是16位
         */
        String data = "Hello, world.", iv = "1234567812345678";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        byte[] encryptBytes = AES_PCBC.encrypt(iv.getBytes(Charset.forName("UTF-8")), keyBytes, data.getBytes(Charset.forName("UTF-8")));
        System.out.println(HexUtil.toHex(encryptBytes));

        byte[] decryptBytes = AES_PCBC.decrypt(iv.getBytes(Charset.forName("UTF-8")), keyBytes, encryptBytes);
        System.out.println(new String(decryptBytes, Charset.forName("UTF-8")));
    }
}

DES

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * @see javax.crypto.spec.DESKeySpec
 */
public class DES {

    private static final String key_algorithm = "DES";

    private static final String cipher_algorithm = "DES/ECB/PKCS5Padding";

    public static byte[] encrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key_algorithm);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key_algorithm);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }
}

单元测试:

import cn.dubby.encrypt.encoding.HexUtil;
import cn.dubby.symmetric.encryption.DES;
import org.junit.Test;

import javax.crypto.*;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class DESTest {

    @Test
    public void encryptDecrypt() throws NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, InvalidKeySpecException, InvalidKeyException {
        String data = "Hello, world.";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        keyGenerator.init(56);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        byte[] encryptBytes = DES.encrypt(keyBytes, data.getBytes(Charset.forName("UTF-8")));
        System.out.println(HexUtil.toHex(encryptBytes));

        byte[] decryptBytes = DES.decrypt(keyBytes, encryptBytes);
        System.out.println(new String(decryptBytes, Charset.forName("UTF-8")));
    }
}

DESede

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * @see javax.crypto.spec.DESedeKeySpec
 */
public class DESede {

    private static final String key_algorithm = "DESede";

    private static final String cipher_algorithm = "DESede/ECB/PKCS5Padding";

    public static byte[] encrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key_algorithm);
        SecretKey secretKey = keyFactory.generateSecret(deSedeKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] keyBytes, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key_algorithm);
        SecretKey secretKey = keyFactory.generateSecret(deSedeKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }
}

单元测试:

package cn.dubby.symmetric.encryption.test;

import cn.dubby.encrypt.encoding.HexUtil;
import cn.dubby.symmetric.encryption.DESede;
import org.junit.Test;

import javax.crypto.*;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class DESedeTest {

    @Test
    public void encryptDecrypt() throws NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, InvalidKeySpecException, InvalidKeyException {
        String data = "Hello, world.";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(168);//还可以选112
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        byte[] encryptBytes = DESede.encrypt(keyBytes, data.getBytes(Charset.forName("UTF-8")));
        System.out.println(HexUtil.toHex(encryptBytes));

        byte[] decryptBytes = DESede.decrypt(keyBytes, encryptBytes);
        System.out.println(new String(decryptBytes, Charset.forName("UTF-8")));
    }
}

IDEA

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class IDEA {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String key_algorithm = "IDEA";

    private static final String cipher_algorithm = "IDEA/ECB/ISO10126Padding";

    public static byte[] encrypt(byte[] keyBytes, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] keyBytes, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        SecretKey secretKey = new SecretKeySpec(keyBytes, key_algorithm);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    /**
     * 生成一个随机的秘钥
     */
    public static byte[] initKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(key_algorithm);
        keyGenerator.init(128);

        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }
}

单元测试:

import cn.dubby.encrypt.encoding.HexUtil;
import cn.dubby.symmetric.encryption.IDEA;
import org.junit.Test;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class IDEATest {

    @Test
    public void encryptDecrypt() throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException {
        String data = "Hello, world.";

        byte[] keyBytes = IDEA.initKey();
        byte[] encryptBytes = IDEA.encrypt(keyBytes, data.getBytes(Charset.forName("UTF-8")));

        System.out.println(HexUtil.toHex(encryptBytes));

        byte[] decryptBytes = IDEA.decrypt(keyBytes, encryptBytes);

        System.out.println(new String(decryptBytes, Charset.forName("UTF-8")));
    }
}

你可能感兴趣的:(Java)