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

示例代码:

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==
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值