I have a certificate as .p12 file to connect to FTP server. I have never used such certificate for connection before.
So my ordinary FTP connection is:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpServer, ftpPort);
ftpClient.login(ftpUser, ftpPassword);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = ftpClient.listFiles();
...
Also I can retrieve some information from .p12 file:
FileInputStream is = new FileInputStream("d:\\temp\\cert\\$126805.p12");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, passwordCertificate.toCharArray());
String alias = "my_alias";
Key key = keystore.getKey(alias, passwordCertificate.toCharArray());
if (key instanceof PrivateKey) {
// Get certificate of public key
Certificate cert = keystore.getCertificate(alias);
// Get public key
PublicKey publicKey = cert.getPublicKey();
System.out.println("Public key: " + publicKey);
System.out.println("Key: " + key);
// Return a key pair
new KeyPair(publicKey, (PrivateKey) key);
}
How can I connect to FTP using the information from .p12 file?
Addition. I have done the following steps:
- Imported the PKCS12 file into a keystore:
keytool -importkeystore -srckeystore $126805.p12 -destkeystore keystore.jks -srcstoretype pkcs12
Apply the code:
String keystoreFile = "D:\\temp\\cert\\keystore.jks"; String passwordKeyStore = "123456"; File storeFile = new File(keystoreFile); KeyStore keyStore = loadStore("JKS", storeFile, passwordKeyStore); X509TrustManager defaultTrustManager = TrustManagerUtils.getDefaultTrustManager(keyStore); String protocol = "SSL"; FTPSClient client = new FTPSClient(protocol, true); //also I tried FTPSClient client = new FTPSClient(protocol, false); client.setTrustManager(defaultTrustManager); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); String host = "ftp_host_name"; System.out.println("**** Connect to host ****"); client.connect(host);//Here I get an Exception ...
Where
private KeyStore loadStore(String storeType, File storePath, String storePass)
throws KeyStoreException, IOException, GeneralSecurityException {
KeyStore ks = KeyStore.getInstance(storeType);
FileInputStream stream = null;
try {
stream = new FileInputStream(storePath);
ks.load(stream, storePass.toCharArray());
} finally {
Util.closeQuietly(stream);
}
return ks;
}
During connection I receive the following error:
Could not connect to server. java.net.ConnectException: Connection timed out: connect
The same behaviour I get when I don't use any trustManager. It seems that for some reasons certificate is not applied properly.
Could anyone give me any suggestions?