4

I have been using java's KeyPairGenerator in order to generate public/private keys within a program so that I can encrypt and decrypt files(also using java encrypt/decrypt methods). I want to be able to move over to using openssl in order to generate these public private keypairs however I keep getting padding exceptions when I decrypt my files. For example instead of using java's KeyPairGenerator, I try and use openssl to generate keys:

openssl rsa -in keypair.pem -outform DEF -pubout -out public.der
openssl pkcs8 -topk8 -nocrypt -in keypair.pem -outform DER -out private.der

Where I try to use the DER files to encrypt/decrypt my files.

I'm assuming that this means that the format of the keys in my openssl commands do not match up how java's KeyPairGenerator works. Here is a snippet of my key generating code:

public void createPublicPrivateKeys() throws IOException, NoSuchAlgorithmException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    logger.info("Password to encrypt the private key: ");
    String password = in.readLine();
    logger.info("Generating an RSA keypair.");

    // Create an RSA key key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(4096);
    KeyPair keyPair = keyPairGenerator.genKeyPair();

    logger.info("Done generating the keypair.\n");

    // Write public key out to a file
    String publicKeyFilename = "publicKey.der";
    logger.info("Public key filename: " + publicKeyFilename);

    // Get  encoded form of the public key for future usage -- this is X.509 by default.
    byte[] publicKeyBytes = keyPair.getPublic().getEncoded();

    // Write the encoded public key
    FileOutputStream fos = new FileOutputStream(publicKeyFilename);
    fos.write(publicKeyBytes);
    fos.close();

    String privateKeyFilename = "privateKey.der";
    logger.info("Private key filename: " + privateKeyFilename);

    // Get the encoded form -- PKCS#8 by default.
    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();

    // Encrypt the password
    byte[] encryptedPrivateKeyBytes = new byte[0];
    try {
        encryptedPrivateKeyBytes = passwordEncrypt(password.toCharArray(), privateKeyBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

    fos = new FileOutputStream(privateKeyFilename);
    fos.write(encryptedPrivateKeyBytes);
    fos.close();
}

What is the openssl equivalent of using java's KeyPairGenerator? Also note that using outside packages such as bouncy castle is not an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.