RSA公私钥加解密方式-工具类

直接上代码

​
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
/**
 * @author yao
 * @create 2018/1/20
 */
public class RSAEncrypt {
    private static final String ALGORITHM = "RSA";
    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static final int MAX_DECRYPT_BLOCK = 128;
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥

    public static final Integer PUBLICKEY = 0;//0表示公钥
    public static final Integer PRIVATEKEY = 1;//1表示私钥


    public RSAEncrypt() {
    }

    /**
     * 公钥加密
     * @param str 明文参数
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    public static String encryptPublic(String str, String publicKey) throws Exception {
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey)KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = getCipher(1, pubKey);
        return splitEncrypt(str, cipher, pubKey.getModulus());
    }
    /**
     * 私钥加密
     * @param str 明文参数
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String encryptPrivate(String str, String privateKey) throws Exception {
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = getCipher(1, priKey);
        return splitEncrypt(str, cipher, priKey.getModulus());
    }
    /**
     * 公钥解密
     * @param str  密文参数
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    public static String decryptPublic(String str, String publicKey) throws Exception {
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey)KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = getCipher(2, pubKey);
        return splitDecrypt(str, cipher, pubKey.getModulus());
    }

    /**
     * 私钥解密
     * @param str  密文参数
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String decryptPrivate(String str, String privateKey) throws Exception {
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = getCipher(2, priKey);
        return splitDecrypt(str, cipher, priKey.getModulus());
    }

    private static String splitDecrypt(String str, Cipher cipher, BigInteger modulus) throws Exception {
        byte[] bytes = Base64.decodeBase64(str);
        int inputLen = bytes.length;
        int offLen = 0;
        int i = 0;

        ByteArrayOutputStream byteArrayOutputStream;
        byte[] cache;
        for(byteArrayOutputStream = new ByteArrayOutputStream(); inputLen - offLen > 0; offLen = 128 * i) {
            if (inputLen - offLen > 128) {
                cache = cipher.doFinal(bytes, offLen, 128);
            } else {
                cache = cipher.doFinal(bytes, offLen, inputLen - offLen);
            }

            byteArrayOutputStream.write(cache);
            ++i;
        }

        byteArrayOutputStream.close();
        cache = byteArrayOutputStream.toByteArray();
        return new String(cache);
    }

    private static Cipher getCipher(int model, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(model, key);
        return cipher;
    }

    private static String splitEncrypt(String str, Cipher cipher, BigInteger modulus) throws Exception {
        byte[] bytes = str.getBytes();
        int inputLen = bytes.length;
        int offLen = 0;
        int i = 0;

        ByteArrayOutputStream bops;
        byte[] cache;
        for(bops = new ByteArrayOutputStream(); inputLen - offLen > 0; offLen = 117 * i) {
            if (inputLen - offLen > 117) {
                cache = cipher.doFinal(bytes, offLen, 117);
            } else {
                cache = cipher.doFinal(bytes, offLen, inputLen - offLen);
            }

            bops.write(cache);
            ++i;
        }

        bops.close();
        cache = bops.toByteArray();
        String encodeToString = Base64.encodeBase64String(cache);
        return encodeToString;
    }

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(PUBLICKEY ,publicKeyString); 
        keyMap.put(PRIVATEKEY ,privateKeyString); 
    }

    public static void main(String[] args) throws Exception {
        //参数
        String str = "{\"test\":\"001\"}";
        System.out.println("参数:" + str);
        //随机生成密钥对
        genKeyPair();
        //公钥加密
        System.out.println("公钥:" + keyMap.get(PUBLICKEY));
        System.out.println("私钥:" + keyMap.get(PRIVATEKEY));
        String encrypt = RSAEncrypt.encryptPublic(str, keyMap.get(PUBLICKEY));
        System.out.println("公钥加密:" + encrypt);
        //私钥解密
        String decrypt = RSAEncrypt.decryptPrivate(encrypt, keyMap.get(PRIVATEKEY));
        System.out.println("私钥解密:" + decrypt);

        //私钥加密
        String encryptPrivate = RSAEncrypt.encryptPrivate(str, keyMap.get(PRIVATEKEY));
        System.out.println("私钥加密:" + encryptPrivate);
        //公钥解密
        String decryptPublic = RSAEncrypt.decryptPublic(encryptPrivate, keyMap.get(PUBLICKEY));
        System.out.println("公钥解密:" + decryptPublic);

    }
}

​

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人类幼崽养成记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值