生成android自签名证书流程
Step-to-Step Guide to Programming Android SSL with Self-Signed Server Certificate
There is a dearth of SDK documentation on how to work with SSL connections on Android with self-signed certificate. Here is a method that stores a self-signed certificate in the application resource and then later uses that certificate for SSL connections.
1. We create a self-signed server certificate for our SSL server:
keytool-genkey-dname"cn=ssltest,ou=test,o=example,c=US"-aliasssltest-keypassssltest-keystorec:\test\ssltest.keystore-storepassssltest-validity180
2. We export the certificate to a file:
keytool-export-aliasssltest-keystorec:\test\ssltest.keystore-filec:\test\ssltest.cer-storepassssltest-keypassssltest
3. Since Android uses theJCEprovider fromBouncy Castle, wedownloadthe provider jarbcprov-jdk16-145.jarfrom BC and store it atC:\androidproject\libs.
4. Now, we import the server certificate to our Android project as araw resource:
keytool-import-aliasssltestcert-fileC:\test\ssltest.cer-keypassssltestcert-keystoreC:\androidproject\res\raw\ssltestcert-storetypeBKS-storepassssltestcert-providerClassorg.bouncycastle.jce.provider.BouncyCastleProvider-providerpathc:\androidproject\libs\bcprov-jdk16-145.jar
Note that we give it a store typeBKS.
If you use the Eclipse ADK, the ADK will automatically create a resource idssltestcertafter you refresh the project.
5. We can now use the server certificate in our Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Load the self-signed server certificate char [] passphrase = "ssltestcert" .toCharArray(); KeyStore ksTrust = KeyStore.getInstance( "BKS" ); ksTrust.load(context.getResources().openRawResource(R.raw.ssltestcert), passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(ksTrust); // Create a SSLContext with the certificate SSLContext sslContext = SSLContext.getInstance( "TLS" ); sslContext.init( null , tmf.getTrustManagers(), new SecureRandom()); // Create a HTTPS connection URL url = new URL( "https" , "10.0.2.2" , 8443 , "/ssltest" ); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); /* Uncomment the following line of code if you want to skip SSL */ /* hostname verification. But it should only be done for testing. */ /* See http://randomizedsort.blogspot.com/2010/09/programmatically-disabling-java-ssl.html */ /* conn.setHostnameVerifier(new NullVerifier()); */ conn.setSSLSocketFactory(sslContext.getSocketFactory()); |
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer