In Java, The KeyPairGenerator class is used to create a pair of private/public keys. Java supports below three basic types of algorithms with keysize in parenthesis:
Read more
(1024)DiffieHellman - DSA (1024)
- RSA (1024, 2048)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
public class GenerateKeysEncoded {
private KeyPairGenerator keyGen;
private KeyPair pair;
private PrivateKey privateKey;
private PublicKey publicKey;
public GenerateKeysEncoded(int keylength, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
this.keyGen = KeyPairGenerator.getInstance(algorithm);
this.keyGen.initialize(keylength);
}
public void createKeys() {
this.pair = this.keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}
public PrivateKey getPrivateKey() {
return this.privateKey;
}
public PublicKey getPublicKey() {
return this.publicKey;
}
public void writeToFile(String path, byte[] key) throws IOException {
File f = new File(path);
f.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(f);
fos.write(key);
fos.flush();
fos.close();
}
public static void main(String[] args) {
GenerateKeysEncoded gk;
try {
gk = new GenerateKeysEncoded(1024, "RSA");
gk.createKeys();
gk.writeToFile("publicKey", gk.getPublicKey().getEncoded());
gk.writeToFile("privateKey", gk.getPrivateKey().getEncoded());
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}