Two-way SSL ticket verification on the Android platform

Source: Internet
Author: User
Tags pkcs12 pfx file

Two-way SSL ticket verification on the Android platform

Environment: SERVER: apache server, openssl.

Clients: PC, java, and android platforms.

Ideas:

1. Perform one-way ssl verification and then two-way ssl verification.

2. PC first, java platform, and android. You don't have to do this. You have to make a choice. I personally want to figure out the entire process and take more steps.

Procedure:

1. An http server is built with apache on the pc, and a self-Signed CA certificate ca. crt is built with openssl. The server certificate server. crt is issued and the client certificate client. crt is issued. (There are many materials for configuring ssl communication in apache + openssl)

2. Install ca. crt, configure the server, enable one-way authentication, and test and verify one-way ssl communication using a browser.

3. Package client. crt and client. key to generate the client. pfx file in pkcs12 format.

4. Configure the server, enable two-way authentication, import the client. pfx file through a browser, and test and verify two-way ssl communication.


Important:

The Java platform recognizes certificate files in jks format by default, but the android platform only recognizes certificate files in bks format. You need to configure the BC library in java. For details, refer to: keystore.

For code reference, refer. (Some items need to be fine-tuned. I hope you can change them by yourself. For some people, there may be some pitfalls. If you have any questions, please leave a message and I will try my best to answer them)

  1. Public class MySSLSocket extends Activity {
  2. Private static final int SERVER_PORT = 50030; // port number
  3. Private static final String SERVER_IP = "218.206.176.146"; // connection IP
  4. Private static final String CLIENT_KET_PASSWORD = "123456"; // private Key Password
  5. Private static final String CLIENT_TRUST_PASSWORD = "123456"; // trust the certificate Password
  6. Private static final String CLIENT_AGREEMENT = "TLS"; // protocol of use
  7. Private static final String CLIENT_KEY_MANAGER = "X509"; // key manager
  8. Private static final String CLIENT_TRUST_MANAGER = "X509 ";//
  9. Private static final String CLIENT_KEY_KEYSTORE = "BKS"; // password library. BouncyCastle password library is used here.
  10. Private static final String CLIENT_TRUST_KEYSTORE = "BKS ";//
  11. Private static final String ENCONDING = "UTF-8"; // Character Set
  12. Private SSLSocket Client_sslSocket;
  13. Private Log tag;
  14. Private TextView TV;
  15. Private Button btn;
  16. Private Button btn2;
  17. Private Button btn3;
  18. Private EditText et;
  19. /** Called when the activity is first created .*/
  20. @ Override
  21. Public void onCreate (Bundle savedInstanceState ){
  22. Super. onCreate (savedInstanceState );
  23. SetContentView (R. layout. main );
  24. TV = (TextView) findViewById (R. id. TextView01 );
  25. Et = (EditText) findViewById (R. id. EditText01 );
  26. Btn = (Button) findViewById (R. id. Button01 );
  27. Btn2 = (Button) findViewById (R. id. Button02 );
  28. Btn3 = (Button) findViewById (R. id. Button03 );
  29. Btn. setOnClickListener (new Button. OnClickListener (){
  30. @ Override
  31. Public void onClick (View arg0 ){
  32. If (null! = Client_sslSocket ){
  33. GetOut (Client_sslSocket, et. getText (). toString ());
  34. GetIn (Client_sslSocket );
  35. Et. setText ("");
  36. }
  37. }
  38. });
  39. Btn2.setOnClickListener (new Button. OnClickListener (){
  40. @ Override
  41. Public void onClick (View arg0 ){
  42. Try {
  43. Client_sslSocket.close ();
  44. Client_sslSocket = null;
  45. } Catch (IOException e ){
  46. E. printStackTrace ();
  47. }
  48. }
  49. });
  50. Btn3.setOnClickListener (new View. OnClickListener (){
  51. @ Override
  52. Public void onClick (View arg0 ){
  53. Init ();
  54. GetIn (Client_sslSocket );
  55. }
  56. });
  57. }
  58. Public void init (){
  59. Try {
  60. // Obtain an SSL SSLContext instance
  61. SSLContext sslContext = SSLContext. getInstance (CLIENT_AGREEMENT );
  62. // Obtain the X509 key manager instance of KeyManagerFactory and TrustManagerFactory
  63. KeyManagerFactory keyManager = KeyManagerFactory. getInstance (CLIENT_KEY_MANAGER );
  64. TrustManagerFactory trustManager = TrustManagerFactory. getInstance (CLIENT_TRUST_MANAGER );
  65. // Obtain the BKS password library instance
  66. KeyStore kks = KeyStore. getInstance (CLIENT_KEY_KEYSTORE );
  67. KeyStore tks = KeyStore. getInstance (CLIENT_TRUST_KEYSTORE );
  68. // Add the client to load the certificate and private key, and read the key and trust certificate by reading the resource file
  69. Kks. load (getBaseContext ()
  70. . GetResources ()
  71. . OpenRawResource (R. drawable. kclient), CLIENT_KET_PASSWORD.toCharArray ());
  72. Tks. load (getBaseContext ()
  73. . GetResources ()
  74. . OpenRawResource (R. drawable. lt_client), CLIENT_TRUST_PASSWORD.toCharArray ());
  75. // Initialize the key manager
  76. KeyManager. init (kks, CLIENT_KET_PASSWORD.toCharArray ());
  77. TrustManager. init (tks );
  78. // Initialize SSLContext
  79. SslContext. init (keyManager. getKeyManagers (), trustManager. getTrustManagers (), null );
  80. // Generate SSLSocket
  81. Client_sslSocket = (SSLSocket) sslContext. getSocketFactory (). createSocket (SERVER_IP, SERVER_PORT );
  82. } Catch (Exception e ){
  83. Tag. e ("MySSLSocket", e. getMessage ());
  84. }
  85. }
  86. Public void getOut (SSLSocket socket, String message ){
  87. PrintWriter out;
  88. Try {
  89. Out = new PrintWriter (
  90. New BufferedWriter (
  91. New OutputStreamWriter (
  92. Socket. getOutputStream ()
  93. )
  94. ), True );
  95. Out. println (message );
  96. } Catch (IOException e ){
  97. E. printStackTrace ();
  98. }
  99. }
  100. Public void getIn (SSLSocket socket ){
  101. BufferedReader in = null;
  102. String str = null;
  103. Try {
  104. In = new BufferedReader (
  105. New InputStreamReader (
  106. Socket. getInputStream ()));
  107. Str = new String (in. readLine (). getBytes (), ENCONDING );
  108. } Catch (UnsupportedEncodingException e ){
  109. E. printStackTrace ();
  110. } Catch (IOException e ){
  111. E. printStackTrace ();
  112. }
  113. New AlertDialog
  114. . Builder (MySSLSocket. this)
  115. . SetTitle ("Server Message ")
  116. . SetNegativeButton ("OK", null)
  117. . SetIcon (android. R. drawable. ic_menu_agenda)
  118. . SetMessage (str)
  119. . Show ();
  120. }
  121. }


    Unidirectional:

    1. Use keytool to import ca. crt to the certificate library ca. bks in bks format to verify the server certificate. The command is as follows:

    Keytool-import-alias ca-file ca. crt-keystore ca. bks-storetype BKS-provider org. bouncycastle. jce. provider. BouncyCastleProvider

    2. The server is configured with one-way authentication, and ca. bks is placed in the assets or raw of the android project. The corresponding read is in the code

    1. Kks. load (getBaseContext ()
    2. . GetResources ()
    3. . OpenRawResource (R. drawable. kclient), CLIENT_KET_PASSWORD.toCharArray ());

      Not necessarily R. drawable. kclient. You can modify and read the file based on your actual situation.

      At this point, one-way ssl communication should be OK.

      (PS: for operations in 2, you do not have to do this. You can also set the ca. bks is imported to cacerts on the android platform. bks file, and then read authentication from this file, how to import, a lot of online information, such as: http://blog.csdn.net/haijun286972766/article/details/6247675


      For problems encountered during debugging, refer:

      Generally, it can pass through the simulator, and it will be okay on the real platform.

      Note the validity period of the Certificate. You must perform the operation within the validity period of the certificate.

      Bidirectional:

      Two-way implementation on the basis of one-way, but Mr Cheng can recognize other client certificates on the android platform. This is also a headache. There are very few materials on the Internet to generate client certificates in bks format, which are rarely used for reference.

      At this point, it is too frustrating. It is estimated that many of the guys are also getting stuck here. At the beginning, there was no clue that client certificates can be generated on PCs and JAVA platforms, however, it is dumb to switch to the android platform. You cannot use keytool to export the crt certificate generated by other tools to the bks format. You cannot use keytool to generate a new bks certificate;

      I tried all the methods I could think about. I was wondering if I was wrong about any details. In theory, I was sure I could do something. Why couldn't I see any implementation? I 've been looking for information for several days, but I haven't made any progress.

      Later, I will refer to the foreign documents about using openssl to generate pkcs12. pfx format certificate, and then use the tool portecle to convert to the BKS format. It is used on the android platform. At the beginning, it is a mandatory conversion. If an error occurs, the conversion fails, however, it is no problem to convert the format to jks. You can only find a solution based on the error prompt. After trying a lot, I am confused;

      1. Finally, I saw a sentence from the foreign documents. I had an epiphany and used the portecle tool to create a bks-format keystore, and then set the client. the key pair import (import key pair) in pfx and save the bks file. The test is successful. It turns out to be a little bit more.

      PS: It should be okay to use portecle for direct conversion, but I have never been successful. It may be that there is a problem with my java environment, and the old prompt is illegal key size.

      2. Configure the server for two-way authentication, and put ca. bks to the assets or raw of the android project. The corresponding read is in the code

      1. Tks. load (getBaseContext ()
      2. . GetResources ()
      3. . OpenRawResource (R. drawable. lt_client), CLIENT_TRUST_PASSWORD.toCharArray ());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.