Bootstrap

java对数据进行加密、解密

java对数据进行加密、解密

RSA不对称加密

关于base64可以参考我的上一篇博客: java Base64编码、解码

import org.springframework.util.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author ListJiang
 * @class RSA加密工具类
 * @remark
 * @date 2020/9/14 19:56
 */
public class EncrypRSA {
   

    private static final String PUBLIC = "PUBLIC";
    private static final String PRIVATE = "PRIVATE";


    /**
     * 根据公钥加密
     *
     * @param publicKey      公钥
     * @param cleartextBytes 明文
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] cleartextBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
   
        if (publicKey != null) {
   
            //Cipher负责完成加密或解密工作,基于RSA
            Cipher cipher = Cipher.getInstance("RSA");
            //根据公钥,对Cipher对象进行初始化
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] resultBytes = cipher.doFinal(cleartextBytes);
            return resultBytes;
        }
        return null;
    }

    /**
     * 根据公钥加密
     *
     * @param publicKey 公钥
     * @param cleartext 明文
     * @return
     * @throws Exception
     */
    public byte[] encrypt(RSAPublicKey publicKey, String cleartext) throws Exception {
   
        if (publicKey != null) {
   
            return encrypt(publicKey, cleartext.getBytes());
        }
        return null;
    }

    /**
     * 指定加密类型进行加密
     *
     * @param key       密钥
     * @param cleartext 明文
     * @param keyType   加密密钥类型,默认公钥加密
     * @return
     * @throws Exception
     */
    public byte[] encrypt(String key, String cleartext, String keyType) throws Exception {
   
        if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(keyType)) {
   
            switch (keyType) {
   
                case PUBLIC:
                    return encrypt(getPublicKey(key), cleartext.getBytes());
                case PRIVATE:
                    return encrypt
;