Java Requires Chilkat v11.0.0+
Chilkat2 Java
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.PrivateKey;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rsa;
public class ChilkatExample {
public static void main(String[] args) {
Rsa rsa = new Rsa();
// Generate a 2048-bit key.
PrivateKey privKey = new PrivateKey();
try {
rsa.genKey(2048, privKey);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
String password = "secret";
// Saving to a relative path (from the current working directory of the process).
String path = "rsaKeys/myTestRsaPrivate.pem";
// Encrypt the PEM using 256-bit AES encryption.
privKey.setPkcs8EncryptAlg("aes256");
try {
privKey.savePkcs8EncryptedPemFile(password, path);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
//
// We can also save the public key.
// There is no need to encrypt public keys.
PublicKey pubKey = new PublicKey();
privKey.toPublicKey(pubKey);
path = "rsaKeys/myTestRsaPublic.pem";
// Choose PKCS1 or PKCS8
// We'll choose PKCS8.
boolean preferPkcs1 = false;
try {
pubKey.savePemFile(preferPkcs1, path);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
//
System.out.println("Success.");
}
}