Extracting private key in java

Deadly 提交于 2019-12-06 00:37:59

If you want to save the private key to a file use

byte[] privateKeyBytes = privKey.getEncoded();

This returns the key in DER encoded (binary) format.

In case you want just to display the contained values on the console just print it using toString():

System.out.println(privKey);

BouncyCastle has the useful PEMWriter class that you can use to write the private key to a file in PEM format (this is what tools like OpenSSH and curl expect).

PEMWriter privatepemWriter = new PEMWriter(new FileWriter(filename)));
privatepemWriter.writeObject(privKey);
privatepemWriter.close();

Otherwise you can just save the byte array from the private key which is the DER format also used by many tools.

Finally you can write it to a JKS keystore used by other java programs using this:

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null);
keyStore.setKeyEntry("some alias", privKey, somePassword.toCharArray(), chain[0]));
FileOutputStream fos = new FileOutputStream(filename);
keyStore.store(fos, somePassword.toCharArray());
fos.close();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!