package com.ruoyi.common.utils;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
|
import javax.crypto.Cipher;
|
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 {
|
|
|
/**
|
* 数据解密
|
*
|
* @param encryptedData
|
* @return
|
*/
|
public String decryptedData(String encryptedData, String pri_key) {
|
String privateKeyString = "私钥的Base64编码字符串"; // 后端私钥的Base64编码字符串
|
|
try {
|
// 将私钥Base64编码字符串转换为PrivateKey对象
|
byte[] privateKeyBytes = Base64.getDecoder().decode(pri_key);
|
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
|
|
// 使用私钥解密数据
|
Cipher decryptCipher = Cipher.getInstance("RSA");
|
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
|
byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedData));
|
|
// 解密后的数据
|
String decryptedData = new String(decryptedBytes);
|
System.out.println("解密后的数据:" + decryptedData);
|
return decryptedData;
|
} catch (Exception e) {
|
log.error("解密报错了:{}", e.getMessage());
|
}
|
return null;
|
}
|
|
/**
|
* 要加密的明文数据
|
*
|
* @param plainText
|
* @return
|
*/
|
public String encryptedData(String plainText, String pub_key) {
|
String publicKeyString = "公钥的Base64编码字符串"; // 前端传递的公钥字符串
|
// 将公钥Base64编码字符串转换为PublicKey对象
|
try {
|
|
byte[] publicKeyBytes = Base64.getDecoder().decode(pub_key);
|
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
PublicKey publicKey = keyFactory.generatePublic(keySpec);
|
|
// 使用公钥加密数据
|
Cipher encryptCipher = Cipher.getInstance("RSA");
|
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
byte[] encryptedBytes = encryptCipher.doFinal(plainText.getBytes());
|
|
// 将加密后的数据转换为Base64编码的字符串
|
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
|
System.out.println("加密后的数据:" + encryptedText);
|
return encryptedText;
|
} catch (Exception e) {
|
log.error("加密失败了:{}", e.getMessage());
|
}
|
return null;
|
}
|
|
|
}
|