【问题标题】:SelfSigned Cert for HTTPs download in Android Studio在 Android Studio 中下载用于 HTTPs 的 SelfSigned Cert
【发布时间】:2016-05-19 13:44:25
【问题描述】:

好的,我一直在努力从 HTTPS 网站下载图像以显示在我的 android 应用程序中。我一直在使用 android 开发网站来执行此操作。 http://developer.android.com/training/articles/security-ssl.html 但是,当我尝试使用 .setSSLSocketFactory() 方法时,IDE 说它无法解析此方法。我不知道我在这里做错了什么,我认为我拥有执行此操作所需的所有导入。 任何帮助将不胜感激。

这是我的代码:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;


public class CertificateHandler {
    private final String myCert = "MyCA.crt";

    public void getToken(HttpURLConnection urlConnection) {

        try {
            // Load CAs from an InputStream
            // (could be from a resource or ByteArrayInputStream or ...)
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            // From https://www.washington.edu/itconnect/security/ca/load-der.crt
            InputStream caInput = new BufferedInputStream(new FileInputStream("myCert"));
            Certificate ca;
            try {
                ca = cf.generateCertificate(caInput);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                caInput.close();
            }

            // Create a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf =         TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            // Create an SSLContext that uses our TrustManager
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
            urlConnection.setSSLSocketFactory(context.getSocketFactory());


        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

    }
}

【问题讨论】:

  • 不应该是HttpsUrlConnection吗?? developer.android.com/reference/javax/net/ssl/…
  • 是的,Raghunandan,我的问题是我正在下载一个 URL 列表,它们与 http 和 https 混合在一起。主 url 是一个 http,所以我必须将每个 url 分成两个不同的组,并用不同的方法下载它们。非常感谢mcuh
  • 您找到解决问题的方法了吗?我在 Android N 上遇到了类似的问题。
  • 并非如此。我不得不重新设计整个项目以使用正确的证书。我会把它贴在下面供你使用。

标签: java android ssl certificate self-signed


【解决方案1】:

这是我为我工作的答案:

我用来接收所有 https 获取请求的 HTTPS 获取类。

public class MyHttpsGet extends AsyncTask<String, Void, String> {

Context context;

int cert;
boolean allowHost;
private String username;
private String password;

//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert)
{
    this.context = context;
    this.cert = cert;
    this.allowHost = allowHost;
    this.username = username;
    this.password = password;

}

//used for image downloading
public MyHttpsGet(){}

@Override
protected String doInBackground(String... params) {
    String url = params[0];
    return httpsDownloadData(url, context, cert);
}

public String httpsDownloadData (String urlString, Context context, int certRawResId)
{
    String respone = null;

    try {
        // build key store with ca certificate
        KeyStore keyStore = buildKeyStore(context, certRawResId);

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        // Create a connection from url
        URL url = new URL(urlString);
        if (username != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            });
        }
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());


        int statusCode = urlConnection.getResponseCode();
        Log.d("Status code: ", Integer.toString(statusCode));


        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {
            respone = streamToString(inputStream);
            inputStream.close();
        }

    }catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    Log.d("MyHttps Respones: ", respone);
    return respone;
}


private static KeyStore buildKeyStore(Context context, int certRawResId){
    // init a default key store
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);

        // read and add certificate authority
        Certificate cert = readCert(context, certRawResId);
        keyStore.setCertificateEntry("ca", cert);


    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return keyStore;

}

private static Certificate readCert(Context context, int certResourceId) throws IOException {

    // read certificate resource
    InputStream caInput = context.getResources().openRawResource(certResourceId);

    Certificate ca = null;
    try {
        // generate a certificate
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e) {
        e.printStackTrace();
    } finally {
        caInput.close();
    }

    return ca;
}

//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {

    StringBuilder sb = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }

    return sb.toString();
}


 }

这就是你在任何活动的主要方法中使用它的方式:

MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2);
        try {
            myJson = task.execute(myUrl).get();
            Log.d("Promo Json: " , myJson);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        new runningMan().execute();

其中 R.raw.gdroot_g2 是存储在您的 android 项目的 raw 文件夹中的证书。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2021-04-27
    • 2017-02-04
    • 2016-09-27
    • 2017-10-05
    • 2017-02-04
    相关资源
    最近更新 更多