栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[java基础]RSA加密

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[java基础]RSA加密

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;


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);
    }


    
    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";


    
    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;
    }
    
    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;

    }

    
    public static String generateDownload(List resourceVoList,List 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);

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959570.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号