Search code examples
encryptionrsaprivate-keypublic-key

Using Keytool in a java program?


I am trying to write a program to generate RSA keys private.der, and public.der in PKCS#8, DER format.

I can do it in OpenSSL manually easily, but I have no idea how to do it in java. I read about Keytool that you can also use manually. But I want to automate the process in a program to generate a unique usable keypair each time the program is ran, and export them to a folder.

Any help would be appreciated.


Solution

  • Key generation works as follows:

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048); // Keysize
    KeyPair kp = keyGen.genKeyPair():
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    

    Then use privKey.getEncoded() and pubKey.getEncoded() to get the encoded versions.