|
| 1 | +package dev.findfirst.security.util; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.security.KeyPair; |
| 7 | +import java.security.KeyPairGenerator; |
| 8 | +import java.security.NoSuchAlgorithmException; |
| 9 | +import java.security.PrivateKey; |
| 10 | +import java.security.PublicKey; |
| 11 | +import java.security.spec.PKCS8EncodedKeySpec; |
| 12 | +import java.security.spec.X509EncodedKeySpec; |
| 13 | + |
| 14 | +public class KeyGenerator { |
| 15 | + |
| 16 | + public static void generateKeys(String privateKeyPath, String publicKeyPath) |
| 17 | + throws NoSuchAlgorithmException, IOException { |
| 18 | + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); |
| 19 | + keyGen.initialize(2048); |
| 20 | + KeyPair pair = keyGen.generateKeyPair(); |
| 21 | + PrivateKey privateKey = pair.getPrivate(); |
| 22 | + PublicKey publicKey = pair.getPublic(); |
| 23 | + |
| 24 | + // Save the private key in PKCS8 format |
| 25 | + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); |
| 26 | + try (FileOutputStream fos = new FileOutputStream(privateKeyPath)) { |
| 27 | + fos.write(pkcs8EncodedKeySpec.getEncoded()); |
| 28 | + } |
| 29 | + |
| 30 | + // Save the public key in X.509 format |
| 31 | + X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); |
| 32 | + try (FileOutputStream fos = new FileOutputStream(publicKeyPath)) { |
| 33 | + fos.write(x509EncodedKeySpec.getEncoded()); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + String privateKeyPath = "app.key"; |
| 39 | + String publicKeyPath = "app.pub"; |
| 40 | + |
| 41 | + File privateKeyFile = new File(privateKeyPath); |
| 42 | + File publicKeyFile = new File(publicKeyPath); |
| 43 | + |
| 44 | + if (!privateKeyFile.exists() || !publicKeyFile.exists()) { |
| 45 | + try { |
| 46 | + generateKeys(privateKeyPath, publicKeyPath); |
| 47 | + System.out.println("Keys generated successfully."); |
| 48 | + } catch (NoSuchAlgorithmException | IOException e) { |
| 49 | + e.printStackTrace(); |
| 50 | + } |
| 51 | + } else { |
| 52 | + System.out.println("Keys already exist."); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments