package com.ruoyi.common.utils.rsa; import com.alibaba.fastjson.JSONObject; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.KeyFactory; import java.security.interfaces.RSAPublicKey; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.Date; /** * token 加密工具类 */ public class RSAPublicUtils { private static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJYJcyDY6o29eo4/5AII88CnalMb8OFtLiTBWxu4UYHR5TYttHJk5dPvK/0hsAnz8WZsfP4bc8kGrA60eQIikOcCAwEAAQ=="; /** * RSA公钥加密 * * @param input 加密字符串 * publicKey 公钥 * @return 密文 * @throws Exception 加密过程中的异常信息 */ public static String encrypt(String input) throws Exception { ByteArrayOutputStream bops = null; String encodeToString = null; try{ //base64编码的公钥 byte[] decoded = Base64.getDecoder().decode(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); // 标识 byte[] bytes = input.getBytes(); int inputLen = bytes.length; int offLen = 0;//偏移量 int i = 0; bops = new ByteArrayOutputStream(); while(inputLen - offLen > 0){ byte [] cache; if(inputLen - offLen > 53){ cache = cipher.doFinal(bytes, offLen,53); }else{ cache = cipher.doFinal(bytes, offLen,inputLen - offLen); } bops.write(cache); i++; offLen = 53 * i; } bops.close(); byte[] encryptedData = bops.toByteArray(); encodeToString = Base64.getEncoder().encodeToString(encryptedData); }catch (Exception e){ e.printStackTrace(); throw new Exception("加密异常"); }finally { if(bops != null){ bops.close(); } } return encodeToString; } public static void main(String[] args) throws Exception { JSONObject param = new JSONObject(); param.put("userId", "1111"); param.put("date", new Date().getTime()); String message = param.toJSONString(); System.out.println("原文:" + message); String messageEn = encrypt(message); System.out.println("密文:" + messageEn); } }