1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.server.telecom.testapps;
17 
18 import android.app.Activity;
19 import android.content.Context;
20 import android.os.Bundle;
21 import android.telephony.ImsiEncryptionInfo;
22 import android.text.TextUtils;
23 import android.util.Log;
24 import android.telephony.TelephonyManager;
25 import android.view.View;
26 import android.view.View.OnClickListener;
27 import android.widget.ArrayAdapter;
28 import android.widget.EditText;
29 import android.widget.Toast;
30 
31 import android.app.ProgressDialog;
32 import android.os.AsyncTask;
33 import android.util.Log;
34 import android.widget.ListView;
35 import android.widget.Toast;
36 
37 import org.json.JSONArray;
38 import org.json.JSONException;
39 import org.json.JSONObject;
40 
41 import java.security.KeyFactory;
42 import java.security.NoSuchAlgorithmException;
43 import java.security.PublicKey;
44 import java.security.spec.InvalidKeySpecException;
45 import java.security.spec.X509EncodedKeySpec;
46 
47 import java.io.BufferedInputStream;
48 import java.io.BufferedReader;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.io.InputStreamReader;
52 import java.net.HttpURLConnection;
53 import java.net.MalformedURLException;
54 import java.net.ProtocolException;
55 import java.net.URL;
56 import java.util.ArrayList;
57 import java.util.Date;
58 
59 import android.util.Base64;
60 
61 public class TestCertActivity extends Activity {
62 
63     private EditText mCertUrlView;
64     public static final String LOG_TAG = "TestCertActivity";
65 
66     private ProgressDialog progressDialog;
67     private ArrayList<String> keyList = new ArrayList<String>();
68 
69     // URL to get the json
70     private String mURL = "";
71 
72     @Override
onCreate(Bundle savedInstanceState)73     protected void onCreate(Bundle savedInstanceState) {
74         super.onCreate(savedInstanceState);
75         setContentView(R.layout.testcert_main);
76         findViewById(R.id.get_key_button).setOnClickListener(new OnClickListener() {
77             @Override
78             public void onClick(View v) {
79                 new GetKeys().execute();
80             }
81         });
82 
83         mCertUrlView = (EditText) findViewById(R.id.text);
84         mCertUrlView.setText(mURL);
85     }
86 
87     /**
88      * Class to get json by making HTTP call
89      */
90     private class GetKeys extends AsyncTask<Void, Void, Void> {
91 
92         @Override
onPreExecute()93         protected void onPreExecute() {
94             super.onPreExecute();
95             progressDialog = new ProgressDialog(TestCertActivity.this);
96             progressDialog.setMessage("Downloading...");
97             progressDialog.setCancelable(false);
98             progressDialog.show();
99         }
100 
getCertificateList()101         public String getCertificateList() {
102             String response = null;
103             String mURL = mCertUrlView.getText().toString();
104             try {
105                 URL url = new URL(mURL);
106                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
107                 conn.setRequestMethod("GET");
108                 // read the response
109                 InputStream in = new BufferedInputStream(conn.getInputStream());
110                 response = convertToString(in);
111             } catch (ProtocolException e) {
112                 Log.e(LOG_TAG, "ProtocolException: " + e.getMessage());
113             } catch (MalformedURLException e) {
114                 Log.e(LOG_TAG, "MalformedURLException: " + e.getMessage());
115             } catch (IOException e) {
116                 Log.e(LOG_TAG, "IOException: " + e.getMessage());
117             } catch (Exception e) {
118                 Log.e(LOG_TAG, "Exception: " + e.getMessage());
119             }
120             return response;
121         }
122 
convertToString(InputStream is)123         private String convertToString(InputStream is) {
124             BufferedReader reader = new BufferedReader(new InputStreamReader(is));
125             StringBuilder sb = new StringBuilder();
126 
127             String line;
128             try {
129                 while ((line = reader.readLine()) != null) {
130                     sb.append(line).append('\n');
131                 }
132             } catch (IOException e) {
133                 e.printStackTrace();
134             } finally {
135                 try {
136                     is.close();
137                 } catch (IOException e) {
138                     e.printStackTrace();
139                 }
140             }
141             return sb.toString();
142         }
143 
savePublicKey(String key, int type, String identifier)144         private void savePublicKey(String key, int type, String identifier) {
145             byte[] keyBytes = Base64.decode(key.getBytes(), Base64.DEFAULT);
146             final TelephonyManager telephonyManager =
147                     (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
148 
149             String mcc = "";
150             String mnc = "";
151             String networkOperator = telephonyManager.getNetworkOperator();
152 
153             if (!TextUtils.isEmpty(networkOperator)) {
154                 mcc = networkOperator.substring(0, 3);
155                 mnc = networkOperator.substring(3);
156                 Log.i(LOG_TAG, "using values for mnc, mcc: " + mnc + "," + mcc);
157             }
158 
159             ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo(mcc,
160                     mnc, type, identifier, keyBytes, new Date());
161             telephonyManager.setCarrierInfoForImsiEncryption(imsiEncryptionInfo);
162             keyList.add(imsiEncryptionInfo.getKeyType() + "," +
163                     imsiEncryptionInfo.getKeyIdentifier());
164             Log.i(LOG_TAG,"calling telephonymanager complete");
165         }
166 
167         @Override
doInBackground(Void... arg0)168         protected Void doInBackground(Void... arg0) {
169             // Making a request to url and getting response
170             String jsonStr = getCertificateList();
171             Log.d(LOG_TAG, "Response from url: " + jsonStr);
172 
173             if (jsonStr != null) {
174                 try {
175                     JSONObject jsonObj = new JSONObject(jsonStr);
176                     // Getting JSON Array node
177                     JSONArray certificates = jsonObj.getJSONArray("certificates");
178 
179                     // looping through the certificates
180                     for (int i = 0; i < certificates.length(); i++) {
181                         JSONObject cert = certificates.getJSONObject(i);
182                         String key = cert.getString("key");
183                         int type = cert.getInt("type");
184                         String identifier = cert.getString("identifier");
185                         savePublicKey(key, type, identifier);
186                     }
187                 } catch (final JSONException e) {
188                     Log.e(LOG_TAG, "Json parsing error: " + e.getMessage());
189                     runOnUiThread(new Runnable() {
190                         @Override
191                         public void run() {
192                             Toast.makeText(getApplicationContext(),
193                                     "Json parsing error: " + e.getMessage(),
194                                     Toast.LENGTH_LONG)
195                                     .show();
196                         }
197                     });
198                 }
199             } else {
200                 Log.e(LOG_TAG, "Unable to get JSON from server " + mURL);
201                 runOnUiThread(new Runnable() {
202                     @Override
203                     public void run() {
204                         Toast.makeText(getApplicationContext(),
205                                 "Unable to get JSON from server!",
206                                 Toast.LENGTH_LONG)
207                                 .show();
208                     }
209                 });
210             }
211             return null;
212         }
213 
214         @Override
onPostExecute(Void result)215         protected void onPostExecute(Void result) {
216 
217             super.onPostExecute(result);
218             if (progressDialog.isShowing()) {
219                 progressDialog.dismiss();
220             }
221             ListView listView = (ListView) findViewById(R.id.keylist);
222             ArrayAdapter arrayAdapter =
223                     new ArrayAdapter(TestCertActivity.this, R.layout.key_list, keyList);
224             listView.setAdapter(arrayAdapter);
225         }
226     }
227 }
228 
229 
230