Java 根据公钥对明文进行RSA加密

示例代码:

java 复制代码
import javax.crypto.Cipher;
import java.security.PublicKey;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;

public class RSAUtil {
    /**
     * RSA加密
     * @param publicKeyStr 公钥字符串
     * @param plainText 明文字符串
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String encryptByPublicKey(String publicKeyStr, String plainText) throws Exception {
        // 将公钥字符串转换为公钥对象
        byte[] publicKeyBytes = Base64.decodeBase64(publicKeyStr);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对明文进行加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] plainTextBytes = plainText.getBytes("UTF-8");
        byte[] encryptedBytes = cipher.doFinal(plainTextBytes);

        // 将加密后的字节数组转换为字符串
        return Base64.encodeBase64String(encryptedBytes);
    }
}

// 使用示例:
String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQzJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJwIDAQAB";
String plainText = "Hello, world!";
String encryptedText = RSAUtil.encryptByPublicKey(publicKeyStr, plainText);
System.out.println(encryptedText); // 输出:LJ5zJzJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJwJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJzvJZzjJw==
相关推荐
喵叔哟3 分钟前
重构代码之移动字段
java·数据库·重构
喵叔哟3 分钟前
重构代码之取消临时字段
java·前端·重构
fa_lsyk5 分钟前
maven环境搭建
java·maven
Daniel 大东24 分钟前
idea 解决缓存损坏问题
java·缓存·intellij-idea
wind瑞30 分钟前
IntelliJ IDEA插件开发-代码补全插件入门开发
java·ide·intellij-idea
HappyAcmen31 分钟前
IDEA部署AI代写插件
java·人工智能·intellij-idea
马剑威(威哥爱编程)36 分钟前
读写锁分离设计模式详解
java·设计模式·java-ee
鸽鸽程序猿37 分钟前
【算法】【优选算法】前缀和(上)
java·算法·前缀和
修道-032338 分钟前
【JAVA】二、设计模式之策略模式
java·设计模式·策略模式
九圣残炎43 分钟前
【从零开始的LeetCode-算法】2559. 统计范围内的元音字符串数
java·算法·leetcode