HelperUtils.java 12 KB

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