RSA的加密和解密

public class RSA {
    /**
     * 加载私钥
     *
     * @param privateKeyStr 私钥
     * @throws Exception 异常
     */
    private static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {

        byte[] key = Base64.decode(privateKeyStr, Base64.DEFAULT);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keys = Base64.decode(publicKey, Base64.DEFAULT);

        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keys);
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param key
     * @return
     */
    public static String publicEncrypt(String data, String key) {

        try {
            RSAPublicKey publicKey = getPublicKey(key);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            int length = publicKey.getModulus().bitLength();
            byte[] bytes = data.getBytes("UTF-8");
            byte[] codes = rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, bytes, length);

            return Base64.encodeToString(codes, Base64.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }


    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();

        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultDatas;
    }


    /**
     * 解码密文
     *
     * @param privateKey       私钥
     * @param rsaBase64Context base64加密的字符串
     * @return 解密后的内容
     */
    public static String getDecryptString(String privateKey, String rsaBase64Context) {
        try {
            RSAPrivateKey key = loadPrivateKey(privateKey);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptData = Base64.decode(rsaBase64Context, Base64.DEFAULT);

            ByteArrayOutputStream out = new ByteArrayOutputStream(encryptData.length);
            int BLOCK_SIZE = 128;
            for (int i = 0; i < encryptData.length; i += BLOCK_SIZE) {
                int leftBytes = encryptData.length - i;
                int length = (leftBytes <= BLOCK_SIZE) ? leftBytes : BLOCK_SIZE;
                out.write(cipher.doFinal(encryptData, i, length));
            }
            String string = new String(out.toByteArray(), "UTF-8");
            System.out.println("RAS.Decrpyt.Result = " + string);
            System.out.println("RAS.Decrpyt.Length = " + string.length());
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取密钥信息
     *
     * @param in 输入流
     * @return 密钥
     * @throws IOException io
     */
    public static String readKey(InputStream in) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) == '-') {
                continue;
            } else {
                sb.append(readLine);
                sb.append('\r');
            }
        }

        return sb.toString();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值