【发布时间】:2013-12-04 16:21:27
【问题描述】:
我正在尝试连接到服务器 o 获取我需要重用的 SSL 证书(用于应用程序中的安全 TCP 连接)。我需要将二进制形式的证书传递给这些类,如果用户第二天尝试重新连接到同一台服务器,我还需要将这个新证书与保存的证书进行比较。 出于这个原因,我有这个代码:
ttpsURLConnection = (HttpsURLConnection)url.openConnection();
inputStream = httpsURLConnection.getInputStream();
Certificate[] cert = httpsURLConnection.getServerCertificates();
//we are taking the last certificate which should be the server certificate
X509Certificate x509Certificate = (X509Certificate) cert[cert.length-1];
byte [] encodedCertificate = x509Certificate.getEncoded();
我想知道保存此证书的最佳和最安全的方法,以便不必每次都打开连接。
首先我想到在这篇文章的帮助下使用 Android KeyChain: http://nelenkov.blogspot.com.es/2011/11/using-ics-keychain-api.html。 问题是他需要用户交互,然后用户必须在他的设备上激活模式或图钉,否则这不起作用。另一个不便之处是证书将可供所有应用使用,我不希望这样。
我也尝试过使用 KeySore:
String keyStoreType = KeyStore.getDefaultType();
keyStore = KeyStore.getInstance(keyStoreType);
InputStream stream = null;
char[] password = null;
keyStore.load(stream, password);
if(keyStore.getCertificate(CERTIFICATE_ALIAS) == null){
Log.d(TAG, "KeyStore doesn't contain field "+CERTIFICATE_ALIAS);
keyStore.setCertificateEntry(CERTIFICATE_ALIAS, certificate);
} else {
Log.d(TAG, "KeyStore already contains field "+CERTIFICATE_ALIAS);
}
}
每次我回来时 keyStore.getCertificate(CERTIFICATE_ALIAS) == null 总是返回 true,所以不可能以这种方式“保存”证书。
我正在考虑使用私有模式将证书保存到 SharedPreferences,但我想知道它是否安全?如果没有,是否有更好的方法来保存仅由我的应用程序使用的证书(api 级别 14++) 谢谢
【问题讨论】:
标签: android ssl certificate