Java RSA加解密、公私密钥对生成

话不多说,直接上干货。
附带公私密钥对生成。

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
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.Base64;
import java.util.HashMap;
import java.util.Map;

public class RsaUtils {

    private static String publicK = "xx";

    private static String privateK = "xx";

    private static final String KEY_ALGORITHM = "RSA";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return 公钥对象
     */
    public static PublicKey getPublicKey(String publicKey) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
        }
        byte[] decodedKey = org.apache.commons.codec.binary.Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        try {
            return keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * RSA公钥加密
     *
     * @param str 加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey ) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(
                new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * RSA加密(大字符)
     *
     * @param data 待加密数据
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encrypt(String data, PublicKey publicKey){
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            e.printStackTrace();
            throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
        }
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                try {
                    cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
                } catch (IllegalBlockSizeException | BadPaddingException e) {
                    e.printStackTrace();
                    throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
                }
            } else {
                try {
                    cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
                } catch (IllegalBlockSizeException | BadPaddingException e) {
                    e.printStackTrace();
                    throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
                }
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(ErrorCodeEnum.SERVER_ERROR);
        }
        return org.apache.commons.codec.binary.Base64.encodeBase64String(encryptedData);
    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @param privateKey 私钥
     * @return 明文
     *
     */
    public static String decrypt(String str, String privateKey) throws UnsupportedEncodingException,
            NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException, InvalidKeyException {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(
                new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        return new String(cipher.doFinal(inputByte));
    }

    /**
     * 生成RSA的密钥对
     */
    public static class RsaKeyUtils {

        private static final String PUBLIC_KEY = "RSAPublicKey";

        private static final String PRIVATE_KEY = "RSAPrivateKey";

        //map对象中存放公私钥
        public static Map initKey() throws Exception {
            //获得对象 KeyPairGenerator 参数 RSA 1024个字节
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            //通过对象 KeyPairGenerator 获取对象KeyPair
            KeyPair keyPair = keyPairGen.generateKeyPair();

            //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            //公私钥对象存入map中
            Map keyMap = new HashMap<>(2);
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }

        //获得公钥
        public static String getPublicKey(Map keyMap) throws Exception {
            //获得map中的公钥对象 转为key对象
            Key key = keyMap.get(PUBLIC_KEY);
            //byte[] publicKey = key.getEncoded();
            //编码返回字符串
            return Base64.getEncoder().encodeToString(key.getEncoded());
        }

        //获得私钥
        public static String getPrivateKey(Map keyMap) throws Exception {
            //获得map中的私钥对象 转为key对象
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            //byte[] privateKey = key.getEncoded();
            //编码返回字符串
            return Base64.getEncoder().encodeToString(key.getEncoded());
        }

        public static void getKey() throws Exception {
            Map keyMap = initKey();
            String publicKey = getPublicKey(keyMap);
            publicK = publicKey;
            System.out.println("publicKey -> " + publicKey);
            String privateKey = getPrivateKey(keyMap);
            privateK = privateKey;
            System.out.println("privateKey -> " + privateKey);
        }
    }

    public static void main(String[] args) throws Exception {
        RsaKeyUtils.getKey();
        String s = "1234567890";
        String encrypt = encrypt(s, publicK);
        System.out.println(encrypt);
        String decrypt = decrypt(encrypt, privateK);
        System.out.println(decrypt);

        PublicKey publicKey = getPublicKey(publicK);
        String encrypt1 = encrypt(s, publicKey);
        System.out.println(encrypt1);
        String decrypt1 = decrypt(encrypt1, privateK);
        System.out.println(decrypt1);
        System.out.println();
    }
}

你可能感兴趣的:(Java RSA加解密、公私密钥对生成)