HelperUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import java.net.InetAddress;
  3. import java.net.UnknownHostException;
  4. import java.security.KeyStore;
  5. import java.security.SecureRandom;
  6. import org.apache.http.HttpVersion;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.conn.ClientConnectionManager;
  10. import org.apache.http.conn.scheme.PlainSocketFactory;
  11. import org.apache.http.conn.scheme.Scheme;
  12. import org.apache.http.conn.scheme.SchemeRegistry;
  13. import org.apache.http.conn.ssl.SSLSocketFactory;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.impl.client.DefaultHttpClient;
  16. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  17. import org.apache.http.params.BasicHttpParams;
  18. import org.apache.http.params.HttpParams;
  19. import org.apache.http.params.HttpProtocolParams;
  20. import org.apache.http.protocol.HTTP;
  21. import android.content.Context;
  22. import android.net.ConnectivityManager;
  23. import android.net.NetworkInfo;
  24. import android.net.wifi.WifiInfo;
  25. import android.net.wifi.WifiManager;
  26. import android.os.Environment;
  27. import android.preference.PreferenceManager;
  28. import android.text.TextUtils;
  29. import de.tudarmstadt.informatik.hostage.logging.Record;
  30. import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
  31. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  32. /**
  33. * Helper class with some static methods for general usage.
  34. *
  35. * @author Lars Pandikow
  36. * @author Wulf Pfeiffer
  37. *
  38. */
  39. public final class HelperUtils {
  40. /**
  41. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
  42. * "00, 01".
  43. *
  44. * @param bytes
  45. * that will be converted.
  46. * @return converted String.
  47. */
  48. public static String bytesToHexString(byte[] bytes) {
  49. char[] hexArray = "0123456789ABCDEF".toCharArray();
  50. int v;
  51. StringBuffer buffer = new StringBuffer();
  52. for (int j = 0; j < bytes.length; j++) {
  53. v = bytes[j] & 0xFF;
  54. buffer.append(hexArray[v >>> 4]);
  55. buffer.append(hexArray[v & 0x0F]);
  56. if (j < bytes.length - 1)
  57. buffer.append(", ");
  58. }
  59. return buffer.toString();
  60. }
  61. /**
  62. * Converts a byte[] to a String, but only characters in ASCII between 32
  63. * and 127
  64. *
  65. * @param bytes
  66. * that are converted
  67. * @return converted String
  68. */
  69. public static String byteToStr(byte[] bytes) {
  70. int size = 0;
  71. for(byte b : bytes) {
  72. if(isLetter((char) b)) {
  73. size++;
  74. }
  75. }
  76. char[] chars = new char[size];
  77. for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
  78. if (isLetter((char) bytes[i])) {
  79. chars[j] = (char) bytes[i];
  80. j++;
  81. }
  82. }
  83. return new String(chars);
  84. }
  85. /**
  86. * Concatenates several byte arrays.
  87. *
  88. * @param bytes
  89. * The byte arrays.
  90. * @return A single byte arrays containing all the bytes from the given
  91. * arrays in the order they are given.
  92. */
  93. public static byte[] concat(byte[]... bytes) {
  94. int newSize = 0;
  95. for (byte[] b : bytes)
  96. if (b != null)
  97. newSize += b.length;
  98. byte[] dst = new byte[newSize];
  99. int currentPos = 0;
  100. int newPos;
  101. for (byte[] b : bytes) {
  102. if (b != null) {
  103. newPos = b.length;
  104. System.arraycopy(b, 0, dst, currentPos, newPos);
  105. currentPos += newPos;
  106. }
  107. }
  108. return dst;
  109. }
  110. /**
  111. * Creates a HttpClient with an own SSL Socket.
  112. *
  113. * @return HttpsClient who accepts accepts all certificates.
  114. * @see MySSLSocketFactory
  115. */
  116. public static HttpClient createHttpClient() {
  117. try {
  118. KeyStore trustStore = KeyStore.getInstance(KeyStore
  119. .getDefaultType());
  120. trustStore.load(null, null);
  121. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  122. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  123. HttpParams params = new BasicHttpParams();
  124. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  125. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  126. SchemeRegistry registry = new SchemeRegistry();
  127. registry.register(new Scheme("http", PlainSocketFactory
  128. .getSocketFactory(), 80));
  129. registry.register(new Scheme("https", sf, 443));
  130. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  131. params, registry);
  132. return new DefaultHttpClient(ccm, params);
  133. } catch (Exception e) {
  134. e.printStackTrace();
  135. return new DefaultHttpClient();
  136. }
  137. }
  138. /**
  139. * Puts a 0x00 byte between each byte in a byte array.
  140. *
  141. * @param bytes
  142. * that need to be filled with 0x00.
  143. * @return filled byte array.
  144. */
  145. public static byte[] fillWithZero(byte[] bytes) {
  146. byte[] newBytes = new byte[(bytes.length * 2)];
  147. for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
  148. newBytes[j] = bytes[i];
  149. newBytes[j + 1] = 0x00;
  150. }
  151. return newBytes;
  152. }
  153. /**
  154. * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
  155. * a byte array.
  156. *
  157. * @param bytes
  158. * that need to be filled with 0x00.
  159. * @return filled byte array.
  160. */
  161. public static byte[] fillWithZeroExtended(byte[] bytes) {
  162. byte[] zeroBytes = fillWithZero(bytes);
  163. byte[] newBytes = new byte[zeroBytes.length + 2];
  164. newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
  165. return newBytes;
  166. }
  167. /**
  168. * Gets BSSID of the wireless network.
  169. *
  170. * @param context
  171. * Needs a context to get system recourses.
  172. * @return BSSID of wireless network if connected, else null.
  173. */
  174. public static String getBSSID(Context context) {
  175. String bssid = null;
  176. ConnectivityManager connManager = (ConnectivityManager) context
  177. .getSystemService(Context.CONNECTIVITY_SERVICE);
  178. NetworkInfo networkInfo = connManager
  179. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  180. if (networkInfo != null && networkInfo.isConnected()) {
  181. final WifiManager wifiManager = (WifiManager) context
  182. .getSystemService(Context.WIFI_SERVICE);
  183. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  184. if (connectionInfo != null
  185. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  186. bssid = connectionInfo.getBSSID();
  187. }
  188. }
  189. return bssid;
  190. }
  191. /**
  192. * Gets internal IP address of the device in a wireless network.
  193. *
  194. * @param context
  195. * Needs a context to get system recourses.
  196. * @return internal IP of the device in a wireless network if connected,
  197. * else null.
  198. */
  199. public static String getInternalIP(Context context) {
  200. String ipAddress = null;
  201. ConnectivityManager connManager = (ConnectivityManager) context
  202. .getSystemService(Context.CONNECTIVITY_SERVICE);
  203. NetworkInfo networkInfo = connManager
  204. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  205. if (networkInfo != null && networkInfo.isConnected()) {
  206. final WifiManager wifiManager = (WifiManager) context
  207. .getSystemService(Context.WIFI_SERVICE);
  208. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  209. if (connectionInfo != null) {
  210. try {
  211. ipAddress = InetAddress.getByAddress(
  212. unpackInetAddress(connectionInfo.getIpAddress()))
  213. .getHostAddress();
  214. } catch (UnknownHostException e) {
  215. e.printStackTrace();
  216. }
  217. }
  218. }
  219. return ipAddress;
  220. }
  221. /**
  222. * Produces a random String. The String can be of random length (minimum 1)
  223. * with a maximum length, or it can be forced to have the length that was
  224. * given.
  225. *
  226. * @param length
  227. * maximal / forced length of String.
  228. * @param forceLength
  229. * forces the String to be exact the given length instead of
  230. * maximum
  231. * @return random String.
  232. */
  233. public static String getRandomString(int length, boolean forceLength) {
  234. SecureRandom rndm = new SecureRandom();
  235. char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
  236. for (int i = 0; i < c.length; i++) {
  237. c[i] = (char) (rndm.nextInt(95) + 32);
  238. }
  239. return new String(c);
  240. }
  241. /**
  242. * Gets SSID of the wireless network.
  243. *
  244. * @param context
  245. * Needs a context to get system recourses
  246. * @return SSID of wireless network if connected, else null.
  247. */
  248. public static String getSSID(Context context) {
  249. String ssid = null;
  250. ConnectivityManager connManager = (ConnectivityManager) context
  251. .getSystemService(Context.CONNECTIVITY_SERVICE);
  252. NetworkInfo networkInfo = connManager
  253. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  254. if (networkInfo != null && networkInfo.isConnected()) {
  255. final WifiManager wifiManager = (WifiManager) context
  256. .getSystemService(Context.WIFI_SERVICE);
  257. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  258. if (connectionInfo != null
  259. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  260. ssid = connectionInfo.getSSID();
  261. }
  262. }
  263. return ssid;
  264. }
  265. /**
  266. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  267. *
  268. * @param string
  269. * that will be converted.
  270. * @return converted byte array.
  271. */
  272. public static byte[] hexStringToBytes(String string) {
  273. String[] hexStrings = string.split(", ");
  274. byte[] bytes = new byte[hexStrings.length];
  275. for (int j = 0; j < hexStrings.length; j++) {
  276. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
  277. .digit(hexStrings[j].charAt(1), 16));
  278. }
  279. return bytes;
  280. }
  281. /**
  282. * Checks if external storage is available for read and write.
  283. *
  284. * @return True if external storage is available for read and write, else
  285. * false.
  286. */
  287. public static boolean isExternalStorageWritable() {
  288. String state = Environment.getExternalStorageState();
  289. if (Environment.MEDIA_MOUNTED.equals(state)) {
  290. return true;
  291. }
  292. return false;
  293. }
  294. /**
  295. * Generates a random byte[] of a specified size
  296. *
  297. * @param size
  298. * of the byte[]
  299. * @return random byte[]
  300. */
  301. public static byte[] randomBytes(int size) {
  302. byte[] bytes = new byte[size];
  303. SecureRandom rdm = new SecureRandom();
  304. rdm.nextBytes(bytes);
  305. return bytes;
  306. }
  307. /**
  308. * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
  309. * {0x02, 0x01, 0x00}.
  310. *
  311. * @param bytes
  312. * array that is turned.
  313. * @return turned array.
  314. */
  315. public static byte[] turnByteArray(byte[] bytes) {
  316. byte[] tmp = new byte[bytes.length];
  317. for (int i = 0; i < bytes.length; i++) {
  318. tmp[i] = bytes[bytes.length - 1 - i];
  319. }
  320. return tmp;
  321. }
  322. /**
  323. * Uploads a single Record to a server, specified in the settings.
  324. *
  325. * @param record
  326. * The Record to upload.
  327. * @return True if the upload was successful, else false.
  328. */
  329. public static boolean uploadSingleRecord(Context context, Record record) {
  330. // Create a https client. Uses MySSLSocketFactory to accept all
  331. // certificates
  332. HttpClient httpclient = HelperUtils.createHttpClient();
  333. HttpPost httppost;
  334. try {
  335. // Create HttpPost
  336. httppost = new HttpPost(PreferenceManager
  337. .getDefaultSharedPreferences(context).getString(
  338. "pref_upload", "https://ssi.cased.de"));
  339. // Create JSON String of Record
  340. StringEntity se = new StringEntity(record.toString(TraCINgFormatter
  341. .getInstance()));
  342. httppost.setEntity(se);
  343. // Execute HttpPost
  344. httpclient.execute(httppost);
  345. } catch (Exception e) {
  346. e.printStackTrace();
  347. return false;
  348. }
  349. return true;
  350. }
  351. /**
  352. * Determines if a character is in ASCII between 32 and 126
  353. *
  354. * @param character
  355. * that is checked
  356. * @return true if the character is between 32 and 126, else false
  357. */
  358. private static boolean isLetter(char character) {
  359. return (character > 31 && character < 127);
  360. }
  361. private static byte[] unpackInetAddress(int bytes) {
  362. return new byte[] { (byte) ((bytes) & 0xff),
  363. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  364. (byte) ((bytes >>> 24) & 0xff) };
  365. }
  366. public static boolean isWifiConnected(Context context){
  367. ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  368. NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  369. return mWifi.isConnected();
  370. }
  371. }