示例代码:
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==