java 用bouncycastle 生成pem格式的rsa

maven  pem.xml

<dependency>  
    <groupId>org.bouncycastle</groupId>  
    <artifactId>bcprov-jdk15on</artifactId>  
    <version>1.70</version> <!-- 请根据需要检查最新版本 -->  
</dependency>

 

java 用bouncycastle 生成pem格式的rsa

import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;  
import org.bouncycastle.asn1.x500.X500Name;  
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;  
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;  
import org.bouncycastle.cert.X509v1CertificateBuilder;  
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;  
import org.bouncycastle.cert.jcajce.JcaX509v1CertificateGenerator;  
import org.bouncycastle.jce.provider.BouncyCastleProvider;  
import org.bouncycastle.openssl.PEMKeyPair;  
import org.bouncycastle.openssl.PEMParser;  
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;  
import org.bouncycastle.operator.ContentSigner;  
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;  
  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.StringWriter;  
import java.math.BigInteger;  
import java.security.*;  
import java.security.cert.X509Certificate;  
import java.util.Date;  
  
public class RSAGenerator {  
  
    static {  
        Security.addProvider(new BouncyCastleProvider());  
    }  
  
    public static void main(String[] args) throws Exception {  
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");  
        keyPairGenerator.initialize(2048);  
        KeyPair keyPair = keyPairGenerator.generateKeyPair();  
  
        // 保存公钥为PEM格式  
        StringWriter publicKeyWriter = new StringWriter();  
        try (JcaPEMWriter pemWriter = new JcaPEMWriter(publicKeyWriter)) {  
            pemWriter.writeObject(keyPair.getPublic());  
        }  
        String publicKeyPem = publicKeyWriter.toString();  
  
        // 保存私钥为PKCS#8 PEM格式  
        StringWriter privateKeyWriter = new StringWriter();  
        try (JcaPEMWriter pemWriter = new JcaPEMWriter(privateKeyWriter)) {  
            pemWriter.writeObject(keyPair.getPrivate());  
        }  
        String privateKeyPem = privateKeyWriter.toString();  
  
        System.out.println("Public Key (PEM):");  
        System.out.println(publicKeyPem);  
        System.out.println("Private Key (PKCS#8 PEM):");  
        System.out.println(privateKeyPem);  
    }  
}

 

posted @ 2024-07-05 14:44  ☆♂安♀★  阅读(27)  评论(0编辑  收藏  举报