All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ideaaedi.commonds.security.RSA Maven / Gradle / Ivy

The newest version!
package com.ideaaedi.commonds.security;

import com.ideaaedi.commonds.exception.CryptographyRuntimeException;
import org.apache.commons.lang3.tuple.Pair;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
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公钥/私钥 工具类
 *
 * @author JustryDeng 
 * @since  2020/5/10 14:48:13
 */
@SuppressWarnings("unused")
public final class RSA extends BaseSecuritySupport {
    
    private RSA() {
        throw new UnsupportedOperationException("util class cannot supported instance");
    }
    
    private static final String KEY_ALGORITHM = "RSA";
    
    private static final String PUBLIC_KEY = "RSAPublicKey";
    
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    
    /**
     * 公钥加密
     *
     * @param content
     *         需要被加密的内容
     * @param publicKeyStr
     *         公钥
     *
     * @return 加密后的内容
     */
    public static String encrypt(String content, String publicKeyStr) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
            InvalidKeyException {
        PublicKey publicKey = loadPublicKeyByStr(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64.encode(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    }
    
    /**
     * 公钥加密
     *
     * @param content
     *         需要被加密的内容
     * @param publicKeyStr
     *         公钥
     *
     * @return 加密后的内容
     */
    public static String encryptSilently(String content, String publicKeyStr) {
        try {
            return RSA.encrypt(content, publicKeyStr);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new CryptographyRuntimeException(String.format("content -> %s, publicKeyStr -> %s", content, publicKeyStr), e);
        }
    }
    
    /**
     * 私钥解密
     *
     * @param content
     *         需要被解密的内容
     * @param privateKeyStr
     *         私钥
     *
     * @return 解密后的内容
     */
    public static String decrypt(String content, String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        PrivateKey privateKey = loadPrivateKeyByStr(privateKeyStr);
        byte[] contentBytes = Base64.decode(content);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(contentBytes), StandardCharsets.UTF_8);
    }
    
    /**
     * 私钥解密
     *
     * @param content
     *         需要被解密的内容
     * @param privateKeyStr
     *         私钥
     *
     * @return 解密后的内容
     */
    public static String decryptSilently(String content, String privateKeyStr) {
        try {
            return RSA.decrypt(content, privateKeyStr);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new CryptographyRuntimeException(String.format("content -> %s, privateKeyStr -> %s", content, privateKeyStr), e);
        }
    }
    
    /**
     * 生成RSA公私钥
     *
     * @return 
    *
  • 左-公钥
  • *
  • 右-私钥
  • *
*/ public static Pair generateRsaKeyPair() throws NoSuchAlgorithmException { Map keyMap = initKey(); Key publicKey = (Key) keyMap.get(PUBLIC_KEY); String publicKeyStr = Base64.encode(publicKey.getEncoded()); Key privateKey = (Key) keyMap.get(PRIVATE_KEY); String privateKeyStr = Base64.encode(privateKey.getEncoded()); return Pair.of(publicKeyStr, privateKeyStr); } /** * 生成RSA公私钥 * * @return
    *
  • 左-公钥
  • *
  • 右-私钥
  • *
*/ public static Pair generateRsaKeyPairSilently() { try { return RSA.generateRsaKeyPair(); } catch (NoSuchAlgorithmException e) { throw new CryptographyRuntimeException(e); } } /** * 将字符串私钥转换为RSAPrivateKey * * @param privateKeyStr * 字符串私钥 * * @return RSAPrivateKey实例 */ private static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] privateKey = Base64.decode(privateKeyStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } /** * 将字符串公钥转换为RSAPublicKey * * @param publicKeyStr * 字符串公钥 * @throws NoSuchAlgorithmException 当算法不支持时抛出 * @throws InvalidKeySpecException 当key无效时抛出 * @return RSAPublicKey实例 */ private static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] publicKey = Base64.decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } /** * 初始化key */ private static Map initKey() throws NoSuchAlgorithmException { // 获取密钥对生成器 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); // 设置密钥位数 keyPairGen.initialize(3072); // 生成密钥对 KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map keyMap = new HashMap<>(4); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy