Android HttpsURLConnection可以在模拟器上使用自签名证书,但不能在真实设备上使用

问题描述 投票:0回答:1

我使用此命令为在EC2实例上运行的Nginx服务器创建自签名证书

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/selfsigned.key -out /etc/ssl/certs/selfsigned.crt

作为通用名称(例如服务器FQDN或您的名称),我使用了EC2实例的公共DNS,ec2-somenumber.region.compute.amazonaws.com

我使用此代码解决信任问题,我将selfsigned.crt复制到应用程序原始文件夹中,并以这种方式使用它:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.selfsigned);
Certificate ca = cf.generateCertificate(caInput);

// 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 _sslContext = SSLContext.getInstance("TLS");
_sslContext.init(null, tmf.getTrustManagers(), null);

URL url = new URL("https://ec2-somenumber.region.compute.amazonaws.com");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(_sslContext.getSocketFactory());

现在,它可以完美地在模拟器上运行,但是当我尝试在真实设备上调试它时,会出现此错误:

 javax.net.ssl.SSLPeerUnverifiedException: Hostname ec2-somenumber.region.compute.amazonaws.com not verified

我在stackoverlow上阅读了很多问题,实际上我不想覆盖hostnameVerifier,直到我了解为什么它可以在模拟器上运行而不在真实设备上运行。

您有什么建议吗?

谢谢

java android amazon-ec2 httpsurlconnection self-signed-certificate
1个回答
0
投票

如果您遇到相同的问题,请参考此link以生成证书。

要使自签名证书在真实设备上工作,我需要在用于创建证书的ssl.conf文件中指定这样的使用者备用名称

[alt_names]
DNS.1   = ec2-somenumber.region.compute.amazonaws.com
© www.soinside.com 2019 - 2024. All rights reserved.