package com.ruoyi.common.utils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.crypto.Cipher; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; 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.Base64; @Slf4j @Component public class RSAPublicKeyExample { public static String encryptedData(String plainText, String pubKey) { try { byte[] publicKeyBytes = Base64.getDecoder().decode(pubKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); // Base64 编码(必须保留) String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes); // 可选:如果用于 URL 传输,再进行 URL 编码 return URLEncoder.encode(encryptedText, StandardCharsets.UTF_8.toString()); } catch (Exception e) { System.err.println("加密失败: " + e.getMessage()); e.printStackTrace(); return null; } } /** * RSA 私钥解密(解密 Base64 编码后的密文,支持 URL 解码) */ public static String decryptedData(String encryptedData, String priKey) { try { // 可选:先 URL 解码(如果加密前做了 URLEncoder) String base64Encrypted = URLDecoder.decode(encryptedData, StandardCharsets.UTF_8.toString()); // Base64 解码 byte[] encryptedBytes = Base64.getDecoder().decode(base64Encrypted); byte[] privateKeyBytes = Base64.getDecoder().decode(priKey); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } catch (Exception e) { System.err.println("解密失败: " + e.getMessage()); e.printStackTrace(); return null; } } public static void main(String[] args) { String decodedString = null; try { decodedString = URLDecoder.decode("0902%E4%BB%BB%E5%8A%A1%E6%B5%8B%E8%AF%95--------", "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(decodedString); } }