Java加解密之RSA
RSA加解密需要有公钥,私钥;可以使用公钥加密,私钥解密;也可以使用私钥加密,公钥解密。私钥加密相同的数据密文相同,公钥加密相同的数据密文不同。

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/***
 *  进行RSA加密解密
 */
public class SecrteKeyUtil {

    private static Logger logger = LoggerFactory.getLogger(SecrteKeyUtil.class);

    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhK5CC/0MQqdG9xtMhGP0Cy8qkRw/UK7ktS9cN46V4wsDX5KvlTXyIYDXjiYwKvGVUak2OKZB688Qlz3RRy1E4UNosf8YREGwdNXE5wvG0bf1Qd5RCr/Cr99M3x/Elyp1Z+jFZlFXrbAAQZq/sRh+9l+xn3l8+ChhuTdXKBhpl+8cz4edmGHPWkOuGvoN6lOE8lNzbZtmz5dfbAEtbsOin+/u69ynoIGz4iYL7KnzDrZOOHutZ4++qtiX+Pbhse+h2tPAwgUSOOTKsoEn/zjadOS6XJJ1VeeWnBVSn40jPbYRt3ymApItQcym6mWSnyg+2flLnpdAf7DIQn2Qlqt+VwIDAQAB";
    public static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCErkIL/QxCp0b3G0yEY/QLLyqRHD9QruS1L1w3jpXjCwNfkq+VNfIhgNeOJjAq8ZVRqTY4pkHrzxCXPdFHLUThQ2ix/xhEQbB01cTnC8bRt/VB3lEKv8Kv30zfH8SXKnVn6MVmUVetsABBmr+xGH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J57sHsRmJeaKZhMChll4WFJdreG8zsE5qkImdHy/vkzgjQD+vTwx7qySUWqlTuMLIAomtdSZzhLKmA6LqJmNDOiDgPXZHZAOS779wf8tn+S0jJf8g7mY73ZkpXeUuyoETlicU1CqbemfBQjcEURLBo6Rku8bhqcTtvse5vhAoGAfuHzU9bz++EtQgfo2PPTD76erfjsYHGy4SR+S2WwgCBt04WZEWkbympjvpZQAMdD9WCOv3R1fNGLUIcRzrjlUt+HIAxJtW6tWYhL4i+KM4NqUhF+2TesGzYTPP8x8PSaWGT4ruynKrgxR08XaHyH3L/Htd3OMXTasgTPuZNguIw=";
    public static final String SIGN_NAME = "RSA"; // aes rsa

    /**
     * 生成公钥与私钥对
     *
     * @return 公钥Key=publicKey 私钥Key=privateKey
     * @throws Exception
     */
    public static Map<String, String> getKeys() throws Exception {
        int len = 2048;//rsa算法长度,生成秘钥对时用
        // 获得公钥与私钥对
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(SIGN_NAME);
        keyPairGen.initialize(len);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, String> keys = new HashMap<>(2);
        String privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        keys.put("privateKey", privateKey);
        RSAPublicKey rsapublicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKey = Base64.encodeBase64String(rsapublicKey.getEncoded());
        keys.put("publicKey", publicKey);
        return keys;
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(publicKeyStr);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(SIGN_NAME);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此算法",e);
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            logger.error("公钥非法",e);
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            logger.error("公钥数据为空",e);
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从字符串中加载私钥
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(SIGN_NAME);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此算法",e);
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            logger.error("私钥非法",e);
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            logger.error("私钥数据为空",e);
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 公钥加密过程
     *
     * @param publicKey     公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(SIGN_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return Base64.encodeBase64String(output);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此加密算法",e);
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            logger.error("加密公钥非法,请检查",e);
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            logger.error("明文长度非法",e);
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            logger.error("明文数据已损坏",e);
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥加密过程
     *
     * @param privateKey    私钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return Base64.encodeBase64String(output);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此加密算法",e);
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            logger.error("加密私钥非法,请检查",e);
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            logger.error("明文长度非法",e);
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            logger.error("明文长度非法",e);
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥解密过程
     *
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此解密算法",e);
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            logger.error("解密私钥非法,请检查",e);
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            logger.error("密文长度非法",e);
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            logger.error("密文数据已损坏",e);
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 公钥解密过程
     *
     * @param publicKey  公钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            logger.error("无此解密算法",e);
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            logger.error("解密公钥非法,请检查",e);
            throw new Exception("解密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            logger.error("密文长度非法",e);
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            logger.error("密文数据已损坏",e);
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 私钥加密
     * @param content 明文
     * @return
     */
    public static String priEncrypt(String content){
        String res = "";
        try {
            //加载私钥
            RSAPrivateKey rsaprikey = loadPrivateKeyByStr(PRIVATE_KEY);
            //私钥加密
            res = encrypt(rsaprikey,content.getBytes());
        } catch (Exception e) {
            logger.error("私钥加密出错",e);
        }
        return res;
    }

    /**
     * 公钥加密
     * @param content 明文
     * @return
     */
    public static String pubEncrypt(String content){
        String res = "";
        try {
            //加载公钥
            RSAPublicKey rsapubkey = loadPublicKeyByStr(PUBLIC_KEY);
            //公钥加密
            res = encrypt(rsapubkey,content.getBytes());
        } catch (Exception e) {
            logger.error("公钥加密出错",e);
        }
        return res;
    }

    /**
     * 私钥解密
     * @param content 加密后的密文
     */
    public static String priDecrypt(String content){
        String res = "";
        try {
            //加载私钥
            RSAPrivateKey rsaprikey = loadPrivateKeyByStr(PRIVATE_KEY);
            //解密
            res = decrypt(rsaprikey,Base64.decodeBase64(content));
        } catch (Exception e) {
            logger.error("私钥解密出错",e);
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 公钥解密
     * @param content 加密后的密文
     */
    public static String pubDecrypt(String content){
        String res = "";
        try {
            //加载公钥
            RSAPublicKey rsapubkey = loadPublicKeyByStr(PUBLIC_KEY);
            //解密
            res = decrypt(rsapubkey,Base64.decodeBase64(content));
        } catch (Exception e) {
            logger.error("公钥解密出错",e);
            e.printStackTrace();
        }
        return res;
    }

}