rsa的公钥加密私钥解密和私钥加密公钥解密,rsa公钥私钥加解密

package com.my.demo.utils;

import com.my.demo.common.Constants;
import com.my.experiment.exception.OptException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;



@Component
@Slf4j
public class RsaUtil {
    private static final String KEY_ALGORITHM = "RSA";
    private static final String PK = Constants.getPublicKey();
    private static final String SK = Constants.getPrivateKey();

    /**
     * 使用RSA公钥加密
     */

    public static String encryptByPublicKey(String str) {
        return Base64.encodeBase64String(getMaxResultEncrypt(str, getPublicKey(Cipher.ENCRYPT_MODE)));
    }
    /**
     * 使用公钥解密
     */
    public static String decryptByPublicKey(String data) {
        try {
            return new String(getMaxResultDecrypt(data, getPublicKey(Cipher.DECRYPT_MODE)));
        }catch (Exception e){
            throw new OptException("解密失败|"+e.getMessage());
        }
    }
    /**
     * 使用RSA私钥解密
     *
     * @param str 加密字符串
     */
    public static String decryptByPrivateKey(String str) {
        return new String(getMaxResultDecrypt(str, getPrivateKey(Cipher.DECRYPT_MODE)));
    }

    /**
     * 使用RSA私钥加密
     * @param data       加密数据
     */
    public static String encryptByPrivateKey(String data) {
        try {
            return Base64.encodeBase64String(getMaxResultEncrypt(data, getPrivateKey(Cipher.ENCRYPT_MODE)));
        } catch (Exception e) {
            throw new OptException("加密失败|"+e.getMessage());
        }
    }
    /**
     * 当长度过长的时候,需要分割后加密 117个字节
     */
    private static byte[] getMaxResultEncrypt(String str, Cipher cipher){
        try {
            byte[] inputArray = str.getBytes(StandardCharsets.UTF_8.name());
            int inputLength = inputArray.length;
            // 最大加密字节数,超出最大字节数需要分组加密
            int maxEncryptBlock = 117;
            // 标识
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache;
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > maxEncryptBlock) {
                    cache = cipher.doFinal(inputArray, offSet, maxEncryptBlock);
                    offSet += maxEncryptBlock;
                } else {
                    cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }
            return resultBytes;
        }catch (Exception e){
            e.printStackTrace();
            throw new OptException("加密处理失败,"+e.getMessage());
        }
    }

    /**
     * 当长度过长的时候,需要分割后解密 128个字节
     */
    private static byte[] getMaxResultDecrypt(String str, Cipher cipher) {
        try {
            byte[] inputArray = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8.name()));
            int inputLength = inputArray.length;
            // 最大解密字节数,超出最大字节数需要分组加密
            int maxEncryptBlock = 128;
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache;
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > maxEncryptBlock) {
                    cache = cipher.doFinal(inputArray, offSet, maxEncryptBlock);
                    offSet += maxEncryptBlock;
                } else {
                    cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }
            return resultBytes;
        }catch (Exception e){
            e.printStackTrace();
            throw new OptException("解密数据处理异常,"+e.getMessage());
        }
    }
    /**
     * 根据加解密类型处理公钥
     *
     */
    public static Cipher getPublicKey(int mode) {
        try {
            String publicKey = formatString(PK);
            byte[] decoded = Base64.decodeBase64(publicKey);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decoded);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey key = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(mode, key);
            return cipher;
        } catch (Exception e) {
            throw new OptException("转换公钥异常====>>" + e.getMessage());
        }
    }

    /**
     * 根据加解密类型处理私钥
     */
    public static Cipher getPrivateKey(int mode) {
        try {
            //mode 加解密模式 ENCRYPT_MODE = 1  DECRYPT_MODE = 2
            String privateKey = formatString(SK);
            byte[] decoded = Base64.decodeBase64(privateKey);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decoded);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(mode, key);
            return cipher;
        } catch (Exception e) {
            throw new OptException("转换私钥异常====>>" + e.getMessage());
        }
    }
    public static String formatString(String source) {
        if (source == null) {
            return null;
        }
        return source.replace("\\r", "").replace("\\n", "").trim().replace(" ","");
    }
    public static void main(String[] args) throws Exception {
        String xxStr = "阿什顿放假啊是www";
        //加密
        String bytes1 = RsaUtil.encryptByPrivateKey(xxStr);
        String bytes2 = RsaUtil.encryptByPublicKey(xxStr);
        log.info("公钥加密2:{}",bytes2);
        log.info("私钥加密1:{}",bytes1);

        //解密
        log.info("私钥解密密2:{}",RsaUtil.decryptByPrivateKey(bytes2));
        log.info("公钥解密密1:{}",RsaUtil.decryptByPublicKey(bytes1));

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

axwlj

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

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

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

打赏作者

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

抵扣说明:

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

余额充值