2017-10-20 231 views
2

我的網絡代碼是用NDK(cURL + OpenSSL)編寫的,我想使用來自Android的憑證存儲的證書作爲SSL連接的客戶端證書。此外,我想向用戶提供可用證書列表,以便他可以選擇連接證書。不幸的是,我無法從關鍵存儲獲得證書。如何從「憑證存儲」加載證書?

我在我的Android設備(5.0.2)上安裝了一個客戶端證書到「憑證存儲」(設置 - > Secutrity - > ...),但我無法從Java訪問它。我嘗試撥打以下代碼,但密鑰存儲是empy,儘管證書已安裝在憑證存儲中:

//KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 
KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); 
ks.load(null); 

Enumeration<String> aliases = ks.aliases(); 
while(aliases.hasMoreElements()) { 
    String alias = (String)aliases.nextElement(); 
    Log.i("app", "alias name: " + alias); 
    Certificate certificate = ks.getCertificate(alias); 
    Log.i("app", certificate.toString()); 
} 

我在做什麼錯?

回答

0

用戶憑據都可以通過Android的KeyChain,而不是Android的密鑰庫

鑰匙串類,可以訪問私鑰及其相應的證書鏈中憑證存儲。

使用choosePrivateKeyAlias提示用戶選擇證書。系統爲用戶啓動一個活動來選擇別名並通過回叫發送給您。然後使用getPrivateKeygetCertificate恢復密鑰和相應的證書鏈

KeyChain.choosePrivateKeyAlias(activity, new KeyChainAliasCallback() { 
      public void alias(String alias) {    
       //do something with the selected alias      
      }    
     }, 
     new String[] { KeyProperties.KEY_ALGORITHM_RSA, "DSA"}, // List of acceptable key types. null for any 
     null,      // issuer, null for any 
     null,      // host name of server requesting the cert, null if unavailable 
     -1,       // port of server requesting the cert, -1 if unavailable 
     "");       // alias to preselect, null if unavailable 

PrivateKey privateKey = KeyChain.getPrivateKey(activity, alias); 
X509Certificate chain[] = KeyChain.getCertificateChain(activity, alias); 
0

嘗試這樣:安裝在設備

X509TrustManager manager = null; 
FileInputStream fs = null; 

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 

try 
{ 
    fs = new FileInputStream(System.getProperty("javax.net.ssl.trustStore")); 
    keyStore.load(fs, null); 
} 
finally 
{ 
    if (fs != null) { fs.close(); } 
} 

trustManagerFactory.init(keyStore); 
TrustManager[] managers = trustManagerFactory.getTrustManagers(); 

for (TrustManager tm : managers) 
{ 
    if (tm instanceof X509TrustManager) 
    { 
     manager = (X509TrustManager) tm; 
     break; 
    } 
}