Skip to content

RSA加密工具类

java

/**
 * <p>
 * RSA 公钥私钥加密解密工具类
 * </p>
 *
 * @author Gnerv LiGen
 */
public class RsaEncryptTools {

    private static final String STATUS_MODE = "RSA";
    /**
     * "算法/模式/补码方式"
     */
    private static final String TRANS_FORMATION = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
    private static final int KEY_SIZE = 1024;

    private RsaEncryptTools() {
    }

    public static KeyPair genKeyPair() throws NoSuchAlgorithmException {
        return genKeyPair(KEY_SIZE);
    }

    public static String getPublicKey(KeyPair keyPair) {
        // 得到公钥
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        // 得到公钥字符串
        return Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
    }

    public static String getPrivateKey(KeyPair keyPair) {
        // 得到私钥
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到私钥字符串
        return Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
    }

    public static KeyPair genKeyPair(int keySize) throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(STATUS_MODE);
        // 初始化密钥对生成器
        keyPairGen.initialize(keySize, new SecureRandom());
        // 生成一个密钥对
        return keyPairGen.generateKeyPair();
    }

    public static String encrypt(String content, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance(STATUS_MODE).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    }

    public static String decrypt(String content, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        //base64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(content);
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance(STATUS_MODE).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
        cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
        return new String(cipher.doFinal(inputByte));
    }

}

Released under the MIT License.