在Android上设置FTPS服务器/客户端

时间:2017-08-04 21:34:00

标签: java android ssl ftp ftps

我一直在尝试设置支持SSL / TLS的FTP服务器,以及成功连接到此服务器的FTPS客户端。我首先使用本教程链接生成证书/密钥:http://callistaenterprise.se/blogg/teknik/2011/11/24/creating-self-signed-certificates-for-use-on-android/

这生成了一个client.bks,clienttruststore.bks,server.bks,servertruststore.bks(使用了BouncyCastle)。我还创建了一个client.jks和一个clienttruststore.jks,用于非Android设备,仅用于初始测试而不使用BouncyCastle。

一切都很好,没有错误。目前,我正在试验Android上的服务器,并在Netbeans上使用Java在本地运行客户端。我将相应的文件放入客户端(JKS文件)和服务器(BKS文件)。话虽这么说,我仍然遇到连接到服务器的问题,因为我无法找到所请求的目标错误的有效证书路径。我遵循了多个关于如何解决这个问题的教程(包括InstallCert.java教程),但令人惊讶的是无济于事。

我设置我的服务器(使用Apache的FTP服务器库)或客户端(使用Apache Common的库)是错误的吗?

我已在下面附加了我的服务器代码:

        package com.example.gurnaaz.ftpsserver;

        import android.content.pm.PackageManager;
        import android.net.wifi.WifiManager;
        import android.os.Build;
        import android.support.annotation.NonNull;
        import android.support.v4.app.ActivityCompat;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.text.format.Formatter;
        import android.widget.Toast;

        import org.apache.ftpserver.FtpServer;
        import org.apache.ftpserver.FtpServerFactory;
        import org.apache.ftpserver.ftplet.FtpException;
        import org.apache.ftpserver.listener.ListenerFactory;
        import org.apache.ftpserver.ssl.SslConfigurationFactory;
        import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
        import org.apache.ftpserver.usermanager.UsernamePasswordAuthentication;

        import java.io.File;

        public class MainActivity extends AppCompatActivity {
            private static final int REQUEST_CODE = 0x11;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                String[] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"};
                ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE); // without sdk version check




            }

            @Override
            public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);

                if (requestCode == REQUEST_CODE) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // save file
                        FtpServerFactory serverFactory = new FtpServerFactory();
                        ListenerFactory factory = new ListenerFactory();
        // set the port of the listener
                        factory.setPort(3425);

                        SslConfigurationFactory ssl = new SslConfigurationFactory();
                        ssl.setKeystoreFile(new File("storage/emulated/0/Pictures/server.bks"));

                        ssl.setKeystorePassword("abc1234");
                        ssl.setTruststoreFile(new File("storage/emulated/0/Pictures/servertruststore.bks"));
                        ssl.setTruststorePassword("abc1234");
                        factory.setSslConfiguration(ssl.createSslConfiguration());
                        factory.setImplicitSsl(true);
        // replace the default listener
                        serverFactory.addListener("default", factory.createListener());
        // start the server
                        System.out.println("AFTER I LOADED IT");
                        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
                        userManagerFactory.setFile(new File("storage/emulated/0/Pictures/myusers.properties"));
                        serverFactory.setUserManager(userManagerFactory.createUserManager());
                        FtpServer server = serverFactory.createServer();
                        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
                        String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
                        System.out.println("THE IP IS " + ip);
                        try {
                            server.start();
                        } catch (FtpException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "PERMISSION_DENIED", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }

我在下面附上了我的客户代码:

        import java.io.*;
        import java.security.GeneralSecurityException;
        import java.security.KeyStore;
        import java.security.KeyStoreException;
        import java.security.NoSuchAlgorithmException;

        import org.apache.commons.net.PrintCommandListener;
        import org.apache.commons.net.ftp.FTP;
        import org.apache.commons.net.ftp.FTPConnectionClosedException;
        import org.apache.commons.net.ftp.FTPReply;
        import org.apache.commons.net.ftp.FTPSClient;

        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.net.InetAddress;
        import java.net.Socket;
        import java.net.UnknownHostException;
        import javax.net.ssl.KeyManager;
        import javax.net.ssl.KeyManagerFactory;
        import javax.net.ssl.SSLContext;
        import javax.net.ssl.SSLSocketFactory;

        import org.apache.commons.net.PrintCommandListener;
        import org.apache.commons.net.ftp.FTP;
        import org.apache.commons.net.ftp.FTPReply;
        import org.apache.commons.net.ftp.FTPSClient;
        import org.apache.commons.net.io.Util;
        import org.apache.commons.net.util.TrustManagerUtils;

        import javax.net.ssl.TrustManager;
        import javax.net.ssl.TrustManagerFactory;
        import javax.net.ssl.X509TrustManager;



        public final class FTPSExample {


            public static void main(String[] args) throws Exception {
                System.setProperty("javax.net.debug", "ssl");

                String server = "192.168.1.31";
        //        String username = "USER_TEST";
        //        String password = "ABCD1234";
                String remoteFile = "/Data/Input/PH240819";
                String localFile = "PH240819";
                String protocol = "SSL"; // TLS / null (SSL)
                int port = 3425;
                int timeoutInMillis = 5000;

                FTPSClient client = new FTPSClient(protocol, true);
                client.setNeedClientAuth(true);
                KeyStore ks = KeyStore.getInstance("JKS");
                KeyStore ks2 = KeyStore.getInstance("JKS");
                FileInputStream fis = new FileInputStream("C:\\Users\\Gurnaaz\\Favorites\\clientnotandroid.jks");
                FileInputStream fistrust = new FileInputStream("C:\\Users\\Gurnaaz\\Favorites\\clienttruststorenotandroid.jks");
                ks.load(fis, "abc123".toCharArray());
                ks2.load(fistrust,"abc123".toCharArray());
                fis.close();
                fistrust.close();
                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(ks, "abc123".toCharArray());
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(ks2);
                client.setKeyManager(kmf.getKeyManagers()[0]);
                client.setTrustManager(tmf.getTrustManagers()[0]);
                client.setDataTimeout(timeoutInMillis);
                client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

                System.out.println("################ Connecting to Server ################################");

                try {
                    int reply;
                    System.out.println("################ Connect Call ################################");
                    client.connect(server, port);

        //                client.login(username, password);

                    System.out.println("################ Login Success ################################");

                    //client.setFileType(FTP.BINARY_FILE_TYPE);
                    client.setFileType(FTP.NON_PRINT_TEXT_FORMAT);
                    client.execPBSZ(0);  // Set protection buffer size
                    client.execPROT("P"); // Set data channel protection to private
                    client.enterLocalActiveMode();

                    System.out.println("Connected to " + server + ".");
                    reply = client.getReplyCode();
                    System.out.println("AFTER REPLY CODE WHICH IS " + reply);
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        client.disconnect();
                        System.err.println("FTP server refused connection.");
                        System.exit(1);
                    }
                    System.out.println("BEFORE retrieved FILEs");
                   // client.listFiles();
                   // System.out.println("above is the list of patch");
                    boolean retrieved = client.retrieveFile(remoteFile, new FileOutputStream(localFile));
                    System.out.println("Retrieved value: " + retrieved);
                } catch (Exception e) {
                    if (client.isConnected()) {
                        try {
                            client.disconnect();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    System.err.println("Could not connect to server.");
                    e.printStackTrace();
                    return;
                } finally {
                    client.disconnect();
                    client.logout();
                    System.out.println("# client disconnected");
                }

            }

            //Helper method from apache: http://commons.apache.org/proper/commons-net/apidocs/index.html?org/apache/commons/net/util/KeyManagerUtils.html
            private static 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;
            }
        }

对于我可能出错的地方或任何有用的链接的任何建议将不胜感激!

0 个答案:

没有答案