我正在尝试在 Linux 服务器和 Android APP 之间设置相互验证的 SSL。到目前为止,我已经能够让应用程序使用服务器证书通过 SSL 进行通信,但是一旦我将服务器设置为只接受客户端证书,它就会停止工作。服务器配置似乎还可以,但我有点卡住了。我最好的猜测是客户端证书没有正确呈现给服务器,但不知道接下来如何测试它。我尝试在我的 OS X 钥匙串中为客户端使用 .pem,但浏览器似乎不适用于该证书。然后服务器证书再次完美运行,因为我可以实现 https 连接并且 APP 接受我未签名的服务器证书。
我一直在使用的代码是各种教程的组合,答案是我收藏的主要内容:
- http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
- Android 上的自签名 SSL 接受
- 使用移动应用程序保护通信 [真实性、隐私性和完整性]?
- (对于服务器配置)https://security.stackexchange.com/questions/34897/configure-ssl-mutual-two-way-authentication
这是我用于连接的两个主要类:1)这个类处理 JSON 解析并执行请求
package edu.hci.additional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import android.content.Context;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params, Context context) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
SecureHttpClient httpClient = new SecureHttpClient(context);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
SecureHttpClient httpClient = new SecureHttpClient(context);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
第二个类处理 SSL 身份验证:
package edu.hci.additional;
import android.content.Context;
import android.util.Log;
import edu.hci.R;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
public class SecureHttpClient extends DefaultHttpClient {
private static Context appContext = null;
private static HttpParams params = null;
private static SchemeRegistry schmReg = null;
private static Scheme httpsScheme = null;
private static Scheme httpScheme = null;
private static String TAG = "MyHttpClient";
public SecureHttpClient(Context myContext) {
appContext = myContext;
if (httpScheme == null || httpsScheme == null) {
httpScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
httpsScheme = new Scheme("https", mySSLSocketFactory(), 443);
}
getConnectionManager().getSchemeRegistry().register(httpScheme);
getConnectionManager().getSchemeRegistry().register(httpsScheme);
}
private SSLSocketFactory mySSLSocketFactory() {
SSLSocketFactory ret = null;
try {
final KeyStore clientCert = KeyStore.getInstance("BKS");
final KeyStore serverCert = KeyStore.getInstance("BKS");
final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);
final InputStream server_inputStream = appContext.getResources().openRawResource(R.raw.certs);
clientCert.load(client_inputStream, appContext.getString(R.string.client_store_pass).toCharArray());
serverCert.load(server_inputStream, appContext.getString(R.string.server_store_pass).toCharArray());
String client_password = appContext.getString(R.string.client_store_pass);
server_inputStream.close();
client_inputStream.close();
ret = new SSLSocketFactory(clientCert,client_password,serverCert);
} catch (UnrecoverableKeyException ex) {
Log.d(TAG, ex.getMessage());
} catch (KeyStoreException ex) {
Log.d(TAG, ex.getMessage());
} catch (KeyManagementException ex) {
Log.d(TAG, ex.getMessage());
} catch (NoSuchAlgorithmException ex) {
Log.d(TAG, ex.getMessage());
} catch (IOException ex) {
Log.d(TAG, ex.getMessage());
} catch (Exception ex) {
Log.d(TAG, ex.getMessage());
} finally {
return ret;
}
}
}
要使用以下命令创建我使用 openssl 的密钥:
openssl req -nodes -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 500
为了获得适用于 Android 的 BKS 的密钥,我使用了位于以下位置的充气城堡 bcprov-jdk15on-150.jar:http: //www.bouncycastle.org/latest_releases.html
并使用了命令:
keytool -import -v -trustcacerts -alias 0 -file ~/cert.pem -keystore ~/Downloads/authclientcerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath ~/Downloads/bcprov-jdk15on-150.jar -storepass passWORD
最后,我添加到 /etc/httpd/conf.d/ssl.conf 以要求客户端证书并检查 Fedora 19 中的证书有效性(与我创建的客户端证书匹配)的行是:
...
SSLVerifyClient require
SSLVerifyDepth 5
...
<Location />
SSLRequire ( %{SSL_CLIENT_S_DN_O} eq "Develop" \
and %{SSL_CLIENT_S_DN_OU} in {"Staff", "Operations", "Dev"} )
</Location>
...
SSLOptions +FakeBasicAuth +StrictRequire
我在这个配置文件上尝试了很多组合,并且都以相同的结果结束,给我一个“SSLPeerUnverifiedException:没有对等证书”异常。我在服务器的 SSL 配置文件上评论了这一行,一切正常,但服务器接受所有不是我需要的客户端。
提前致谢 :)
更新
@EJP的回答成功了
首先,我必须将证书添加到正确的 ( /etc/pki/tls/certs/ ) 路径并使用以下命令加载它: 重命名证书: mv ca-andr.pem ca-andr.crt 现在加载证书:
ln -s ca-andr.crt $( openssl x509 -hash -noout -in ca-andr.crt )".0"
这将创建一个 openSSL 可读符号链接,其名称类似于“f3f24175.0”</p>
然后我在 /etc/httpd/conf.d/ssl.conf 配置文件中设置新的证书文件。
…
SSLCACertificateFile /etc/pki/tls/certs/f2f62175.0
…
现在重新启动 http 服务并测试证书是否加载:
openssl verify -CApath /etc/pki/tls/certs/ f2f62175.0
如果一切正常,您应该看到:
f3f24175.0:好的
您可以通过以下方式结束测试:
openssl s_client -connect example.com:443 -CApath /etc/pki/tls/certs
这应该返回受信任的客户端证书列表(如果您看到您添加的证书正在运行)
现在问题的第二部分是我的 authclientcerts.BKS 不包含私钥,因此我提供的密码从未使用过,服务器不会对证书进行身份验证。所以我将我的密钥和证书导出到 pkcs12 并相应地更新了 JAVA 代码。
导出命令:
openssl pkcs12 -export -in ~/cert.pem -inkey ~/key.pem > android_client_p12.p12
然后我更改了 SecureHttpClient.java 类的部分以使用 PKCS12 而不是 BKS 制作客户端证书。
要将密钥存储类型从 BKS 更改为 PKCS12,我替换了:
final KeyStore clientCert = KeyStore.getInstance("BKS”);
为了这:
final KeyStore clientCert = KeyStore.getInstance("PKCS12");
然后我通过替换更新了对位于 res/raw/ 上的实际密钥存储文件的引用:
final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);
为了这:
final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.android_client_p12);
这就是诀窍:D