我正在尝试连接到运行godaddy 256位SSL证书的IIS6盒子,我收到错误:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
一直试图确定导致这种情况的原因,但现在正在绘制空白。
以下是我的联系方式:
HttpsURLConnection conn;
conn = (HttpsURLConnection) (new URL(mURL)).openConnection();
conn.setConnectTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
String tempString = toString(conn.getInputStream());
答案 0 :(得分:186)
与接受的答案相反, 不 需要自定义信任管理器,您需要修复服务器配置!
在连接到安装了错误的dynadot / alphassl证书的Apache服务器时遇到了同样的问题。我正在使用HttpsUrlConnection(Java / Android)连接,它正在抛出 -
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertPathValidatorException:
Trust anchor for certification path not found.
实际问题是服务器配置错误 - 使用http://www.digicert.com/help/或类似方法对其进行测试,它甚至会告诉您解决方案:
“证书未由受信任的机构签名(检查Mozilla的根存储)。如果您从受信任的机构购买证书, 您可能只需要安装一个或多个中间证书 。请与您的证书提供商联系,以获取有关为您的服务器平台执行此操作的帮助。“
您还可以使用openssl检查证书:
openssl s_client -debug -connect www.thedomaintocheck.com:443
您可能会看到:
Verify return code: 21 (unable to verify the first certificate)
并且,在输出的早期:
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=27:certificate not trusted
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=21:unable to verify the first certificate`
证书链只包含1个元素(您的证书):
Certificate chain
0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
i:/O=AlphaSSL/CN=AlphaSSL CA - G2
...但是应该将链中的签名机构引回到受Android(Verisign,GlobalSign等)信任的链中:
Certificate chain
0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
i:/O=AlphaSSL/CN=AlphaSSL CA - G2
1 s:/O=AlphaSSL/CN=AlphaSSL CA - G2
i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
用于配置服务器的说明(和中间证书)通常由颁发证书的机构提供,例如:http://www.alphassl.com/support/install-root-certificate.html
安装证书颁发者提供的中间证书后,我现在使用HttpsUrlConnection连接时没有错误。
答案 1 :(得分:63)
@Chrispix的解决方案很危险! 信任所有证书允许任何人在中间攻击中做一个人!只需向客户发送任何证书,它就会接受它!
将您的证书添加到自定义信任管理器,如本文所述:Trusting all certificates using HttpClient over HTTPS
虽然使用自定义证书建立安全连接有点复杂,但它会为您带来所需的ssl加密安全性,而不会受到中间人攻击的危险!
答案 2 :(得分:16)
您可以在运行时信任特定证书 只需从服务器下载,放入资源并使用ssl-utils-android
加载OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());
在上面的示例中,我使用了OkHttpClient
,但SSLContext
可以与Java中的任何客户端一起使用。
如果您有任何问题,请随时提出。我是这个小型图书馆的作者。
答案 3 :(得分:11)
根据最新的Android文档进行更新(2017年3月):
当您收到此类错误时:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
问题可能是以下之一:
解决方案是教HttpsURLConnection
信任一组特定的CA.怎么样?请检查https://developer.android.com/training/articles/security-ssl.html#CommonProblems
其他使用AsyncHTTPClient
图书馆com.loopj.android:android-async-http
的人,请查看Setup AsyncHttpClient to use HTTPS。
答案 4 :(得分:7)
回复很老的帖子。但也许它会帮助一些新手,如果没有上述工作。
说明:我知道没有人想解释废话;而是解决方案。但在一个班轮中,您尝试从本地计算机访问服务到不信任您的计算机的远程计算机。您请求需要从远程服务器获得信任。
解决方案:以下解决方案假定您符合以下条件
<强>步骤:强>
您需要.keystore扩展名文件才能注册您的应用。如果你不知道如何创建.keystore文件;然后按照以下部分创建.keystore文件或以其他方式跳到下一部分签署Apk文件
创建.keystore文件
打开Android Studio。点击顶部菜单Build&gt;生成签名APK。在下一个窗口中,单击创建新... 按钮。在新窗口中,请输入所有字段的数据。请记住,我推荐的两个密码字段应该具有相同的密码;不要使用不同的密码;并且还记住最顶部字段密钥库路径的保存路径。输入所有字段后,单击“确定”按钮。
签署Apk文件
现在您需要使用刚刚创建的.keystore文件构建已签名的应用程序。请按照以下步骤操作
Choose existing...
按钮Key store password
和Key password
字段使用相同的密码。同时输入别名build.gradle
和Build Types
。Flavors
从下拉列表中选择Build Types
对于release
,但这取决于Flavors
文件中的设置。从此字段中选择build.gradle
。我在staging
中使用了以下设置,您可以使用与我相同的设置,但请确保将build.gradle
更改为您的包名称
applicationId
点击底部的两个productFlavors {
staging {
applicationId "com.yourapplication.package"
manifestPlaceholders = [icon: "@drawable/ic_launcher"]
buildConfigField "boolean", "CATALYST_DEBUG", "true"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "true"
}
production {
buildConfigField "boolean", "CATALYST_DEBUG", "false"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "false"
}
}
复选框,然后点击Signature Versions
按钮。
几乎在那里:
所有的辛勤工作都已完成,现在是真理的运动。要访问由代理备份的Staging服务器,您需要在真正的Android设备测试中进行一些设置。
Android设备中的代理设置:
Finish
Modify network
字段Advanced options
Proxy Hostname
中输入您要连接的主机IP或名称。典型的临时服务器将命名为Proxy Hostname
stg.api.mygoodcompany.com
9502
按钮最后一站:
请记住,我们在签名APK文件部分生成了已签名的apk文件。现在是安装该APK文件的时候了。
Save
adb install
name of the apk file
。输入完整路径adb command not found
C:\Users\shah\AppData\Local\Android\sdk\platform-tools\adb.exe
install
我希望问题可以解决。如果没有,请给我留言。
萨拉姆!
答案 5 :(得分:5)
使用https://www.ssllabs.com/ssltest/测试域。
Shihab Uddin在Kotlin中的解决方案。
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException
object {
val okHttpClient: OkHttpClient
val gson: Gson
val retrofit: Retrofit
init {
okHttpClient = getOkHttpBuilder()
// Other parameters like connectTimeout(15, TimeUnit.SECONDS)
.build()
gson = GsonBuilder().setLenient().create()
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
fun getOkHttpBuilder(): OkHttpClient.Builder =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
OkHttpClient().newBuilder()
} else {
// Workaround for the error "Caused by: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at".
getUnsafeOkHttpClient()
}
private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(
object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<X509Certificate?>?,
authType: String?) = Unit
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<X509Certificate?>?,
authType: String?) = Unit
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
)
// Install the all-trusting trust manager
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory,
trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
如果您使用Glide
,也会出现相同的错误,图像将不会显示。要克服它,请参见Glide - javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found和How to set OkHttpClient for glide。
@GlideModule
class MyAppGlideModule : AppGlideModule() {
val okHttpClient = Api.getOkHttpBuilder().build() // Api is the class written above.
// It is better to create okHttpClient here and not use Api.okHttpClient,
// because their settings may differ. For instance, it can use its own
// `addInterceptor` and `addNetworkInterceptor` that can affect on a read JSON.
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.replace(GlideUrl::class.java, InputStream::class.java,
OkHttpUrlLoader.Factory(okHttpClient))
}
}
build.gradle:
// Glide.
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'
答案 6 :(得分:4)
我收到的错误消息类似,但原因是自签名证书已过期。 尝试使用openssl客户端时,它给了我从firefox检查证书对话框时忽略的原因。
因此,一般情况下,如果证书存在于密钥库中并且其“VALID”,则此错误将会消失。
答案 7 :(得分:3)
从Android客户端连接到Kurento服务器时遇到了同样的问题。 Kurento服务器使用jks证书,所以我不得不将pem转换为它。 作为转换的输入,我使用了cert.pem文件,导致了这样的错误。 但如果使用 fullchain.pem 而不是 cert.pem - 一切正常。
答案 8 :(得分:2)
我遇到了同样的问题,我发现证书.crt文件我提供了缺少中间证书。所以我从服务器管理员那里询问了所有.crt文件,然后以相反的顺序将它们连接起来。
实施例。 1. Root.crt 2. Inter.crt 3. myCrt.crt
在Windows中我执行了复制Inter.crt + Root.crt newCertificate.crt
(这里我忽略了myCrt.crt)
然后我通过inputstream将newCertificate.crt文件提供给代码。 完成工作。
答案 9 :(得分:2)
我知道您不需要信任所有证书,但是就我而言,我遇到了一些调试环境的问题,在这些调试环境中,我们拥有自签名证书,因此我需要一个肮脏的解决方案。
我要做的就是更改sslContext
mySSLContext.init(null, trustAllCerts, null);
trustAllCerts
的创建方式如下:
private final TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
希望这会派上用场。
答案 10 :(得分:2)
如果使用改造,则需要自定义OkHttpClient。
retrofit = new Retrofit.Builder() .baseUrl(ApplicationData.FINAL_URL) .client(getUnsafeOkHttpClient().build()) .addConverterFactory(GsonConverterFactory.create()) .build();
完整代码如下。
public class RestAdapter {
private static Retrofit retrofit = null;
private static ApiInterface apiInterface;
public static OkHttpClient.Builder getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static ApiInterface getApiClient() {
if (apiInterface == null) {
try {
retrofit = new Retrofit.Builder()
.baseUrl(ApplicationData.FINAL_URL)
.client(getUnsafeOkHttpClient().build())
.addConverterFactory(GsonConverterFactory.create())
.build();
} catch (Exception e) {
e.printStackTrace();
}
apiInterface = retrofit.create(ApiInterface.class);
}
return apiInterface;
}
}
答案 11 :(得分:1)
Trust定位错误可能由于很多原因而发生。对我来说,只是我试图访问https://example.com/
而不是https://www.example.com/
。
因此,您可能想在开始构建自己的信任管理器之前像我一样仔细检查URL。
答案 12 :(得分:0)
我使用这些方法,其中之一在上述解决方案中对我有用: 首先:
public okhttp3.OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate
certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void
checkClientTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void
checkServerTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[]
getAcceptedIssuers() {
return new
java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext =
SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new
java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting
manager
final SSLSocketFactory sslSocketFactory =
sslContext.getSocketFactory();
okhttp3.OkHttpClient.Builder builder = new
okhttp3.OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory,
(X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession
session) {
return true;
}
});
okhttp3.OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
第二:
@SuppressLint("TrulyRandom")
public static void handleSSLHandshake() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new
X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[]
certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[]
certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new
HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (Exception ignored) {
}
}
和: 把这个库放到你的类路径中:
implementation 'com.squareup.okhttp:okhttp:2.3.0'
implementation 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-
core:3.3.0'
确保你在课堂上给他们打电话
答案 13 :(得分:0)
我通过改变解决了我的问题
https://example.com/
到
http://example.com/
因为服务器没有 SSL 证书。
因此,请检查您的服务器的 url 并相应地更改
答案 14 :(得分:0)
有时会在管理员错误地设置证书时发生 在这里检查网址 https://www.sslshopper.com/ssl-checker.html
就我而言,有一个错误
并非所有网络浏览器都信任该证书。您可能需要安装中间/链证书以将其链接到受信任的根证书。了解有关此错误的更多信息。您可以按照适用于您的服务器平台的 GlobalSign 的证书安装说明来解决此问题。关注中级证书部分。
答案 15 :(得分:0)
我知道这是一篇非常古老的文章,但是在尝试解决信任锚问题时遇到了这篇文章。我已经发布了解决方法。如果您已经预安装了根CA,则需要在清单中添加配置。
答案 16 :(得分:0)
我遇到了类似的问题,并且完全排除了信任所有来源的策略。
我在这里分享我的解决方案应用于Kotlin中实现的应用程序
我首先建议使用the following website获取有关证书及其有效性的信息
如果该证书未在 Android默认信任存储区中显示为“接受的颁发者” ,我们必须获取该证书并将其合并到应用程序中以创建自定义信任库
在我看来,理想的解决方案是创建一个结合了自定义和Android默认信任存储的高级信任管理器。
在这里,他展示了用于配置与Retrofit一起使用的OkHttpClient的高级代码。
override fun onBuildHttpClient(httpClientBuild: OkHttpClient.Builder) {
val trustManagerWrapper = createX509TrustManagerWrapper(
arrayOf(
getCustomX509TrustManager(),
getDefaultX509TrustManager()
)
)
printX509TrustManagerAcceptedIssuers(trustManagerWrapper)
val sslSocketFactory = createSocketFactory(trustManagerWrapper)
httpClientBuild.sslSocketFactory(sslSocketFactory, trustManagerWrapper)
}
通过这种方式,我可以使用具有自签名证书的服务器与其他服务器进行通信,并使用受信任的认证实体颁发的证书与其他服务器进行通信
就是这样,我希望它可以帮助某人。
答案 17 :(得分:0)
在我的情况下,这是在更新到Android 8.0之后发生的。 Android设置为信任的自签名证书使用签名算法SHA1withRSA。使用签名算法SHA256withRSA切换到新证书可以解决问题。
答案 18 :(得分:0)
在Gingerbread手机中,我总是收到此错误:Trust Anchor not found for Android SSL Connection
,即使我设置依赖我的证书。
这是我使用的代码(在Scala语言中):
object Security {
private def createCtxSsl(ctx: Context) = {
val cer = {
val is = ctx.getAssets.open("mycertificate.crt")
try
CertificateFactory.getInstance("X.509").generateCertificate(is)
finally
is.close()
}
val key = KeyStore.getInstance(KeyStore.getDefaultType)
key.load(null, null)
key.setCertificateEntry("ca", cer)
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
tmf.init(key)
val c = SSLContext.getInstance("TLS")
c.init(null, tmf.getTrustManagers, null)
c
}
def prepare(url: HttpURLConnection)(implicit ctx: Context) {
url match {
case https: HttpsURLConnection ⇒
val cSsl = ctxSsl match {
case None ⇒
val res = createCtxSsl(ctx)
ctxSsl = Some(res)
res
case Some(c) ⇒ c
}
https.setSSLSocketFactory(cSsl.getSocketFactory)
case _ ⇒
}
}
def noSecurity(url: HttpURLConnection) {
url match {
case https: HttpsURLConnection ⇒
https.setHostnameVerifier(new HostnameVerifier {
override def verify(hostname: String, session: SSLSession) = true
})
case _ ⇒
}
}
}
这是连接代码:
def connect(securize: HttpURLConnection ⇒ Unit) {
val conn = url.openConnection().asInstanceOf[HttpURLConnection]
securize(conn)
conn.connect();
....
}
try {
connect(Security.prepare)
} catch {
case ex: SSLHandshakeException /*if ex.getMessage != null && ex.getMessage.contains("Trust anchor for certification path not found")*/ ⇒
connect(Security.noSecurity)
}
基本上,我设置为信任我的自定义证书。如果失败,则禁用安全性。这不是最好的选择,但是我知道老式和越野车的唯一选择。
此示例代码可以轻松转换为Java。
答案 19 :(得分:-1)
**Set proper alias name**
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);