RSA encryption tool class

        RSA encryption tool class, generate key pair, encryption and decryption functions. Use what you like.

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
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.concurrent.ConcurrentMap;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import com.google.common.collect.Maps;
import com.opentrans.otms.api.web.enums.ResponseEnum;
import com.opentrans.otms.exception.RFIException;
import com.opentrans.otms.logger.Logger;
import com.opentrans.otms.logger.LoggerFactory;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class RSAEncryptUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RSAEncryptUtil.class);

    private static final ConcurrentMap<String, Object> KEY_CACHE_MAP = Maps.newConcurrentMap();

    public static final String PRIVATE_KEY = "RSAPrivateKey";

    public static final String INVITATION_PUBLIC_KEY = "InvitationRSAPublicKey";
    public static final String INVITATION_PRIVATE_KEY = "InvitaionRSAPrivateKey";

    private RSAEncryptUtil() {
    }

    public static void main(String[] args) {
        genKeyPair(512);
    }

    public static void genKeyPair(int keysize) {
        // The KeyPairGenerator class is used to generate public and private key pairs, and objects are generated based on the RSA algorithm
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            // Initialize the key pair generator, the key size is 96-1024 bits
            keyPairGen.initialize(keysize, new SecureRandom());
            // Generate a key pair and save it in keyPair
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // get private key
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // get the public key
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // get the public key string
            String publicKeyString = Base64.encode(publicKey.getEncoded());
            // get the private key string
            String privateKeyString = Base64.encode(privateKey.getEncoded());

            LOGGER.info("public key is :" + publicKeyString);
            LOGGER.info("private key is :" + privateKeyString);
        } catch (Exception e) {
            LOGGER.info("get key pair error :{}", e);
        }
    }

    public static RSAPrivateKey getPrivateKeyByStr(String privateKeyStr, String key) {
        try {

            RSAPrivateKey privateKey = (RSAPrivateKey) KEY_CACHE_MAP.get(key);
            if (privateKey == null) {
                byte[] buffer = Base64.decode(privateKeyStr);
                PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                privateKey = (RSAPrivateKey) keyFactory.generatePrivate (keySpec);
                KEY_CACHE_MAP.put(key, privateKey);
            }
            return privateKey;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such algorithm");
        } catch (InvalidKeySpecException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The private key is invalid");
        } catch (NullPointerException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Private key data is empty");
        }
    }

    public static RSAPublicKey getPublicKeyByStr(String publicKeyStr) {
        try {
            byte[] buffer = Base64.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic (keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such algorithm");
        } catch (InvalidKeySpecException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The public key is invalid");
        } catch (NullPointerException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The public key data is empty");
        }
    }

    /**
     * Public key encryption process
     *
     * @param publicKey
     * public key
     * @param plainTextData
     * Plaintext data
     * @return
     * @throws Exception
     * Exception information during encryption
     */
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) {
        if (publicKey == null) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The encryption public key is empty, please set it");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(plainTextData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such encryption algorithm");
        } catch (NoSuchPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "");
        } catch (InvalidKeyException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The encryption public key is invalid, please check");
        } catch (IllegalBlockSizeException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Illegal length of plaintext");
        } catch (BadPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Plaintext data is corrupted");
        }
    }

    /**
     * Private key encryption process
     *
     * @param privateKey
     * private key
     * @param plainTextData
     * Plaintext data
     * @return
     * @throws Exception
     * Exception information during encryption
     */
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) {
        if (privateKey == null) {
            throw new RFIException(ResponseEnum.ERROR.getCode(), "The encrypted private key is empty, please set it");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return cipher.doFinal(plainTextData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such encryption algorithm");
        } catch (NoSuchPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "");
        } catch (InvalidKeyException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The encrypted private key is invalid, please check");
        } catch (IllegalBlockSizeException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Illegal length of plaintext");
        } catch (BadPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Plaintext data is corrupted");
        }
    }

    /**
     * Private key decryption process
     *
     * @param privateKey
     * private key
     * @param cipherData
     * Ciphertext data
     * @return plaintext
     * @throws Exception
     * Exception information during decryption
     */
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) {
        if (privateKey == null) {
            throw new RFIException(ResponseEnum.ERROR.getCode(), "The decryption private key is empty, please set it");
        }
        Cipher cipher = null;
        try {
            // use default RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(cipherData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such decryption algorithm");
        } catch (NoSuchPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The decryption private key is empty, please set it");
        } catch (InvalidKeyException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The decryption private key is illegal, please check");
        } catch (IllegalBlockSizeException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Ciphertext length is illegal");
        } catch (BadPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "ciphertext data is corrupted");
        }
    }

    /**
     * Public key decryption process
     *
     * @param publicKey
     * public key
     * @param cipherData
     * Ciphertext data
     * @return plaintext
     * @throws Exception
     * Exception information during decryption
     */
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) {
        if (publicKey == null) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such decryption algorithm");
        }
        Cipher cipher = null;
        try {
            // use default RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(cipherData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "No such decryption algorithm");
        } catch (NoSuchPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "");
        } catch (InvalidKeyException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "The decryption public key is invalid, please check");
        } catch (IllegalBlockSizeException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "Ciphertext length is illegal");
        } catch (BadPaddingException e) {
            throw new Exception(ResponseEnum.ERROR.getCode(), "ciphertext data is corrupted");
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325545352&siteId=291194637