Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.8 kB
1
Indexable
Never
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAKeyToPEM {

    public static void main(String[] args) throws Exception {
        // Generate RSA key pair
        KeyPair keyPair = generateRSAKeyPair();

        // Save private key to PEM file
        savePrivateKeyToPEM(keyPair.getPrivate(), "private_key.pem");

        // Save public key to PEM file
        savePublicKeyToPEM(keyPair.getPublic(), "public_key.pem");
    }

    private static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // You can choose the key size
        return keyPairGenerator.generateKeyPair();
    }

    private static void savePrivateKeyToPEM(PrivateKey privateKey, String filePath) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        saveToPEM(filePath, "PRIVATE KEY", spec.getEncoded());
    }

    private static void savePublicKeyToPEM(PublicKey publicKey, String filePath) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey.getEncoded());
        saveToPEM(filePath, "PUBLIC KEY", spec.getEncoded());
    }

    private static void saveToPEM(String filePath, String type, byte[] keyBytes) throws Exception {
        String pemString = "-----BEGIN " + type + "-----\n" +
                Base64.getEncoder().encodeToString(keyBytes) +
                "\n-----END " + type + "-----\n";

        Path path = Paths.get(filePath);
        Files.write(path, pemString.getBytes());
    }
}
Leave a Comment