我的应用在Google Play中遭到拒绝,原因是TrustManager的一些不安全的实现。
但在我的库中,我只有一个TrustManager实现(这是我的SSLUtil类)。
import android.content.Context;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class SSLUtil {
/**
* @param ctx
* @param certRaw File from /res/raw
* @return
* @throws Exception
*/
public static SSLSocketFactory trustCert(Context ctx, int certRaw) throws Exception {
// Load CAs from an InputStream
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// File at /res/raw
InputStream caInput = FileUtils.readRawFile(ctx, certRaw);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
} 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);
// Log.d(TAG, "KeyStore: " + keyStore);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
SSLSocketFactory socketFactory = context.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
return socketFactory;
}
}
我在阅读Android开发者网站的以下文档后写了这个课程:
https://developer.android.com/training/articles/security-ssl.html
如果我理解正确,这段代码就可以了。 TrustManager的这个实现是对的吗?
我不明白我的申请被拒绝的原因。
答案 0 :(得分:1)
不,您的代码不安全。从名称allHostsValid
可以看出,代码盲目地接受所有主机名,这意味着连接可以是中间人。你应该删除这个类。