And*_*Dev 6 java android cryptography ssl-certificate
可能这是重复的问题,但我没有完全清楚上一个问题,这就是我发布一个新问题的原因.请看看这个.我将Ca证书放在我的资源文件夹中以验证ca认证证书,并且服务器中也会有相同的ca证书.
我可以使用以下代码使用我的ca证书创建信任管理器:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("Issuer certificate");
if (inputStream != null)
} catch (IOException e) {
e.printStackTrace();
}
InputStream caInput = new BufferedInputStream(inputStream);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca="
+ ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(tmfAlgorithm);
tmf.init(keyStore);
Run Code Online (Sandbox Code Playgroud)
获得这个信任经理后,我应该如何比较我从服务器获得的crt证书...我怀疑:我是否需要创建另一个信任管理器并在获得这两个信任管理器比较任何提供商名称之后?如果我错了,请提供有关此过程的任何信息.
最终能够通过以下过程验证证书。我希望这对其他人有帮助......
public void validateCertificate() throws Exception {
try {
String issuerCertPath = "Issuer Certifate";
String certPath = "Issued Certificate";
X509Certificate issuerCert = getCertFromFile(issuerCertPath);
X509Certificate c1 = getCertFromFile(certPath);
TrustAnchor anchor = new TrustAnchor(issuerCert, null);
Set anchors = Collections.singleton(anchor);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List list = Arrays.asList(new Certificate[] { c1 });
CertPath path = cf.generateCertPath(list);
PKIXParameters params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator
.validate(path, params);
// If
// not
// valid
// will
// throw
System.out.println("VALID");
} catch (Exception e) {
System.out.println("EXCEPTION " + e.getMessage());
e.printStackTrace();
}
}
private X509Certificate getCertFromFile(String path) throws Exception {
AssetManager assetManager = MyActivity.this.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(path);
} catch (IOException e) {
e.printStackTrace();
}
InputStream caInput = new BufferedInputStream(inputStream);
X509Certificate cert = null;
CertificateFactory cf = CertificateFactory.getInstance("X509");
cert = (X509Certificate) cf.generateCertificate(caInput);
cert.getSerialNumber();
return cert;
}
Run Code Online (Sandbox Code Playgroud)