December 13, 2016

Create PublicKey and PrivateKey in Java 8

import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.PublicKey;
import java.security.PrivateKey;

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048, SecureRandom.getInstanceStrong());
KeyPair keyPair = keyPairGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

See also sun.security.tools.keytool.CertAndKeyGen.