import java.security.*; import java.security.cert.*; import java.util.Date; import javax.security.auth.x500.X500Principal; import sun.security.x509.*;
<dependencies> <!-- Bouncy Castle Provider --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk18on</artifactId> <version>1.78</version> </dependency> keygen intellij
// Simple demo public static void main(String[] args) throws Exception KeyPair kp = RsaKeyGen.generate(2048); char[] pwd = "changeMe!".toCharArray(); Path keystorePath = Path.of("demo-keystore.p12"); storeRsaKeyPair(kp, "my-rsa-key", pwd, keystorePath); System.out.println("Keystore written to " + keystorePath.toAbsolutePath()); import java
// ---- 2️⃣ Load (or create) a PKCS#12 keystore ---- KeyStore ks = KeyStore.getInstance("PKCS12"); if (Files.exists(filePath)) try (InputStream in = Files.newInputStream(filePath)) ks.load(in, password); else ks.load(null, null); // create empty keystore 3️⃣ Persisting Keys Securely 3
/** * Generates an RSA key pair. * * @param keySize size in bits (2048, 3072, 4096) * @return generated KeyPair * @throws GeneralSecurityException if the algorithm is unavailable */ public static KeyPair generate(int keySize) throws GeneralSecurityException KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(keySize, new SecureRandom()); return kpg.generateKeyPair();
To use 256‑bit AES on older JDKs you might need the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy . Modern JDKs (≥ 8u161) enable it by default. 3️⃣ Persisting Keys Securely 3.1 Java KeyStore (JKS / PKCS12) A KeyStore is the de‑facto standard for storing private keys and certificates. Below is a helper class that writes an RSA key pair (plus a self‑signed certificate) to a PKCS#12 file.
import java.security.*;