gpt4 book ai didi

java - 在 Android Studio 中下载用于 HTTPs 的自签名证书

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:03 27 4
gpt4 key购买 nike

好的,所以我一直致力于从 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();
}

}
}

最佳答案

这是我为我工作得到的答案:

我用于接收所有 https get 请求的 HTTPS get 类。

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();
}


}

这就是您在任何 Activity 的主要方法中使用它的方式:

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 文件夹中的证书。

关于java - 在 Android Studio 中下载用于 HTTPs 的自签名证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35294325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com