[java基础]RSA加密

该博客介绍了如何在Java中使用Hutool库进行RSA加密,包括正常加密和应对超过最大加密字节数的分组加密。通过示例展示了加密、解密过程,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rsa加密

项目中用到了rsa加密,
对接时发现最大加密字节数117,超出最大字节数需要分组加密

1.正常加密


package com.plan.License;

import com.alibaba.fastjson.JSON;

import java.text.SimpleDateFormat;
import java.util.Base64;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;

/**
 * 非分组加密
 * 使用hutool工具类中的rsa工具*/
public class RSAUsing {

    private static final String PRIVATE_KEY="aaa";
    private static final String  PUBLIC_KEY="bbb";

    /**
     * 获取公钥私钥密钥对
     * */
    public static String getKeyPair(RSA rsa){
        StringBuilder rtnStb=new StringBuilder();
        //获得私钥
        //System.out.println(rsa.getPrivateKey());
        rtnStb.append("privateKey: ");
        rtnStb.append(rsa.getPrivateKeyBase64());
        rtnStb.append("\n");
        //获得公钥
        //System.out.println(rsa.getPublicKey());
        rtnStb.append("publicKey: ");
        rtnStb.append(rsa.getPublicKeyBase64());
        return rtnStb.toString();
    }

    //加密
    public static String getEncryptString(String str, RSA rsa){
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        return Base64.getEncoder().encodeToString(encrypt);
    }

    //解密
    public static String getDecryptString(String str, RSA rsa){
        byte[] aByte = Base64.getDecoder().decode(str);
        byte[] decrypt = rsa.decrypt(aByte, KeyType.PrivateKey);
        return new String(decrypt, CharsetUtil.CHARSET_UTF_8);
    }


    /**
     * 封装生成license
     * @param license
     * @return
     */
    public static String generateLicense123(LicenseVo license) {
        //1.Java对象->Json字符串
        String licenseString = JSONObject.toJSONString(license);
        System.out.println("licenseString"+licenseString);
        //将生成的license加密
        RSA rsa = new RSA();
        String encryptTxt=RSAUsing.getEncryptString(JSON.toJSONString(licenseString), rsa);
        System.out.println("密文"+encryptTxt);
        String decryptTxt=RSAUsing.getDecryptString(encryptTxt, rsa);
        System.out.println("解密"+decryptTxt);
        return encryptTxt;

}


    public static void main(String[] args) {
        String priKey="aaa";
        String pubKey="bbb";
        RSA rsa = new RSA(priKey, pubKey);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String plainTxt="123456789";
        String encryptTxt=getEncryptString(JSON.toJSONString(plainTxt), rsa);
        System.out.println("加密密文:"+encryptTxt);
        String decryptTxt=getDecryptString(encryptTxt, rsa);

        System.out.println("解密后:"+decryptTxt);
    }
}


2.分组加密

package com.plan.License;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.plan.business.domain.vo.PResourceVo;
import com.plan.business.domain.vo.PSoftwareVo;
import net.sf.json.JSONArray;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 分组加密
 */

public class RSAUtils2 {

    private static final String PRIVATE_KEY="aaa";
    private static final String  PUBLIC_KEY="bbb";


    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//  String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        String outStr = null;
        byte[] inputArray = str.getBytes("UTF-8");
        int inputLength = inputArray.length;
        System.out.println("加密字节数:" + inputLength);
        // 最大加密字节数,超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 117;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } 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);
        }
        outStr = Base64.encodeBase64String(resultBytes);
        return outStr;
    }
    /**
     * 封装生成license
     * @param license
     * @return
     */
    public static String generateLicense(LicenseVo license) throws Exception {
        //1.Java对象->Json字符串
        String licenseString = JSONObject.toJSONString(license);
        System.out.println("licenseString"+licenseString);
        //将生成的license加密
        String encryptTxt=RSAUtils2.encrypt(JSON.toJSONString(licenseString),PUBLIC_KEY);
        System.out.println("密文"+encryptTxt);

        return encryptTxt;

    }

    /**
     * 封装生成已下载的json
     * @param
     * @return
     */
    public static String generateDownload(List<PResourceVo> resourceVoList,List<PSoftwareVo> softwareVoList) throws Exception {
        //1.Java集合->Json字符串
        JSONArray jsonArray =null;
        String encryptTxt="";
        if(resourceVoList!=null&&resourceVoList.size()>0){
             jsonArray = JSONArray.fromObject(resourceVoList);
        }else{
             jsonArray = JSONArray.fromObject(softwareVoList);
        }
        encryptTxt=encryptTxt.concat(RSAUtils2.encrypt(jsonArray.toString(),PUBLIC_KEY));
        System.out.println("downloadString"+jsonArray);
        System.out.println("密文"+encryptTxt);
        return encryptTxt;

    }



    public static void main(String[] args) throws Exception {

        String priKey="aaa";
        String pubKey="bbb";
//        RSA rsa = new RSA(priKey, pubKey);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String plainTxt="{\"code\":\"123456789\",\"customerId\":1,\"customerName\":\"客户名称\",\"endTime\":\"2022-10-1\",\"license\":\"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4oZSlP9KlXr8vMN/Yvu/7Rvnu\",\"remarks\":\"备注\",\"startTime\":\"2021-10-1\"}";

        int i = plainTxt.length();
        byte[]  buff = plainTxt.getBytes();

        System.out.println("明文长度:"+buff.length);

        String encryptTxt=encrypt(plainTxt, pubKey);
        System.out.println("加密密文:"+encryptTxt);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值