Our Products:   CompleteFTP  edtFTPnet/Free  edtFTPnet/PRO  edtFTPj/Free  edtFTPj/PRO
0 votes
2.8k views
in Java FTP by (160 points)
I am trying to use the SSLFTPClient with loadClientKeyFile() and an InputStream parameter. The problem that I am having is my client cert resides in the database and I only have access to it as a Java KeyStore. I can get the certificate parts to correctly PEM encode but the PrivateKey does not encode correctly. Does anyone know how to get a correct PEM encoded PrivateKey from a KeyStore object?

I am doing something like the following, but the private key I get is invalid.

public static String getPEMFromPrivateKey( PrivateKey privateKey ) throws
CertificateEncodingException, IOException, Base64FormatException,
NoSuchAlgorithmException, InvalidKeySpecException {
String strPEM = null;
if (privateKey != null)
{

KeyFactory rsakf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
RSAPrivateKey rsaPrivKey= (RSAPrivateKey) rsakf.generatePrivate(privKeySpec);

byte[] baDER = rsaPrivKey.getEncoded();
ByteArrayOutputStream baosPEM = new ByteArrayOutputStream();
baosPEM.write("-----BEGIN RSA PRIVATE KEY-----".getBytes());
baosPEM.write("\n".getBytes());
baosPEM.write(Base64.encode(baDER));
baosPEM.write("\n".getBytes());
baosPEM.write("-----END RSA PRIVATE KEY-----".getBytes());
baosPEM.write("\n".getBytes());

strPEM = baosPEM.toString();
}
return (strPEM);
}

Anyone have any ideas on this?

2 Answers

0 votes
by (160 points)
Thanks for your followup! While this works, we are reluctant to add a depencency on EDT to our KeyStore Util. My co worker came up with another solution using the BouncyCastly crypto library.

ByteArrayInputStream bais = new ByteArrayInputStream(privateKey.getEncoded());
ASN1InputStream asn1InputStream = new ASN1InputStream(bais);
PrivateKeyInfo privateInfo =
new PrivateKeyInfo ( (DERSequence)asn1InputStream.readObject() );
RSAPrivateKeyStructure privateStructure =
new RSAPrivateKeyStructure ( (DERSequence)privateInfo.getPrivateKey() );
asn1InputStream.close();
bais.close();

byte[] baDER = privateStructure.getDEREncoded();

Thanks
0 votes
by (51.6k points)
Thanks for sharing!

- Hans (EDT)

Categories

...