使用 javax.crypto 进行加密解密

733 阅读1分钟

使用 javax.crypto 进行加密解密

javax.crypto 的相关类

结合 Base64 使用。

javax.crypto.BadPaddingException;
javax.crypto.Cipher;
javax.crypto.IllegalBlockSizeException;
javax.crypto.NoSuchPaddingException;
javax.crypto.spec.IvParameterSpec;
javax.crypto.spec.SecretKeySpec;

完整的加密解密代码

其中 加密键值 是 32位,加密IV 是 16位。 BouncyCastle是包含很多哈希算法和加密算法的第三方库。

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;

/**
 * 加密解密工具类
 */
@Component
public class EncryptUtil {
	/** 加密键值(32位) */
	public static final String KEY = "12345678901234567890123456789012";

	/** 加密IV(16位) */
	public static final String IV = "1234567890123456";

	/** Cipher 变换 */
	public static final String TRANSFORMATION = "AES/CBC/PKCS7Padding";

	/** 算法 SecretKeySpec */
	private static final String ALGORITHM_AES = "AES";

	static {
        	// 注册BouncyCastle
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * 加密
	 * 
	 * @param s - 加密目标内容
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidAlgorithmParameterException
	 * @throws InvalidKeyException
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 */
	public static String encrypt(String s)
			throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		byte[] encrypted = null;
		Cipher cipher = Cipher.getInstance(TRANSFORMATION);
		SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8.name()), ALGORITHM_AES);
		AlgorithmParameterSpec algorithmParameterSpec = new IvParameterSpec(IV.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, algorithmParameterSpec);
		encrypted = cipher.doFinal(s.getBytes(StandardCharsets.UTF_8.name()));
		return Base64.encodeBase64String(encrypted);
	}

	/**
	 * 解密
	 * 
	 * @param s - 解密目标内容
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidAlgorithmParameterException
	 * @throws InvalidKeyException
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 */
	public static String decrypt(String s)
			throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Cipher cipher = Cipher.getInstance(TRANSFORMATION);
		SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8.name()), ALGORITHM_AES);
		AlgorithmParameterSpec algorithmParameterSpec = new IvParameterSpec(IV.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, algorithmParameterSpec);
		return new String(cipher.doFinal(Base64.decodeBase64(s)), StandardCharsets.UTF_8.name());
	}
}

测试类:

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args)  {
        // 加密
        String s = "";
        String encryptedResult = "";
        s = "Hello, world"; 
        try {
            encryptedResult =  EncryptUtil.encrypt(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(encryptedResult);
        
        // 解密
        String result = "";
        String decryptedResult = "";
        
        result = encryptedResult;
        try {
            decryptedResult = EncryptUtil.decrypt(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(decryptedResult);
    }
}

测试结果:

ov8brlPB/1hqYgBcJczrLg==
Hello, world