import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import java.io.FileWriter; import java.io.IOException; import java.security.*; public class RSAKeyGenerator { //密码加密位数 private static final int KEY_SIZE = 2048; public static void main(String[] args) { try { // 添加Bouncy Castle作为安全提供程序 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 将私钥保存到.pem文件 saveKeyToPemFile(keyPair.getPrivate(), "private.pem"); // 将公钥保存到.pem文件 saveKeyToPemFile(keyPair.getPublic(), "public.pem"); System.out.println("RSA密钥对已生成并保存到.pem文件中。"); } catch (Exception e) { e.printStackTrace(); } } private static void saveKeyToPemFile(Key key, String filename) throws IOException { try (JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(filename))) { pemWriter.writeObject(key); } } }