2021-10-26

【Android】Nougat(Android7, API24) 在 APP 加入自己信任的憑證

參考資料 ----

7.1.1版以前的Android 裝置2021年9月起將不支援Let's Encrypt憑證

為什麼網站使用Let’s Encrypt SSL憑證卻無法正常訪問?

der pem cer crt key pfx等概念及区别

Let's Encrypt Certificates

网络安全配置



如果在 APP 內有(包括但不限於) 使用到 webview 元件 或 urlconnectionvolley,並且要 訪問/瀏覽/request 的網站是使用 Let's Encrypt 的憑證,則在 Android7.1.1(Nougat, API24~25)(含) 以前的裝置會出現下述的訊息,而無法 訪問/瀏覽/request 網站。

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

這個現象,即使在 AndroidStudio模擬器也會發生,所以如果您的 APP 的 minSdkVersion 是在 24(含) 以下,建議您建個 API24 的模擬器檢查一下您的 APP,看是否運作正常。


對應的方法,就是在 APP 加入自己信任的憑證。


打開 Chrome 造訪您自己的網站, 點 網址旁的 鎖



→ 已建立安全連線



→ 憑證有效



→ 可以看到 "簽發者" 是 "R3"




Let's Encrypt 的 簽發證書列表 https://letsencrypt.org/certificates/

找到

Let’s Encrypt R3 (RSA 2048, O = Let's Encrypt, CN = R3)

Signed by ISRG Root X1: der, pem, txt

下載 lets-encrypt-r3.der 到 /專案/res/raw/ 下, 修改檔名, 去除連字號變成 letsencryptr3.der


建立 /專案/res/xml/security.xml

 
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">(不含www.)您的域名</domain>
        <trust-anchors>
            <certificates src="@raw/letsencryptr3"/> der 證書檔名
        </trust-anchors>
    </domain-config>
</network-security-config>
 



修改 AndroidManifast.xml

 
<application
    ...
    ...
    android:networkSecurityConfig="@xml/security"    因為這個屬性是對 API24 以上, 我的 app minSdkVersion=23
    tools:targetApi="n"                     所以 AndroidStudio 會再補上這個屬性
    ...
    ... >
 


就 ok 了

不過對 API23(含) 以下的 Android 裝置無效,再找時間研究了。





2021.11.21
意外的發現,因為暫時解決不了 API23 的問題,所以老人家就想說...先將 minSdkVersion=24 擋一下,等問題解決了再改回原 minSdkVersion
結果上架更新後,老人家的 華為 T3(API23) 平板仍然可以在 Google Play Store 搜的到 APP,只不過在 APP 介紹頁面會顯示 "這個應用程式可能無法針對你的裝置進行最佳化調整" 的警示,但還是可以更新,而且更新後,竟然就恢復正常了!! 送出 request 可以正常得到回應,也可以正常下載檔案了!!

沒有留言:

張貼留言