我的网络代码是用NDK(cURL + OpenSSL)编写的,我想使用Android的凭据存储证书作为SSL连接的客户端证书。此外,我想向用户提供可用证书列表,因此他可以选择连接证书。不幸的是,我无法从密钥存储中获取证书。
我安装了一个客户端证书到#34;凭证存储" (设置 - > Secutrity - > ...)在我的Android设备(5.0.2)上,但我无法从Java访问它。我试图调用以下代码,但密钥存储空间很大,证书安装在凭证存储中:
//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 :(得分:0)
设备上安装的用户凭据可通过Android KeyChain获得,而非Android KeyStore
KeyChain类提供对凭据存储中私钥及其相应证书链的访问。
使用choosePrivateKeyAlias
提示用户选择证书。系统启动一个Activity,供用户选择别名并通过回调发送给您。然后使用getPrivateKey
和getCertificate
来恢复密钥和相应的认证链
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);
答案 1 :(得分:-1)
尝试这样的事情:
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;
}
}