From 99b823bc2802c28ae669d061f771986b0534ce60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rui=20Ara=C3=BAjo?= Date: Mon, 1 Jun 2015 17:11:59 +0200 Subject: [PATCH] Update version. Reformat the code. --- .../afilechooser/FileListFragment.java | 28 +- .../afilechooser/utils/FileUtils.java | 110 ++- android/routerKeygen/build.gradle | 3 +- android/routerKeygen/lint.xml | 3 +- .../routerKeygen/src/main/AndroidManifest.xml | 20 +- .../connecter/ConfigurationSecurities.java | 41 +- .../connecter/ConfigurationSecuritiesOld.java | 121 +-- .../connecter/ConfigurationSecuritiesV8.java | 201 +++-- .../com/farproc/wifi/connecter/Version.java | 40 +- .../java/com/farproc/wifi/connecter/Wifi.java | 547 +++++++------- .../com/hb/views/PinnedSectionListView.java | 118 +-- .../java/com/robobunny/SeekBarPreference.java | 402 +++++----- .../changelibs/library/Constants.java | 20 +- .../library/internal/ChangeLog.java | 38 +- .../library/internal/ChangeLogAdapter.java | 111 ++- .../library/internal/ChangeLogException.java | 14 +- .../library/internal/ChangeLogRow.java | 82 ++- .../library/internal/ChangeLogRowHeader.java | 24 +- .../changelibs/library/parser/BaseParser.java | 16 +- .../changelibs/library/parser/XmlParser.java | 134 ++-- .../library/view/ChangeLogListView.java | 370 +++++----- .../org/exobel/routerkeygen/AdsUtils.java | 331 +++++---- .../routerkeygen/AutoConnectManager.java | 4 +- .../routerkeygen/AutoConnectService.java | 422 ++++++----- .../java/org/exobel/routerkeygen/Base64.java | 646 ++++++++-------- .../routerkeygen/CancelOperationActivity.java | 92 +-- .../DictionaryDownloadService.java | 552 +++++++------- .../org/exobel/routerkeygen/Downloader.java | 188 ++--- .../org/exobel/routerkeygen/JenkinsHash.java | 161 ++-- .../routerkeygen/NotificationUtils.java | 126 ++-- .../exobel/routerkeygen/RefreshHandler.java | 44 +- .../routerkeygen/RouterKeygenApplication.java | 100 +-- .../routerkeygen/UpdateCheckerService.java | 183 +++-- .../exobel/routerkeygen/WifiScanReceiver.java | 40 +- .../routerkeygen/WifiStateReceiver.java | 48 +- .../exobel/routerkeygen/WirelessMatcher.java | 688 +++++++++--------- .../algorithms/AliceGermanyKeygen.java | 121 ++- .../algorithms/AliceItalyKeygen.java | 259 ++++--- .../algorithms/AndaredKeygen.java | 34 +- .../algorithms/ArcadyanKeygen.java | 178 ++--- .../algorithms/ArnetPirelliKeygen.java | 125 ++-- .../routerkeygen/algorithms/AxtelKeygen.java | 62 +- .../routerkeygen/algorithms/BelkinKeygen.java | 155 ++-- .../algorithms/CabovisaoSagemKeygen.java | 60 +- .../algorithms/ComtrendKeygen.java | 156 ++-- .../routerkeygen/algorithms/ConnKeygen.java | 104 +-- .../routerkeygen/algorithms/DiscusKeygen.java | 41 +- .../routerkeygen/algorithms/DlinkKeygen.java | 170 +++-- .../routerkeygen/algorithms/EircomKeygen.java | 90 +-- .../routerkeygen/algorithms/HuaweiKeygen.java | 292 ++++---- .../algorithms/InfostradaKeygen.java | 45 +- .../algorithms/InterCableKeygen.java | 72 +- .../routerkeygen/algorithms/Keygen.java | 210 +++--- .../routerkeygen/algorithms/MaxcomKeygen.java | 46 +- .../algorithms/MegaredKeygen.java | 44 +- .../algorithms/MeoPirelliKeygen.java | 80 +- .../algorithms/NativeThomson.java | 259 ++++--- .../routerkeygen/algorithms/OnoKeygen.java | 142 ++-- .../algorithms/OteBAUDKeygen.java | 45 +- .../algorithms/OteHuaweiKeygen.java | 103 ++- .../routerkeygen/algorithms/OteKeygen.java | 62 +- .../routerkeygen/algorithms/PBSKeygen.java | 154 ++-- .../algorithms/PirelliKeygen.java | 140 ++-- .../routerkeygen/algorithms/PtvKeygen.java | 44 +- .../algorithms/SitecomKeygen.java | 128 ++-- .../routerkeygen/algorithms/SkyV1Keygen.java | 91 ++- .../algorithms/Speedport500Keygen.java | 67 +- .../routerkeygen/algorithms/TecomKeygen.java | 69 +- .../routerkeygen/algorithms/TeleTuKeygen.java | 82 +-- .../routerkeygen/algorithms/TelseyKeygen.java | 393 +++++----- .../algorithms/ThomsonKeygen.java | 151 ++-- .../routerkeygen/algorithms/TplinkKeygen.java | 46 +- .../algorithms/VerizonKeygen.java | 98 ++- .../routerkeygen/algorithms/WiFiNetwork.java | 129 ++-- .../algorithms/WifimediaRKeygen.java | 67 +- .../routerkeygen/algorithms/Wlan2Keygen.java | 148 ++-- .../routerkeygen/algorithms/Wlan6Keygen.java | 165 +++-- .../routerkeygen/algorithms/ZyxelKeygen.java | 107 ++- .../config/AliceConfigParser.java | 52 +- .../routerkeygen/config/AliceMagicInfo.java | 86 ++- .../config/OTEHuaweiConfigParser.java | 32 +- .../config/TeleTuConfigParser.java | 58 +- .../routerkeygen/config/TeleTuMagicInfo.java | 91 ++- .../routerkeygen/ui/ManualInputActivity.java | 126 ++-- .../routerkeygen/ui/ManualInputFragment.java | 432 ++++++----- .../routerkeygen/ui/MessagePublisher.java | 2 +- .../routerkeygen/ui/NetworkActivity.java | 156 ++-- .../routerkeygen/ui/NetworkFragment.java | 223 +++--- .../routerkeygen/ui/NetworksListActivity.java | 639 ++++++++-------- .../routerkeygen/ui/NetworksListFragment.java | 396 +++++----- .../exobel/routerkeygen/ui/Preferences.java | 411 ++++++----- .../routerkeygen/ui/WifiListAdapter.java | 423 ++++++----- .../exobel/routerkeygen/utils/HashUtils.java | 42 +- .../routerkeygen/utils/InputStreamUtils.java | 36 + .../routerkeygen/utils/StringUtils.java | 155 ++-- .../actionbar_indeterminate_progress.xml | 2 +- .../main/res/layout-v11/activity_twopane.xml | 6 +- .../main/res/layout-v11/item_list_wifi.xml | 11 +- .../res/layout-v14/changelogrow_layout.xml | 2 +- .../res/layout-v14/fragment_manual_input.xml | 11 +- .../src/main/res/layout/about_dialog.xml | 125 ++-- .../actionbar_indeterminate_progress.xml | 2 +- .../res/layout/activity_cancel_operation.xml | 1 - .../res/layout/activity_networks_list.xml | 2 +- .../res/layout/activity_single_fragment.xml | 2 +- .../src/main/res/layout/activity_twopane.xml | 4 +- .../main/res/layout/changelogrow_layout.xml | 2 +- .../res/layout/changelogrowheader_layout.xml | 52 +- .../src/main/res/layout/dialog_changelog.xml | 5 +- .../main/res/layout/fragment_manual_input.xml | 11 +- .../src/main/res/layout/fragment_network.xml | 54 +- .../res/layout/fragment_networks_list.xml | 4 +- .../src/main/res/layout/item_list_wifi.xml | 11 +- .../src/main/res/layout/notification.xml | 2 +- .../src/main/res/layout/preferences.xml | 11 +- .../src/main/res/layout/results.xml | 11 +- .../main/res/layout/seek_bar_preference.xml | 14 +- .../main/res/menu/networks_context_menu.xml | 11 +- .../src/main/res/menu/networks_list.xml | 9 +- .../src/main/res/menu/preferences.xml | 11 +- .../src/main/res/menu/share_keys.xml | 23 +- .../src/main/res/raw/changelog.xml | 65 +- .../src/main/res/values-es/strings.xml | 13 +- .../src/main/res/values-fr/strings.xml | 60 +- .../src/main/res/values-it/strings.xml | 37 +- .../src/main/res/values-large/refs.xml | 2 +- .../src/main/res/values-nl/strings.xml | 18 +- .../src/main/res/values-pt/strings.xml | 13 +- .../src/main/res/values-sw600dp/refs.xml | 2 +- .../src/main/res/values/strings.xml | 12 +- android/routerkeygen_version.json | 5 +- 131 files changed, 7540 insertions(+), 7548 deletions(-) create mode 100644 android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/InputStreamUtils.java diff --git a/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/FileListFragment.java b/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/FileListFragment.java index 5da363a..c8cab13 100644 --- a/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/FileListFragment.java +++ b/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/FileListFragment.java @@ -37,23 +37,9 @@ public class FileListFragment extends ListFragment implements LoaderManager.LoaderCallbacks> { - /** - * Interface to listen for events. - */ - public interface Callbacks { - /** - * Called when a file is selected from the list. - * - * @param file The file selected - */ - public void onFileSelected(File file); - } - private static final int LOADER_ID = 0; - private FileListAdapter mAdapter; private String mPath; - private Callbacks mListener; /** @@ -108,7 +94,7 @@ public void onActivityCreated(Bundle savedInstanceState) { public void onListItemClick(ListView l, View v, int position, long id) { FileListAdapter adapter = (FileListAdapter) l.getAdapter(); if (adapter != null) { - File file = (File) adapter.getItem(position); + File file = adapter.getItem(position); mPath = file.getAbsolutePath(); mListener.onFileSelected(file); } @@ -133,4 +119,16 @@ public void onLoadFinished(Loader> loader, List data) { public void onLoaderReset(Loader> loader) { mAdapter.clear(); } + + /** + * Interface to listen for events. + */ + public interface Callbacks { + /** + * Called when a file is selected from the list. + * + * @param file The file selected + */ + void onFileSelected(File file); + } } diff --git a/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/utils/FileUtils.java b/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/utils/FileUtils.java index 25c8008..9110a35 100644 --- a/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/utils/FileUtils.java +++ b/android/aFileChooser/src/main/java/com/ipaulpro/afilechooser/utils/FileUtils.java @@ -45,19 +45,57 @@ * @author paulburke (ipaulpro) */ public class FileUtils { - private FileUtils() {} //private constructor to enforce Singleton pattern - - /** TAG for log messages. */ - static final String TAG = "FileUtils"; - private static final boolean DEBUG = false; // Set to true to enable logging - public static final String MIME_TYPE_AUDIO = "audio/*"; public static final String MIME_TYPE_TEXT = "text/*"; public static final String MIME_TYPE_IMAGE = "image/*"; public static final String MIME_TYPE_VIDEO = "video/*"; public static final String MIME_TYPE_APP = "application/*"; - public static final String HIDDEN_PREFIX = "."; + /** TAG for log messages. */ + static final String TAG = "FileUtils"; + private static final boolean DEBUG = false; // Set to true to enable logging + /** + * File and folder comparator. TODO Expose sorting option method + * + * @author paulburke + */ + public static Comparator sComparator = new Comparator() { + @Override + public int compare(File f1, File f2) { + // Sort alphabetically by lower case, which is much cleaner + return f1.getName().toLowerCase().compareTo( + f2.getName().toLowerCase()); + } + }; + /** + * File (not directories) filter. + * + * @author paulburke + */ + public static FileFilter sFileFilter = new FileFilter() { + @Override + public boolean accept(File file) { + final String fileName = file.getName(); + // Return files only (not directories) and skip hidden files + return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX); + } + }; + /** + * Folder (directories) filter. + * + * @author paulburke + */ + public static FileFilter sDirFilter = new FileFilter() { + @Override + public boolean accept(File file) { + final String fileName = file.getName(); + // Return directories only and skip hidden directories + return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX); + } + }; + + private FileUtils() { + } //private constructor to enforce Singleton pattern /** * Gets the extension of a file name, like ".png" or ".jpg". @@ -84,10 +122,7 @@ public static String getExtension(String uri) { * @return Whether the URI is a local one. */ public static boolean isLocal(String url) { - if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) { - return true; - } - return false; + return url != null && !url.startsWith("http://") && !url.startsWith("https://"); } /** @@ -215,7 +250,7 @@ public static boolean isGooglePhotosUri(Uri uri) { * @author paulburke */ public static String getDataColumn(Context context, Uri uri, String selection, - String[] selectionArgs) { + String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; @@ -247,7 +282,7 @@ public static String getDataColumn(Context context, Uri uri, String selection, *
* Callers should check whether the path is local before assuming it * represents a local file. - * + * * @param context The context. * @param uri The Uri to query. * @see #isLocal(String) @@ -265,7 +300,7 @@ public static String getPath(final Context context, final Uri uri) { ", Scheme: " + uri.getScheme() + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString() - ); + ); final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; @@ -313,7 +348,7 @@ else if (isMediaDocument(uri)) { } final String selection = "_id=?"; - final String[] selectionArgs = new String[] { + final String[] selectionArgs = new String[]{ split[1] }; @@ -448,8 +483,7 @@ public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) { id, MediaStore.Video.Thumbnails.MINI_KIND, null); - } - else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) { + } else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) { bm = MediaStore.Images.Thumbnails.getThumbnail( resolver, id, @@ -468,48 +502,6 @@ else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) { return bm; } - /** - * File and folder comparator. TODO Expose sorting option method - * - * @author paulburke - */ - public static Comparator sComparator = new Comparator() { - @Override - public int compare(File f1, File f2) { - // Sort alphabetically by lower case, which is much cleaner - return f1.getName().toLowerCase().compareTo( - f2.getName().toLowerCase()); - } - }; - - /** - * File (not directories) filter. - * - * @author paulburke - */ - public static FileFilter sFileFilter = new FileFilter() { - @Override - public boolean accept(File file) { - final String fileName = file.getName(); - // Return files only (not directories) and skip hidden files - return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX); - } - }; - - /** - * Folder (directories) filter. - * - * @author paulburke - */ - public static FileFilter sDirFilter = new FileFilter() { - @Override - public boolean accept(File file) { - final String fileName = file.getName(); - // Return directories only and skip hidden directories - return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX); - } - }; - /** * Get the Intent for selecting content to be used in an Intent Chooser. * diff --git a/android/routerKeygen/build.gradle b/android/routerKeygen/build.gradle index 88d0fc1..bc53001 100644 --- a/android/routerKeygen/build.gradle +++ b/android/routerKeygen/build.gradle @@ -77,9 +77,8 @@ def getNdkBuildCmd() { dependencies { compile project(':aFileChooser') compile 'com.android.support:support-v4:22.1.1' - compile 'com.google.android.gms:play-services:+' + compile 'com.google.android.gms:play-services:7.3.0' compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' - compile 'com.android.support:support-v4:22.1.0' compile 'ch.acra:acra:4.6.2' compile files('libs/MMSDK.jar') } diff --git a/android/routerKeygen/lint.xml b/android/routerKeygen/lint.xml index 8423c0e..c70207f 100644 --- a/android/routerKeygen/lint.xml +++ b/android/routerKeygen/lint.xml @@ -1,3 +1,2 @@ - - \ No newline at end of file + \ No newline at end of file diff --git a/android/routerKeygen/src/main/AndroidManifest.xml b/android/routerKeygen/src/main/AndroidManifest.xml index 1d295d4..ad78796 100644 --- a/android/routerKeygen/src/main/AndroidManifest.xml +++ b/android/routerKeygen/src/main/AndroidManifest.xml @@ -2,8 +2,8 @@ + android:versionCode="37" + android:versionName="3.14.2"> + android:theme="@style/Theme.Sherlock"> - + android:label="@string/menu_preferences"> + android:label="@string/app_name"> @@ -55,23 +54,24 @@ + android:label="@string/app_name"> + android:value=".ui.NetworksListActivity" /> + android:label="@string/menu_manual"> + android:value=".ui.NetworksListActivity" /> + = 0; i--) { + final char c = key.charAt(i); + if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { + return false; + } + } + + return true; + } + + @Override + public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) { // If we never set group ciphers, wpa_supplicant puts all of them. @@ -40,7 +62,7 @@ public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { // For WEP, we specifically only set WEP40 and WEP104, so CCMP // and TKIP should not be there. if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP) - && + && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40) || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) { return WEP; @@ -61,7 +83,7 @@ public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { } } - @Override + @Override public String getScanResultSecurity(ScanResult scanResult) { final String cap = scanResult.capabilities; for (int i = SECURITY_MODES.length - 1; i >= 0; i--) { @@ -69,54 +91,33 @@ public String getScanResultSecurity(ScanResult scanResult) { return SECURITY_MODES[i]; } } - + return OPEN; } - @Override - public String getDisplaySecirityString(final ScanResult scanResult) { - return getScanResultSecurity(scanResult); - } - - private static boolean isHexWepKey(String wepKey) { - final int len = wepKey.length(); - - // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) - if (len != 10 && len != 26 && len != 58) { - return false; - } - - return isHex(wepKey); - } - - private static boolean isHex(String key) { - for (int i = key.length() - 1; i >= 0; i--) { - final char c = key.charAt(i); - if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { - return false; - } - } - - return true; + + @Override + public String getDisplaySecirityString(final ScanResult scanResult) { + return getScanResultSecurity(scanResult); } - @Override - public void setupSecurity(WifiConfiguration config, String security, final String password) { + @Override + public void setupSecurity(WifiConfiguration config, String security, final String password) { config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); - + if (TextUtils.isEmpty(security)) { security = OPEN; Log.w(TAG, "Empty security, assuming open"); } - + if (security.equals(WEP)) { - int wepPasswordType = WEP_PASSWORD_AUTO; + int wepPasswordType = WEP_PASSWORD_AUTO; // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { - if (wepPasswordType == WEP_PASSWORD_AUTO) { + if (wepPasswordType == WEP_PASSWORD_AUTO) { if (isHexWepKey(password)) { config.wepKeys[0] = password; } else { @@ -128,28 +129,28 @@ public void setupSecurity(WifiConfiguration config, String security, final Strin : password; } } - + config.wepTxKeyIndex = 0; - + config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); config.allowedKeyManagement.set(KeyMgmt.NONE); - + config.allowedGroupCiphers.set(GroupCipher.WEP40); config.allowedGroupCiphers.set(GroupCipher.WEP104); - - } else if (security.equals(WPA) || security.equals(WPA2)){ + + } else if (security.equals(WPA) || security.equals(WPA2)) { config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); - + config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); - + config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP); config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP); config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA); - + // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (password.length() == 64 && isHex(password)) { @@ -160,7 +161,7 @@ public void setupSecurity(WifiConfiguration config, String security, final Strin config.preSharedKey = Wifi.convertToQuotedString(password); } } - + } else if (security.equals(OPEN)) { config.allowedKeyManagement.set(KeyMgmt.NONE); } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) { @@ -177,9 +178,9 @@ public void setupSecurity(WifiConfiguration config, String security, final Strin } } - @Override - public boolean isOpenNetwork(String security) { - return OPEN.equals(security); - } + @Override + public boolean isOpenNetwork(String security) { + return OPEN.equals(security); + } } diff --git a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/ConfigurationSecuritiesV8.java b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/ConfigurationSecuritiesV8.java index 47efe80..857de05 100644 --- a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/ConfigurationSecuritiesV8.java +++ b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/ConfigurationSecuritiesV8.java @@ -7,21 +7,13 @@ import android.util.Log; public class ConfigurationSecuritiesV8 extends ConfigurationSecurities { - - static final int SECURITY_NONE = 0; + + static final int SECURITY_NONE = 0; static final int SECURITY_WEP = 1; static final int SECURITY_PSK = 2; static final int SECURITY_EAP = 3; - - enum PskType { - UNKNOWN, - WPA, - WPA2, - WPA_WPA2 - } - private static final String TAG = "ConfigurationSecuritiesV14"; - + private static int getSecurity(WifiConfiguration config) { if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { return SECURITY_PSK; @@ -44,60 +36,75 @@ private static int getSecurity(ScanResult result) { return SECURITY_NONE; } - @Override - public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { - return String.valueOf(getSecurity(wifiConfig)); - } + private static PskType getPskType(ScanResult result) { + boolean wpa = result.capabilities.contains("WPA-PSK"); + boolean wpa2 = result.capabilities.contains("WPA2-PSK"); + if (wpa2 && wpa) { + return PskType.WPA_WPA2; + } else if (wpa2) { + return PskType.WPA2; + } else if (wpa) { + return PskType.WPA; + } else { + Log.w(TAG, "Received abnormal flag string: " + result.capabilities); + return PskType.UNKNOWN; + } + } + + @Override + public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { + return String.valueOf(getSecurity(wifiConfig)); + } - @Override - public String getScanResultSecurity(ScanResult scanResult) { - return String.valueOf(getSecurity(scanResult)); - } + @Override + public String getScanResultSecurity(ScanResult scanResult) { + return String.valueOf(getSecurity(scanResult)); + } - @Override - public void setupSecurity(WifiConfiguration config, String security, String password) { - config.allowedAuthAlgorithms.clear(); + @Override + public void setupSecurity(WifiConfiguration config, String security, String password) { + config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); - + final int sec = security == null ? SECURITY_NONE : Integer.valueOf(security); final int passwordLen = password == null ? 0 : password.length(); switch (sec) { - case SECURITY_NONE: - config.allowedKeyManagement.set(KeyMgmt.NONE); - break; - - case SECURITY_WEP: - config.allowedKeyManagement.set(KeyMgmt.NONE); - config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); - config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); - if (passwordLen != 0) { - // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) - if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) && - password.matches("[0-9A-Fa-f]*")) { - config.wepKeys[0] = password; - } else { - config.wepKeys[0] = '"' + password + '"'; + case SECURITY_NONE: + config.allowedKeyManagement.set(KeyMgmt.NONE); + break; + + case SECURITY_WEP: + config.allowedKeyManagement.set(KeyMgmt.NONE); + config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); + config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); + if (passwordLen != 0) { + // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) + if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) && + password.matches("[0-9A-Fa-f]*")) { + config.wepKeys[0] = password; + } else { + config.wepKeys[0] = '"' + password + '"'; + } } - } - break; - - case SECURITY_PSK: - config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); - if (passwordLen != 0) { - if (password.matches("[0-9A-Fa-f]{64}")) { - config.preSharedKey = password; - } else { - config.preSharedKey = '"' + password + '"'; + break; + + case SECURITY_PSK: + config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); + if (passwordLen != 0) { + if (password.matches("[0-9A-Fa-f]{64}")) { + config.preSharedKey = password; + } else { + config.preSharedKey = '"' + password + '"'; + } } - } - break; + break; - case SECURITY_EAP: - config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); - config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); + case SECURITY_EAP: + config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); + config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); // config.eap.setValue((String) mEapMethodSpinner.getSelectedItem()); // // config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition() == 0) ? "" : @@ -118,63 +125,55 @@ public void setupSecurity(WifiConfiguration config, String security, String pass // if (mPasswordView.length() != 0) { // config.password.setValue(mPasswordView.getText().toString()); // } - break; + break; - default: + default: Log.e(TAG, "Invalid security type: " + sec); - } + } // config.proxySettings = mProxySettings; // config.ipAssignment = mIpAssignment; // config.linkProperties = new LinkProperties(mLinkProperties); - - } - - private static PskType getPskType(ScanResult result) { - boolean wpa = result.capabilities.contains("WPA-PSK"); - boolean wpa2 = result.capabilities.contains("WPA2-PSK"); - if (wpa2 && wpa) { - return PskType.WPA_WPA2; - } else if (wpa2) { - return PskType.WPA2; - } else if (wpa) { - return PskType.WPA; + + } + + @Override + public String getDisplaySecirityString(final ScanResult scanResult) { + final int security = getSecurity(scanResult); + if (security == SECURITY_PSK) { + switch (getPskType(scanResult)) { + case WPA: + return "WPA"; + case WPA_WPA2: + case WPA2: + return "WPA2"; + default: + return "?"; + } } else { - Log.w(TAG, "Received abnormal flag string: " + result.capabilities); - return PskType.UNKNOWN; + switch (security) { + case SECURITY_NONE: + return "OPEN"; + case SECURITY_WEP: + return "WEP"; + case SECURITY_EAP: + return "EAP"; + } } + + return "?"; + } + + @Override + public boolean isOpenNetwork(String security) { + return String.valueOf(SECURITY_NONE).equals(security); } - @Override - public String getDisplaySecirityString(final ScanResult scanResult) { - final int security = getSecurity(scanResult); - if(security == SECURITY_PSK) { - switch(getPskType(scanResult)) { - case WPA: - return "WPA"; - case WPA_WPA2: - case WPA2: - return "WPA2"; - default: - return "?"; - } - } else { - switch(security) { - case SECURITY_NONE: - return "OPEN"; - case SECURITY_WEP: - return "WEP"; - case SECURITY_EAP: - return "EAP"; - } - } - - return "?"; - } - - @Override - public boolean isOpenNetwork(String security) { - return String.valueOf(SECURITY_NONE).equals(security); - } + enum PskType { + UNKNOWN, + WPA, + WPA2, + WPA_WPA2 + } } diff --git a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Version.java b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Version.java index 43da246..c23a65f 100644 --- a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Version.java +++ b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Version.java @@ -1,30 +1,30 @@ package com.farproc.wifi.connecter; -import java.lang.reflect.Field; +import android.os.Build.VERSION; -import android.os.Build.VERSION;; +import java.lang.reflect.Field; /** * Get Android version in different Android versions. :) - * @author yuanxiaohui * + * @author yuanxiaohui */ public class Version { - - public final static int SDK = get(); - - @SuppressWarnings("deprecation") - private static int get() { - final Class versionClass = VERSION.class; - try { - // First try to read the recommended field android.os.Build.VERSION.SDK_INT. - final Field sdkIntField = versionClass.getField("SDK_INT"); - return sdkIntField.getInt(null); - }catch (NoSuchFieldException e) { - // If SDK_INT does not exist, read the deprecated field SDK. - return Integer.valueOf(VERSION.SDK); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + + public final static int SDK = get(); + + @SuppressWarnings("deprecation") + private static int get() { + final Class versionClass = VERSION.class; + try { + // First try to read the recommended field android.os.Build.VERSION.SDK_INT. + final Field sdkIntField = versionClass.getField("SDK_INT"); + return sdkIntField.getInt(null); + } catch (NoSuchFieldException e) { + // If SDK_INT does not exist, read the deprecated field SDK. + return Integer.valueOf(VERSION.SDK); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Wifi.java b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Wifi.java index 5c4340a..b910637 100644 --- a/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Wifi.java +++ b/android/routerKeygen/src/main/java/com/farproc/wifi/connecter/Wifi.java @@ -21,13 +21,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - **/ + **/ package com.farproc.wifi.connecter; -import java.util.Comparator; -import java.util.List; - import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; @@ -35,281 +32,287 @@ import android.text.TextUtils; import android.util.Log; +import java.util.Comparator; +import java.util.List; + public class Wifi { - - public static final ConfigurationSecurities ConfigSec = ConfigurationSecurities.newInstance(); - - private static final String TAG = "Wifi Connecter"; - - /** - * Change the password of an existing configured network and connect to it - * @param wifiMgr - * @param config - * @param newPassword - * @return - */ - public static int changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) { - ConfigSec.setupSecurity(config, ConfigSec.getWifiConfigurationSecurity(config), newPassword); - final int networkId = wifiMgr.updateNetwork(config); - if(networkId == -1) { - // Update failed. - return -1; - } - // Force the change to apply. - wifiMgr.disconnect(); - return connectToConfiguredNetwork(ctx, wifiMgr, config, true); - } - - /** - * Configure a network, and connect to it. - * @param wifiMgr - * @param scanResult - * @param password Password for secure network or is ignored. - * @return - */ - public static int connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) { - final String security = ConfigSec.getScanResultSecurity(scanResult); - - if(ConfigSec.isOpenNetwork(security)) { - checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept); - } - - WifiConfiguration config = new WifiConfiguration(); - config.SSID = convertToQuotedString(scanResult.SSID); - config.BSSID = scanResult.BSSID; - ConfigSec.setupSecurity(config, security, password); - - int id = -1; - try { - id = wifiMgr.addNetwork(config); - } catch(NullPointerException e) { - Log.e(TAG, "Weird!! Really!! What's wrong??", e); - // Weird!! Really!! - // This exception is reported by user to Android Developer Console(https://market.android.com/publish/Home) - } - if(id == -1) { - return -1; - } - - if(!wifiMgr.saveConfiguration()) { - return -1; - } - - config = getWifiConfiguration(wifiMgr, config, security); - if(config == null) { - return -1; - } - - return connectToConfiguredNetwork(ctx, wifiMgr, config, true); - } - - /** - * Connect to a configured network. - * @param wifiManager - * @param config - * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT - * @return - */ - public static int connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) { - final String security = ConfigSec.getWifiConfigurationSecurity(config); - int configId = config.networkId; - int oldPri = config.priority; - // Make it the highest priority. - int newPri = getMaxPriority(wifiMgr) + 1; - if(newPri > MAX_PRIORITY) { - newPri = shiftPriorityAndSave(wifiMgr); - config = getWifiConfiguration(wifiMgr, config, security); - if(config == null) { - return -1; - } - } - - // Set highest priority to this configured network - config.priority = newPri; - int networkId = wifiMgr.updateNetwork(config); - if(networkId == -1) { - return -1; - } - - // Do not disable others - if(!wifiMgr.enableNetwork(networkId, false)) { - config.priority = oldPri; - return -1; - } - - if(!wifiMgr.saveConfiguration()) { - config.priority = oldPri; - return -1; - } - - // We have to retrieve the WifiConfiguration after save. - config = getWifiConfiguration(wifiMgr, config, security); - if(config == null) { - return -1; - } - - // Disable others, but do not save. - // Just to force the WifiManager to connect to it. - if(!wifiMgr.enableNetwork(config.networkId, true)) { - return -1; - } - - final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect(); - if(!connect) { - return -1; - } - - return configId; - } - - private static void sortByPriority(final List configurations) { - java.util.Collections.sort(configurations, new Comparator() { - - public int compare(WifiConfiguration object1, - WifiConfiguration object2) { - return object1.priority - object2.priority; - } - }); - } - - /** - * Ensure no more than numOpenNetworksKept open networks in configuration list. - * @param wifiMgr - * @param numOpenNetworksKept - * @return Operation succeed or not. - */ - private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) { - final List configurations = wifiMgr.getConfiguredNetworks(); - sortByPriority(configurations); - - boolean modified = false; - int tempCount = 0; - for(int i = configurations.size() - 1; i >= 0; i--) { - final WifiConfiguration config = configurations.get(i); - if(ConfigSec.isOpenNetwork(ConfigSec.getWifiConfigurationSecurity(config))) { - tempCount++; - if(tempCount >= numOpenNetworksKept) { - modified = true; - wifiMgr.removeNetwork(config.networkId); - } - } - } - if(modified) { - return wifiMgr.saveConfiguration(); - } - - return true; - } - - private static final int MAX_PRIORITY = 99999; - - private static int shiftPriorityAndSave(final WifiManager wifiMgr) { - final List configurations = wifiMgr.getConfiguredNetworks(); - sortByPriority(configurations); - final int size = configurations.size(); - for(int i = 0; i < size; i++) { - final WifiConfiguration config = configurations.get(i); - config.priority = i; - wifiMgr.updateNetwork(config); - } - wifiMgr.saveConfiguration(); - return size; - } - - private static int getMaxPriority(final WifiManager wifiManager) { - final List configurations = wifiManager.getConfiguredNetworks(); - int pri = 0; - for(final WifiConfiguration config : configurations) { - if(config.priority > pri) { - pri = config.priority; - } - } - return pri; - } - - public static void cleanPreviousConfiguration(final WifiManager wifiMgr, final ScanResult hotspot, String hotspotSecurity) { - WifiConfiguration config; - do{ - config = getWifiConfiguration(wifiMgr, hotspot, null); - if ( config!= null) - wifiMgr.removeNetwork(config.networkId); - } while ( config != null ); - } - - public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final ScanResult hotspot, String hotspotSecurity) { - final String ssid = convertToQuotedString(hotspot.SSID); - if(ssid.length() == 0) { - return null; - } - - final String bssid = hotspot.BSSID; - if(bssid == null) { - return null; - } - - if(hotspotSecurity == null) { - hotspotSecurity = ConfigSec.getScanResultSecurity(hotspot); - } - - final List configurations = wifiMgr.getConfiguredNetworks(); - if(configurations == null) { - return null; - } - - for(final WifiConfiguration config : configurations) { - if(config.SSID == null || !ssid.equals(config.SSID)) { - continue; - } - if(config.BSSID == null || bssid.equals(config.BSSID)) { - final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); - if(hotspotSecurity.equals(configSecurity)) { - return config; - } - } - } - return null; - } - - public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final WifiConfiguration configToFind, String security) { - final String ssid = configToFind.SSID; - if(ssid.length() == 0) { - return null; - } - - final String bssid = configToFind.BSSID; - - - if(security == null) { - security = ConfigSec.getWifiConfigurationSecurity(configToFind); - } - - final List configurations = wifiMgr.getConfiguredNetworks(); - - for(final WifiConfiguration config : configurations) { - if(config.SSID == null || !ssid.equals(config.SSID)) { - continue; - } - if(config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) { - final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); - if(security.equals(configSecurity)) { - return config; - } - } - } - return null; - } - - public static String convertToQuotedString(String string) { + + public static final ConfigurationSecurities ConfigSec = ConfigurationSecurities.newInstance(); + + private static final String TAG = "Wifi Connecter"; + private static final int MAX_PRIORITY = 99999; + + /** + * Change the password of an existing configured network and connect to it + * + * @param wifiMgr + * @param config + * @param newPassword + * @return + */ + public static int changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) { + ConfigSec.setupSecurity(config, ConfigSec.getWifiConfigurationSecurity(config), newPassword); + final int networkId = wifiMgr.updateNetwork(config); + if (networkId == -1) { + // Update failed. + return -1; + } + // Force the change to apply. + wifiMgr.disconnect(); + return connectToConfiguredNetwork(ctx, wifiMgr, config, true); + } + + /** + * Configure a network, and connect to it. + * + * @param wifiMgr + * @param scanResult + * @param password Password for secure network or is ignored. + * @return + */ + public static int connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) { + final String security = ConfigSec.getScanResultSecurity(scanResult); + + if (ConfigSec.isOpenNetwork(security)) { + checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept); + } + + WifiConfiguration config = new WifiConfiguration(); + config.SSID = convertToQuotedString(scanResult.SSID); + config.BSSID = scanResult.BSSID; + ConfigSec.setupSecurity(config, security, password); + + int id = -1; + try { + id = wifiMgr.addNetwork(config); + } catch (NullPointerException e) { + Log.e(TAG, "Weird!! Really!! What's wrong??", e); + // Weird!! Really!! + // This exception is reported by user to Android Developer Console(https://market.android.com/publish/Home) + } + if (id == -1) { + return -1; + } + + if (!wifiMgr.saveConfiguration()) { + return -1; + } + + config = getWifiConfiguration(wifiMgr, config, security); + if (config == null) { + return -1; + } + + return connectToConfiguredNetwork(ctx, wifiMgr, config, true); + } + + /** + * Connect to a configured network. + * + * @param wifiManager + * @param config + * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT + * @return + */ + public static int connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) { + final String security = ConfigSec.getWifiConfigurationSecurity(config); + int configId = config.networkId; + int oldPri = config.priority; + // Make it the highest priority. + int newPri = getMaxPriority(wifiMgr) + 1; + if (newPri > MAX_PRIORITY) { + newPri = shiftPriorityAndSave(wifiMgr); + config = getWifiConfiguration(wifiMgr, config, security); + if (config == null) { + return -1; + } + } + + // Set highest priority to this configured network + config.priority = newPri; + int networkId = wifiMgr.updateNetwork(config); + if (networkId == -1) { + return -1; + } + + // Do not disable others + if (!wifiMgr.enableNetwork(networkId, false)) { + config.priority = oldPri; + return -1; + } + + if (!wifiMgr.saveConfiguration()) { + config.priority = oldPri; + return -1; + } + + // We have to retrieve the WifiConfiguration after save. + config = getWifiConfiguration(wifiMgr, config, security); + if (config == null) { + return -1; + } + + // Disable others, but do not save. + // Just to force the WifiManager to connect to it. + if (!wifiMgr.enableNetwork(config.networkId, true)) { + return -1; + } + + final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect(); + if (!connect) { + return -1; + } + + return configId; + } + + private static void sortByPriority(final List configurations) { + java.util.Collections.sort(configurations, new Comparator() { + + public int compare(WifiConfiguration object1, + WifiConfiguration object2) { + return object1.priority - object2.priority; + } + }); + } + + /** + * Ensure no more than numOpenNetworksKept open networks in configuration list. + * + * @param wifiMgr + * @param numOpenNetworksKept + * @return Operation succeed or not. + */ + private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) { + final List configurations = wifiMgr.getConfiguredNetworks(); + sortByPriority(configurations); + + boolean modified = false; + int tempCount = 0; + for (int i = configurations.size() - 1; i >= 0; i--) { + final WifiConfiguration config = configurations.get(i); + if (ConfigSec.isOpenNetwork(ConfigSec.getWifiConfigurationSecurity(config))) { + tempCount++; + if (tempCount >= numOpenNetworksKept) { + modified = true; + wifiMgr.removeNetwork(config.networkId); + } + } + } + if (modified) { + return wifiMgr.saveConfiguration(); + } + + return true; + } + + private static int shiftPriorityAndSave(final WifiManager wifiMgr) { + final List configurations = wifiMgr.getConfiguredNetworks(); + sortByPriority(configurations); + final int size = configurations.size(); + for (int i = 0; i < size; i++) { + final WifiConfiguration config = configurations.get(i); + config.priority = i; + wifiMgr.updateNetwork(config); + } + wifiMgr.saveConfiguration(); + return size; + } + + private static int getMaxPriority(final WifiManager wifiManager) { + final List configurations = wifiManager.getConfiguredNetworks(); + int pri = 0; + for (final WifiConfiguration config : configurations) { + if (config.priority > pri) { + pri = config.priority; + } + } + return pri; + } + + public static void cleanPreviousConfiguration(final WifiManager wifiMgr, final ScanResult hotspot, String hotspotSecurity) { + WifiConfiguration config; + do { + config = getWifiConfiguration(wifiMgr, hotspot, null); + if (config != null) + wifiMgr.removeNetwork(config.networkId); + } while (config != null); + } + + public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final ScanResult hotspot, String hotspotSecurity) { + final String ssid = convertToQuotedString(hotspot.SSID); + if (ssid.length() == 0) { + return null; + } + + final String bssid = hotspot.BSSID; + if (bssid == null) { + return null; + } + + if (hotspotSecurity == null) { + hotspotSecurity = ConfigSec.getScanResultSecurity(hotspot); + } + + final List configurations = wifiMgr.getConfiguredNetworks(); + if (configurations == null) { + return null; + } + + for (final WifiConfiguration config : configurations) { + if (config.SSID == null || !ssid.equals(config.SSID)) { + continue; + } + if (config.BSSID == null || bssid.equals(config.BSSID)) { + final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); + if (hotspotSecurity.equals(configSecurity)) { + return config; + } + } + } + return null; + } + + public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final WifiConfiguration configToFind, String security) { + final String ssid = configToFind.SSID; + if (ssid.length() == 0) { + return null; + } + + final String bssid = configToFind.BSSID; + + + if (security == null) { + security = ConfigSec.getWifiConfigurationSecurity(configToFind); + } + + final List configurations = wifiMgr.getConfiguredNetworks(); + + for (final WifiConfiguration config : configurations) { + if (config.SSID == null || !ssid.equals(config.SSID)) { + continue; + } + if (config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) { + final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); + if (security.equals(configSecurity)) { + return config; + } + } + } + return null; + } + + public static String convertToQuotedString(String string) { if (TextUtils.isEmpty(string)) { return ""; } - + final int lastPos = string.length() - 1; - if(lastPos > 0 && (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) { + if (lastPos > 0 && (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) { return string; } - + return "\"" + string + "\""; } - + } diff --git a/android/routerKeygen/src/main/java/com/hb/views/PinnedSectionListView.java b/android/routerKeygen/src/main/java/com/hb/views/PinnedSectionListView.java index 79c57c9..3780346 100644 --- a/android/routerKeygen/src/main/java/com/hb/views/PinnedSectionListView.java +++ b/android/routerKeygen/src/main/java/com/hb/views/PinnedSectionListView.java @@ -16,12 +16,11 @@ package com.hb.views; -import org.exobel.routerkeygen.BuildConfig; - import android.content.Context; import android.database.DataSetObserver; import android.graphics.Canvas; import android.os.Parcelable; +import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.View; import android.widget.AbsListView; @@ -29,6 +28,8 @@ import android.widget.ListView; import android.widget.SectionIndexer; +import org.exobel.routerkeygen.BuildConfig; + /** * ListView capable to pin views at its top while the rest is still scrolled. */ @@ -36,52 +37,52 @@ public class PinnedSectionListView extends ListView { //-- inner classes - /** List adapter to be implemented for being used with PinnedSectionListView adapter. */ - public static interface PinnedSectionListAdapter extends ListAdapter { - /** This method shall return 'true' if views of given type has to be pinned. */ - boolean isItemViewTypePinned(int viewType); - } - - /** Wrapper class for pinned section view and its position in the list. */ - static class PinnedViewShadow { - public View view; - public int position; - } + /** + * Shadow for being recycled, can be null. + */ + PinnedViewShadow mRecycleShadow; + /** + * shadow instance with a pinned view, can be null. + */ + PinnedViewShadow mPinnedShadow; //-- class fields - - /** Default change observer. */ + /** + * Default change observer. + */ private final DataSetObserver mDataSetObserver = new DataSetObserver() { - @Override public void onChanged() { - destroyPinnedShadow(); - }; - @Override public void onInvalidated() { - destroyPinnedShadow(); - } - }; - - /** Delegating listener, can be null. */ - private OnScrollListener mDelegateOnScrollListener; - - /** Shadow for being recycled, can be null. */ - PinnedViewShadow mRecycleShadow; - - /** shadow instance with a pinned view, can be null. */ - PinnedViewShadow mPinnedShadow; - - /** Pinned view Y-translation. We use it to stick pinned view to the next section. */ - int mTranslateY; + @Override + public void onChanged() { + destroyPinnedShadow(); + } - /** Scroll listener which does the magic */ + @Override + public void onInvalidated() { + destroyPinnedShadow(); + } + }; + /** + * Pinned view Y-translation. We use it to stick pinned view to the next section. + */ + int mTranslateY; + /** + * Delegating listener, can be null. + */ + private OnScrollListener mDelegateOnScrollListener; + /** + * Scroll listener which does the magic + */ private final OnScrollListener mOnScrollListener = new OnScrollListener() { - @Override public void onScrollStateChanged(AbsListView view, int scrollState) { + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { if (mDelegateOnScrollListener != null) { // delegate mDelegateOnScrollListener.onScrollStateChanged(view, scrollState); } } - @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mDelegateOnScrollListener != null) { // delegate mDelegateOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); @@ -155,8 +156,6 @@ static class PinnedViewShadow { } }; - //-- class methods - public PinnedSectionListView(Context context, AttributeSet attrs) { super(context, attrs); initView(); @@ -164,10 +163,14 @@ public PinnedSectionListView(Context context, AttributeSet attrs) { public PinnedSectionListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - initView(); - } + initView(); + } + + //-- class methods - /** Create shadow wrapper with a pinned view for a view at given position */ + /** + * Create shadow wrapper with a pinned view for a view at given position + */ private void createPinnedShadow(int position) { // try to recycle shadow @@ -211,7 +214,9 @@ private void createPinnedShadow(int position) { mPinnedShadow = pinnedShadow; } - /** Destroy shadow wrapper for currently pinned view */ + /** + * Destroy shadow wrapper for currently pinned view + */ private void destroyPinnedShadow() { // store shadow for being recycled later mRecycleShadow = mPinnedShadow; @@ -243,7 +248,7 @@ private int findCurrentSectionPosition(int fromPosition) { } // try slow way by looking through to the next section item above - for (int position=fromPosition; position>=0; position--) { + for (int position = fromPosition; position >= 0; position--) { int viewType = adapter.getItemViewType(position); if (adapter.isItemViewTypePinned(viewType)) return position; } @@ -269,7 +274,8 @@ public void onRestoreInstanceState(Parcelable state) { // restore pinned view after configuration change post(new Runnable() { - @Override public void run() { + @Override + public void run() { ListAdapter adapter = getAdapter(); if (adapter == null) return; // nothing to restore as adapter is still null @@ -294,7 +300,7 @@ public void onRestoreInstanceState(Parcelable state) { @Override public void setAdapter(ListAdapter adapter) { - // assert adapter in debug mode + // assert adapter in debug mode if (BuildConfig.DEBUG && adapter != null) { if (!(adapter instanceof PinnedSectionListAdapter)) throw new IllegalArgumentException("Does your adapter implement PinnedSectionListAdapter?"); @@ -314,7 +320,7 @@ public void setAdapter(ListAdapter adapter) { } @Override - protected void dispatchDraw(Canvas canvas) { + protected void dispatchDraw(@NonNull Canvas canvas) { super.dispatchDraw(canvas); if (mPinnedShadow != null) { @@ -332,4 +338,22 @@ protected void dispatchDraw(Canvas canvas) { canvas.restore(); } } + + /** + * List adapter to be implemented for being used with PinnedSectionListView adapter. + */ + public interface PinnedSectionListAdapter extends ListAdapter { + /** + * This method shall return 'true' if views of given type has to be pinned. + */ + boolean isItemViewTypePinned(int viewType); + } + + /** + * Wrapper class for pinned section view and its position in the list. + */ + static class PinnedViewShadow { + public View view; + public int position; + } } \ No newline at end of file diff --git a/android/routerKeygen/src/main/java/com/robobunny/SeekBarPreference.java b/android/routerKeygen/src/main/java/com/robobunny/SeekBarPreference.java index 87a3e85..bc7c2b6 100644 --- a/android/routerKeygen/src/main/java/com/robobunny/SeekBarPreference.java +++ b/android/routerKeygen/src/main/java/com/robobunny/SeekBarPreference.java @@ -1,7 +1,5 @@ package com.robobunny; -import org.exobel.routerkeygen.R; - import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; @@ -16,208 +14,202 @@ import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; +import org.exobel.routerkeygen.R; + public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { - - private final String TAG = getClass().getName(); - - private static final String ANDROIDNS="http://schemas.android.com/apk/res/android"; - private static final String ROBOBUNNYNS="http://robobunny.com"; - private static final int DEFAULT_VALUE = 50; - - private int mMaxValue = 100; - private int mMinValue = 0; - private int mInterval = 1; - private int mCurrentValue; - private String mUnitsLeft = ""; - private String mUnitsRight = ""; - private SeekBar mSeekBar; - - private TextView mStatusText; - - public SeekBarPreference(Context context, AttributeSet attrs) { - super(context, attrs); - initPreference(context, attrs); - } - - public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - initPreference(context, attrs); - } - - private void initPreference(Context context, AttributeSet attrs) { - setValuesFromXml(attrs); - mSeekBar = new SeekBar(context, attrs); - mSeekBar.setMax(mMaxValue - mMinValue); - mSeekBar.setOnSeekBarChangeListener(this); - } - - private void setValuesFromXml(AttributeSet attrs) { - mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 60); - mMinValue = attrs.getAttributeIntValue(ROBOBUNNYNS, "min", 5); - - mUnitsLeft = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsLeft", ""); - String units = getAttributeStringValue(attrs, ROBOBUNNYNS, "units", ""); - mUnitsRight = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsRight", units); - - try { - String newInterval = attrs.getAttributeValue(ROBOBUNNYNS, "interval"); - if(newInterval != null) - mInterval = Integer.parseInt(newInterval); - } - catch(Exception e) { - Log.e(TAG, "Invalid interval value", e); - } - - } - - private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { - String value = attrs.getAttributeValue(namespace, name); - if(value == null) - value = defaultValue; - - return value; - } - - @Override - protected View onCreateView(ViewGroup parent){ - - RelativeLayout layout = null; - - try { - LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - layout = (RelativeLayout)mInflater.inflate(R.layout.seek_bar_preference, parent, false); - } - catch(Exception e) - { - Log.e(TAG, "Error creating seek bar preference", e); - } - - return layout; - - } - - @Override - public void onBindView(View view) { - super.onBindView(view); - - try - { - // move our seekbar to the new view we've been given - ViewParent oldContainer = mSeekBar.getParent(); - ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer); - - if (oldContainer != newContainer) { - // remove the seekbar from the old view - if (oldContainer != null) { - ((ViewGroup) oldContainer).removeView(mSeekBar); - } - // remove the existing seekbar (there may not be one) and add ours - newContainer.removeAllViews(); - newContainer.addView(mSeekBar, ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - } - } - catch(Exception ex) { - Log.e(TAG, "Error binding view: " + ex.toString()); - } - - updateView(view); - } - - /** - * Update a SeekBarPreference view with our current state - * @param view - */ - protected void updateView(View view) { - - try { - RelativeLayout layout = (RelativeLayout)view; - - mStatusText = (TextView)layout.findViewById(R.id.seekBarPrefValue); - mStatusText.setText(String.valueOf(mCurrentValue)); - mStatusText.setMinimumWidth(30); - - mSeekBar.setProgress(mCurrentValue - mMinValue); - - TextView unitsRight = (TextView)layout.findViewById(R.id.seekBarPrefUnitsRight); - unitsRight.setText(mUnitsRight); - - TextView unitsLeft = (TextView)layout.findViewById(R.id.seekBarPrefUnitsLeft); - unitsLeft.setText(mUnitsLeft); - - } - catch(Exception e) { - Log.e(TAG, "Error updating seek bar preference", e); - } - - } - - - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - } - - - public void onStartTrackingTouch(SeekBar seekBar) {} - - - public void onStopTrackingTouch(SeekBar seekBar) { - int newValue = seekBar.getProgress() + mMinValue; - - if(newValue > mMaxValue) - newValue = mMaxValue; - else if(newValue < mMinValue) - newValue = mMinValue; - else if(mInterval != 1 && newValue % mInterval != 0) - newValue = Math.round(((float)newValue)/mInterval)*mInterval; - - // change rejected, revert to the previous value - if(!callChangeListener(newValue)){ - seekBar.setProgress(mCurrentValue - mMinValue); - return; - } - - // change accepted, store it - mCurrentValue = newValue; - mStatusText.setText(String.valueOf(newValue)); - persistInt(newValue); - notifyChanged(); - } - - - @Override - protected Object onGetDefaultValue(TypedArray ta, int index){ - - int defaultValue = ta.getInt(index, DEFAULT_VALUE); - return defaultValue; - - } - - @Override - protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { - - if(restoreValue) { - mCurrentValue = getPersistedInt(mCurrentValue); - } - else { - int temp = 0; - try { - temp = (Integer)defaultValue; - } - catch(Exception ex) { - Log.e(TAG, "Invalid default value: " + defaultValue.toString()); - } - - persistInt(temp); - mCurrentValue = temp; - } - - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - mSeekBar.setEnabled(enabled); - } - + + private static final String ANDROIDNS = "http://schemas.android.com/apk/res/android"; + private static final String ROBOBUNNYNS = "http://robobunny.com"; + private static final int DEFAULT_VALUE = 50; + private final String TAG = getClass().getName(); + private int mMaxValue = 100; + private int mMinValue = 0; + private int mInterval = 1; + private int mCurrentValue; + private String mUnitsLeft = ""; + private String mUnitsRight = ""; + private SeekBar mSeekBar; + + private TextView mStatusText; + + public SeekBarPreference(Context context, AttributeSet attrs) { + super(context, attrs); + initPreference(context, attrs); + } + + public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + initPreference(context, attrs); + } + + private void initPreference(Context context, AttributeSet attrs) { + setValuesFromXml(attrs); + mSeekBar = new SeekBar(context, attrs); + mSeekBar.setMax(mMaxValue - mMinValue); + mSeekBar.setOnSeekBarChangeListener(this); + } + + private void setValuesFromXml(AttributeSet attrs) { + mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 60); + mMinValue = attrs.getAttributeIntValue(ROBOBUNNYNS, "min", 5); + + mUnitsLeft = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsLeft", ""); + String units = getAttributeStringValue(attrs, ROBOBUNNYNS, "units", ""); + mUnitsRight = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsRight", units); + + try { + String newInterval = attrs.getAttributeValue(ROBOBUNNYNS, "interval"); + if (newInterval != null) + mInterval = Integer.parseInt(newInterval); + } catch (Exception e) { + Log.e(TAG, "Invalid interval value", e); + } + + } + + private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { + String value = attrs.getAttributeValue(namespace, name); + if (value == null) + value = defaultValue; + + return value; + } + + @Override + protected View onCreateView(ViewGroup parent) { + + RelativeLayout layout = null; + + try { + LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + layout = (RelativeLayout) mInflater.inflate(R.layout.seek_bar_preference, parent, false); + } catch (Exception e) { + Log.e(TAG, "Error creating seek bar preference", e); + } + + return layout; + + } + + @Override + public void onBindView(View view) { + super.onBindView(view); + + try { + // move our seekbar to the new view we've been given + ViewParent oldContainer = mSeekBar.getParent(); + ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer); + + if (oldContainer != newContainer) { + // remove the seekbar from the old view + if (oldContainer != null) { + ((ViewGroup) oldContainer).removeView(mSeekBar); + } + // remove the existing seekbar (there may not be one) and add ours + newContainer.removeAllViews(); + newContainer.addView(mSeekBar, ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } + } catch (Exception ex) { + Log.e(TAG, "Error binding view: " + ex.toString()); + } + + updateView(view); + } + + /** + * Update a SeekBarPreference view with our current state + * + * @param view + */ + protected void updateView(View view) { + + try { + RelativeLayout layout = (RelativeLayout) view; + + mStatusText = (TextView) layout.findViewById(R.id.seekBarPrefValue); + mStatusText.setText(String.valueOf(mCurrentValue)); + mStatusText.setMinimumWidth(30); + + mSeekBar.setProgress(mCurrentValue - mMinValue); + + TextView unitsRight = (TextView) layout.findViewById(R.id.seekBarPrefUnitsRight); + unitsRight.setText(mUnitsRight); + + TextView unitsLeft = (TextView) layout.findViewById(R.id.seekBarPrefUnitsLeft); + unitsLeft.setText(mUnitsLeft); + + } catch (Exception e) { + Log.e(TAG, "Error updating seek bar preference", e); + } + + } + + + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + } + + + public void onStartTrackingTouch(SeekBar seekBar) { + } + + + public void onStopTrackingTouch(SeekBar seekBar) { + int newValue = seekBar.getProgress() + mMinValue; + + if (newValue > mMaxValue) + newValue = mMaxValue; + else if (newValue < mMinValue) + newValue = mMinValue; + else if (mInterval != 1 && newValue % mInterval != 0) + newValue = Math.round(((float) newValue) / mInterval) * mInterval; + + // change rejected, revert to the previous value + if (!callChangeListener(newValue)) { + seekBar.setProgress(mCurrentValue - mMinValue); + return; + } + + // change accepted, store it + mCurrentValue = newValue; + mStatusText.setText(String.valueOf(newValue)); + persistInt(newValue); + notifyChanged(); + } + + + @Override + protected Object onGetDefaultValue(TypedArray ta, int index) { + + int defaultValue = ta.getInt(index, DEFAULT_VALUE); + return defaultValue; + + } + + @Override + protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { + + if (restoreValue) { + mCurrentValue = getPersistedInt(mCurrentValue); + } else { + int temp = 0; + try { + temp = (Integer) defaultValue; + } catch (Exception ex) { + Log.e(TAG, "Invalid default value: " + defaultValue.toString()); + } + + persistInt(temp); + mCurrentValue = temp; + } + + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + mSeekBar.setEnabled(enabled); + } + } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/Constants.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/Constants.java index 1c6bbe7..6fbbd93 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/Constants.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/Constants.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library; import org.exobel.routerkeygen.R; @@ -30,7 +32,7 @@ public class Constants { * You shouldn't modify this value. * You can use changeLogResourceId attribute in ChangeLogListView **/ - public static final int mChangeLogFileResourceId= R.raw.changelog; + public static final int mChangeLogFileResourceId = R.raw.changelog; /** * Layout resource id for changelog item rows. @@ -38,7 +40,7 @@ public class Constants { * You shouldn't modify this value. * You can use rowLayoutId attribute in ChangeLogListView **/ - public static final int mRowLayoutId=R.layout.changelogrow_layout; + public static final int mRowLayoutId = R.layout.changelogrow_layout; /** * Layout resource id for changelog header rows. @@ -46,7 +48,7 @@ public class Constants { * You shouldn't modify this value. * You can use rowHeaderLayoutId attribute in ChangeLogListView **/ - public static final int mRowHeaderLayoutId=R.layout.changelogrowheader_layout; + public static final int mRowHeaderLayoutId = R.layout.changelogrowheader_layout; /** @@ -55,5 +57,5 @@ public class Constants { * You shouldn't modify this value. * You can use changelog_header_version in strings.xml */ - public static final int mStringVersionHeader= R.string.changelog_header_version; + public static final int mStringVersionHeader = R.string.changelog_header_version; } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLog.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLog.java index a12240c..f41e6ac 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLog.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLog.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.internal; import java.util.LinkedList; @@ -36,8 +38,8 @@ public class ChangeLog { //----------------------------------------------------------------------- - public ChangeLog(){ - rows=new LinkedList(); + public ChangeLog() { + rows = new LinkedList(); } /** @@ -45,9 +47,9 @@ public ChangeLog(){ * * @param row */ - public void addRow(ChangeLogRow row){ - if (row!=null){ - if (rows==null) rows=new LinkedList(); + public void addRow(ChangeLogRow row) { + if (row != null) { + if (rows == null) rows = new LinkedList(); rows.add(row); } } @@ -55,23 +57,23 @@ public void addRow(ChangeLogRow row){ /** * Clear all rows */ - public void clearAllRows(){ - rows=new LinkedList(); + public void clearAllRows() { + rows = new LinkedList(); } @Override public String toString() { - StringBuilder sb=new StringBuilder(); - sb.append("bulletedList="+bulletedList); + StringBuilder sb = new StringBuilder(); + sb.append("bulletedList=" + bulletedList); sb.append("\n"); - if (rows!=null){ - for (ChangeLogRow row:rows){ + if (rows != null) { + for (ChangeLogRow row : rows) { sb.append("row=["); sb.append(row.toString()); sb.append("]\n"); } - }else{ + } else { sb.append("rows:none"); } return sb.toString(); @@ -96,6 +98,4 @@ public void setRows(LinkedList rows) { } - - } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogAdapter.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogAdapter.java index c99b643..0befd03 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogAdapter.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogAdapter.java @@ -1,26 +1,22 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.internal; -import it.gmariotti.changelibs.library.Constants; - -import java.util.List; - -import org.exobel.routerkeygen.R; - import android.content.Context; import android.text.Html; import android.view.LayoutInflater; @@ -29,6 +25,12 @@ import android.widget.ArrayAdapter; import android.widget.TextView; +import org.exobel.routerkeygen.R; + +import java.util.List; + +import it.gmariotti.changelibs.library.Constants; + /** * Adapter for ChangeLog model * @@ -38,19 +40,17 @@ public class ChangeLogAdapter extends ArrayAdapter { protected static final int TYPE_ROW = 0; protected static final int TYPE_HEADER = 1; - + private final Context mContext; private int mRowLayoutId = Constants.mRowLayoutId; private int mRowHeaderLayoutId = Constants.mRowHeaderLayoutId; private int mStringVersionHeader = Constants.mStringVersionHeader; - private final Context mContext; - //private boolean mChangeLogRowClickable = false; public ChangeLogAdapter(Context context, List items) { super(context, 0, items); - mContext=context; + mContext = context; } @Override @@ -67,7 +67,7 @@ public View getView(int position, View convertView, ViewGroup parent) { ChangeLogRow item = getItem(position); View view = convertView; int viewType = this.getItemViewType(position); - // LayoutInflater mInflater = mContext.getLayoutInflater(); + // LayoutInflater mInflater = mContext.getLayoutInflater(); LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); switch (viewType) { @@ -85,23 +85,23 @@ public View getView(int position, View convertView, ViewGroup parent) { if (view == null || viewHolderHeader == null) { int layout = mRowHeaderLayoutId; - view = mInflater.inflate(layout, parent,false); + view = mInflater.inflate(layout, parent, false); //VersionName text TextView textHeader = (TextView) view.findViewById(R.id.chg_headerVersion); //ChangeData text - TextView textDate = (TextView) view.findViewById(R.id.chg_headerDate); - viewHolderHeader= new ViewHolderHeader(textHeader,textDate); + TextView textDate = (TextView) view.findViewById(R.id.chg_headerDate); + viewHolderHeader = new ViewHolderHeader(textHeader, textDate); view.setTag(viewHolderHeader); } if (item != null && viewHolderHeader != null) { - if (viewHolderHeader.version != null){ - StringBuilder sb=new StringBuilder(); + if (viewHolderHeader.version != null) { + StringBuilder sb = new StringBuilder(); //String resource for Version - String versionHeaderString=getContext().getString(mStringVersionHeader); - if (versionHeaderString!=null) + String versionHeaderString = getContext().getString(mStringVersionHeader); + if (versionHeaderString != null) sb.append(versionHeaderString); //VersionName text sb.append(item.versionName); @@ -110,13 +110,13 @@ public View getView(int position, View convertView, ViewGroup parent) { } //ChangeData text - if (viewHolderHeader.date !=null){ + if (viewHolderHeader.date != null) { //Check if exists - if (item.changeDate!=null){ + if (item.changeDate != null) { viewHolderHeader.date.setText(item.changeDate); viewHolderHeader.date.setVisibility(View.VISIBLE); - }else{ + } else { //If item hasn't changedata, hide TextView viewHolderHeader.date.setText(""); viewHolderHeader.date.setVisibility(View.GONE); @@ -143,20 +143,20 @@ public View getView(int position, View convertView, ViewGroup parent) { TextView textText = (TextView) view.findViewById(R.id.chg_text); TextView bulletText = (TextView) view.findViewById(R.id.chg_textbullet); - viewHolder = new ViewHolderRow(textText,bulletText); + viewHolder = new ViewHolderRow(textText, bulletText); view.setTag(viewHolder); } if (item != null && viewHolder != null) { - if (viewHolder.text != null){ + if (viewHolder.text != null) { viewHolder.text.setText(Html.fromHtml(item.getChangeText())); } - if (viewHolder.bulletText!=null){ - if (item.isBulletedList()){ + if (viewHolder.bulletText != null) { + if (item.isBulletedList()) { viewHolder.bulletText.setVisibility(View.VISIBLE); - }else{ + } else { viewHolder.bulletText.setVisibility(View.GONE); } } @@ -186,31 +186,6 @@ public int getItemViewType(int position) { // View Holder //----------------------------------------------------------------------------------- - static class ViewHolderHeader { - TextView version; - TextView date; - - public ViewHolderHeader(TextView version, TextView date) { - this.version = version; - this.date = date; - } - } - - static class ViewHolderRow { - TextView text; - TextView bulletText; - - public ViewHolderRow( TextView text,TextView bulletText) { - this.text = text; - this.bulletText=bulletText; - } - } - - //----------------------------------------------------------------------------------- - // Getter and Setter - //----------------------------------------------------------------------------------- - - public int getmRowLayoutId() { return mRowLayoutId; } @@ -219,6 +194,10 @@ public void setmRowLayoutId(int mRowLayoutId) { this.mRowLayoutId = mRowLayoutId; } + //----------------------------------------------------------------------------------- + // Getter and Setter + //----------------------------------------------------------------------------------- + public int getmRowHeaderLayoutId() { return mRowHeaderLayoutId; } @@ -234,4 +213,24 @@ public int getmStringVersionHeader() { public void setmStringVersionHeader(int mStringVersionHeader) { this.mStringVersionHeader = mStringVersionHeader; } + + static class ViewHolderHeader { + TextView version; + TextView date; + + public ViewHolderHeader(TextView version, TextView date) { + this.version = version; + this.date = date; + } + } + + static class ViewHolderRow { + TextView text; + TextView bulletText; + + public ViewHolderRow(TextView text, TextView bulletText) { + this.text = text; + this.bulletText = bulletText; + } + } } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogException.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogException.java index 5add96e..24fb47a 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogException.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogException.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.internal; /** @@ -21,7 +23,7 @@ * @author Gabriele Mariotti (gabri.mariotti@gmail.com) */ @SuppressWarnings("serial") -public class ChangeLogException extends Exception{ +public class ChangeLogException extends Exception { public ChangeLogException(String s) { diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRow.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRow.java index a5d596c..9744b8b 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRow.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRow.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.internal; /** @@ -22,40 +24,40 @@ */ public class ChangeLogRow { - /** - * Flag to indicate a header row - */ - protected boolean header; + /** + * Flag to indicate a header row + */ + protected boolean header; - /** - * This corresponds to the android:versionName attribute in your manifest file. It is a required data - */ - protected String versionName; + /** + * This corresponds to the android:versionName attribute in your manifest file. It is a required data + */ + protected String versionName; - /** - * Change data. It is optional - */ - protected String changeDate; + /** + * Change data. It is optional + */ + protected String changeDate; - //------------------------------------------------------------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------------- - /** - * Use a bulleted list. It overrides general flag. It is optional - */ - private boolean bulletedList; + /** + * Use a bulleted list. It overrides general flag. It is optional + */ + private boolean bulletedList; - /** - * Special marker in change text. It is optional - * TODO: not yet implemented - */ - private String changeTextTitle; + /** + * Special marker in change text. It is optional + * TODO: not yet implemented + */ + private String changeTextTitle; - /** - * Contains the actual text that will be displayed in your change log. It is required - */ - private String changeText; + /** + * Contains the actual text that will be displayed in your change log. It is required + */ + private String changeText; - //------------------------------------------------------------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------------- /** * Replace special tags [b] [i] @@ -63,22 +65,22 @@ public class ChangeLogRow { * @param changeLogText */ public void parseChangeText(String changeLogText) { - if (changeLogText!=null){ - changeLogText=changeLogText.replaceAll("\\[", "<").replaceAll("\\]",">"); + if (changeLogText != null) { + changeLogText = changeLogText.replaceAll("\\[", "<").replaceAll("\\]", ">"); } setChangeText(changeLogText); } @Override public String toString() { - StringBuilder sb=new StringBuilder(); - sb.append("header="+header); + StringBuilder sb = new StringBuilder(); + sb.append("header=" + header); sb.append(","); - sb.append("versionName="+versionName); + sb.append("versionName=" + versionName); sb.append(","); - sb.append("bulletedList="+bulletedList); + sb.append("bulletedList=" + bulletedList); sb.append(","); - sb.append("changeText="+changeText); + sb.append("changeText=" + changeText); //sb.append(","); //sb.append("changeTextTitle="+changeTextTitle); return sb.toString(); @@ -87,7 +89,7 @@ public String toString() { //------------------------------------------------------------------------------------------------------------------- - public boolean isHeader() { + public boolean isHeader() { return header; } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRowHeader.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRowHeader.java index 903e30a..7c3c4c5 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRowHeader.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/internal/ChangeLogRowHeader.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.internal; /** @@ -20,13 +22,13 @@ * * @author Gabriele Mariotti (gabri.mariotti@gmail.com) */ -public class ChangeLogRowHeader extends ChangeLogRow{ +public class ChangeLogRowHeader extends ChangeLogRow { //----------------------------------------------------------------------- // Constructors //----------------------------------------------------------------------- - public ChangeLogRowHeader(){ + public ChangeLogRowHeader() { super(); setHeader(true); setBulletedList(false); @@ -37,12 +39,12 @@ public ChangeLogRowHeader(){ @Override public String toString() { - StringBuilder sb=new StringBuilder(); - sb.append("header="+super.header); + StringBuilder sb = new StringBuilder(); + sb.append("header=" + super.header); sb.append(","); - sb.append("versionName="+versionName); + sb.append("versionName=" + versionName); sb.append(","); - sb.append("changeDate="+changeDate); + sb.append("changeDate=" + changeDate); return sb.toString(); } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/BaseParser.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/BaseParser.java index 81cc7d3..bcfab9f 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/BaseParser.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/BaseParser.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.parser; import android.content.Context; @@ -46,8 +48,8 @@ public abstract class BaseParser { * * @param context current Context */ - public BaseParser(Context context){ - this.mContext=context; + public BaseParser(Context context) { + this.mContext = context; } //-------------------------------------------------------------------------------- diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/XmlParser.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/XmlParser.java index 7dcdc1a..effeb7b 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/XmlParser.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/parser/XmlParser.java @@ -1,18 +1,20 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.parser; import android.content.Context; @@ -65,23 +67,23 @@ */ public class XmlParser extends BaseParser { - /** TAG for logging **/ - private static String TAG="XmlParser"; - private int mChangeLogFileResourceId= Constants.mChangeLogFileResourceId; + private static final String TAG_CHANGELOG = "changelog"; + private static final String TAG_CHANGELOGVERSION = "changelogversion"; //-------------------------------------------------------------------------------- //TAGs and ATTRIBUTEs in xml file //-------------------------------------------------------------------------------- - - private static final String TAG_CHANGELOG="changelog"; - private static final String TAG_CHANGELOGVERSION="changelogversion"; - private static final String TAG_CHANGELOGTEXT="changelogtext"; - - private static final String ATTRIBUTE_BULLETEDLIST="bulletedList"; - private static final String ATTRIBUTE_VERSIONNAME="versionName"; - private static final String ATTRIBUTE_CHANGEDATE="changeDate"; + private static final String TAG_CHANGELOGTEXT = "changelogtext"; + private static final String ATTRIBUTE_BULLETEDLIST = "bulletedList"; + private static final String ATTRIBUTE_VERSIONNAME = "versionName"; + private static final String ATTRIBUTE_CHANGEDATE = "changeDate"; //private static final String ATTRIBUTE_CHANGETEXT="changeText"; - private static final String ATTRIBUTE_CHANGETEXTTITLE= "changeTextTitle"; + private static final String ATTRIBUTE_CHANGETEXTTITLE = "changeTextTitle"; + /** + * TAG for logging * + */ + private static String TAG = "XmlParser"; + private int mChangeLogFileResourceId = Constants.mChangeLogFileResourceId; //-------------------------------------------------------------------------------- //Constructors @@ -92,7 +94,7 @@ public class XmlParser extends BaseParser { * * @param context current Context */ - public XmlParser(Context context){ + public XmlParser(Context context) { super(context); } @@ -104,9 +106,9 @@ public XmlParser(Context context){ * @param context current Context * @param changeLogFileResourceId reference for a custom xml file */ - public XmlParser(Context context,int changeLogFileResourceId){ + public XmlParser(Context context, int changeLogFileResourceId) { super(context); - this.mChangeLogFileResourceId=changeLogFileResourceId; + this.mChangeLogFileResourceId = changeLogFileResourceId; } //-------------------------------------------------------------------------------- @@ -119,13 +121,13 @@ public XmlParser(Context context,int changeLogFileResourceId){ * @return {@link ChangeLog} obj with all data */ @Override - public ChangeLog readChangeLogFile() throws Exception{ + public ChangeLog readChangeLogFile() throws Exception { - ChangeLog chg=null; + ChangeLog chg = null; try { InputStream is = mContext.getResources().openRawResource(mChangeLogFileResourceId); - if (is!=null){ + if (is != null) { // Create a new XML Pull Parser. XmlPullParser parser = Xml.newPullParser(); @@ -134,26 +136,26 @@ public ChangeLog readChangeLogFile() throws Exception{ parser.nextTag(); // Create changelog obj that will contain all data - chg=new ChangeLog(); + chg = new ChangeLog(); // Parse file readChangeLogNode(parser, chg); // Close inputstream is.close(); - }else{ - Log.d(TAG,"Changelog.xml not found"); + } else { + Log.d(TAG, "Changelog.xml not found"); throw new ChangeLogException("Changelog.xml not found"); } } catch (XmlPullParserException xpe) { - Log.d(TAG,"XmlPullParseException while parsing changelog file",xpe); - throw xpe; - } catch (IOException ioe){ - Log.d(TAG,"Error i/o with changelog.xml",ioe); + Log.d(TAG, "XmlPullParseException while parsing changelog file", xpe); + throw xpe; + } catch (IOException ioe) { + Log.d(TAG, "Error i/o with changelog.xml", ioe); throw ioe; } - if (chg!=null) - Log.d(TAG,"Process ended. ChangeLog:"+chg.toString()); + if (chg != null) + Log.d(TAG, "Process ended. ChangeLog:" + chg.toString()); return chg; } @@ -165,22 +167,22 @@ public ChangeLog readChangeLogFile() throws Exception{ * @param parser * @param changeLog */ - protected void readChangeLogNode(XmlPullParser parser,ChangeLog changeLog) throws Exception{ + protected void readChangeLogNode(XmlPullParser parser, ChangeLog changeLog) throws Exception { - if (parser==null || changeLog==null) return; + if (parser == null || changeLog == null) return; // Parse changelog node - parser.require(XmlPullParser.START_TAG, null,TAG_CHANGELOG); - Log.d(TAG,"Processing main tag="); + parser.require(XmlPullParser.START_TAG, null, TAG_CHANGELOG); + Log.d(TAG, "Processing main tag="); // Read attributes String bulletedList = parser.getAttributeValue(null, ATTRIBUTE_BULLETEDLIST); - if (bulletedList==null || bulletedList.equals("true")){ + if (bulletedList == null || bulletedList.equals("true")) { changeLog.setBulletedList(true); - super.bulletedList=true; - }else{ + super.bulletedList = true; + } else { changeLog.setBulletedList(false); - super.bulletedList=false; + super.bulletedList = false; } //Parse nested nodes @@ -190,7 +192,7 @@ protected void readChangeLogNode(XmlPullParser parser,ChangeLog changeLog) throw } String tag = parser.getName(); - Log.d(TAG,"Processing tag="+tag); + Log.d(TAG, "Processing tag=" + tag); if (tag.equals(TAG_CHANGELOGVERSION)) { readChangeLogVersionNode(parser, changeLog); @@ -205,24 +207,24 @@ protected void readChangeLogNode(XmlPullParser parser,ChangeLog changeLog) throw * @param changeLog * @throws Exception */ - protected void readChangeLogVersionNode(XmlPullParser parser, ChangeLog changeLog) throws Exception{ + protected void readChangeLogVersionNode(XmlPullParser parser, ChangeLog changeLog) throws Exception { - if (parser==null) return; + if (parser == null) return; - parser.require(XmlPullParser.START_TAG, null,TAG_CHANGELOGVERSION); + parser.require(XmlPullParser.START_TAG, null, TAG_CHANGELOGVERSION); // Read attributes String versionName = parser.getAttributeValue(null, ATTRIBUTE_VERSIONNAME); - String changeDate= parser.getAttributeValue(null, ATTRIBUTE_CHANGEDATE); - if (versionName==null) + String changeDate = parser.getAttributeValue(null, ATTRIBUTE_CHANGEDATE); + if (versionName == null) throw new ChangeLogException("VersionName required in changeLogVersion node"); - ChangeLogRowHeader row=new ChangeLogRowHeader(); + ChangeLogRowHeader row = new ChangeLogRowHeader(); row.setVersionName(versionName); row.setChangeDate(changeDate); changeLog.addRow(row); - Log.d(TAG,"Added rowHeader:"+row.toString()); + Log.d(TAG, "Added rowHeader:" + row.toString()); // Parse nested nodes while (parser.next() != XmlPullParser.END_TAG) { @@ -230,10 +232,10 @@ protected void readChangeLogVersionNode(XmlPullParser parser, ChangeLog changeLo continue; } String tag = parser.getName(); - Log.d(TAG,"Processing tag="+tag); + Log.d(TAG, "Processing tag=" + tag); - if (tag.equals(TAG_CHANGELOGTEXT)){ - readChangeLogRowNode(parser, changeLog,versionName); + if (tag.equals(TAG_CHANGELOGTEXT)) { + readChangeLogRowNode(parser, changeLog, versionName); } } } @@ -245,47 +247,47 @@ protected void readChangeLogVersionNode(XmlPullParser parser, ChangeLog changeLo * @param changeLog * @throws Exception */ - private void readChangeLogRowNode(XmlPullParser parser, ChangeLog changeLog,String versionName) throws Exception{ + private void readChangeLogRowNode(XmlPullParser parser, ChangeLog changeLog, String versionName) throws Exception { - if (parser==null) return; + if (parser == null) return; - parser.require(XmlPullParser.START_TAG, null,TAG_CHANGELOGTEXT); + parser.require(XmlPullParser.START_TAG, null, TAG_CHANGELOGTEXT); String tag = parser.getName(); - if (tag.equals(TAG_CHANGELOGTEXT)){ - ChangeLogRow row=new ChangeLogRow(); + if (tag.equals(TAG_CHANGELOGTEXT)) { + ChangeLogRow row = new ChangeLogRow(); row.setVersionName(versionName); // Read attributes - String changeLogTextTitle=parser.getAttributeValue(null,ATTRIBUTE_CHANGETEXTTITLE); - if (changeLogTextTitle!=null) + String changeLogTextTitle = parser.getAttributeValue(null, ATTRIBUTE_CHANGETEXTTITLE); + if (changeLogTextTitle != null) row.setChangeTextTitle(changeLogTextTitle); // It is possible to force bulleted List String bulletedList = parser.getAttributeValue(null, ATTRIBUTE_BULLETEDLIST); - if (bulletedList!=null){ - if (bulletedList.equals("true")){ + if (bulletedList != null) { + if (bulletedList.equals("true")) { row.setBulletedList(true); - }else{ + } else { row.setBulletedList(false); } - }else{ + } else { row.setBulletedList(super.bulletedList); } // Read text if (parser.next() == XmlPullParser.TEXT) { - String changeLogText=parser.getText(); - if (changeLogText==null) + String changeLogText = parser.getText(); + if (changeLogText == null) throw new ChangeLogException("ChangeLogText required in changeLogText node"); row.parseChangeText(changeLogText); parser.nextTag(); } changeLog.addRow(row); - Log.d(TAG,"Added row:"+row.toString()); + Log.d(TAG, "Added row:" + row.toString()); } - parser.require(XmlPullParser.END_TAG, null,TAG_CHANGELOGTEXT); + parser.require(XmlPullParser.END_TAG, null, TAG_CHANGELOGTEXT); } } diff --git a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/view/ChangeLogListView.java b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/view/ChangeLogListView.java index 26fd255..33836f8 100644 --- a/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/view/ChangeLogListView.java +++ b/android/routerKeygen/src/main/java/it/gmariotti/changelibs/library/view/ChangeLogListView.java @@ -1,28 +1,22 @@ -/******************************************************************************* +/** + * **************************************************************************** * Copyright (c) 2013 Gabriele Mariotti. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ******************************************************************************/ + * **************************************************************************** + */ package it.gmariotti.changelibs.library.view; -import it.gmariotti.changelibs.library.Constants; -import it.gmariotti.changelibs.library.internal.ChangeLog; -import it.gmariotti.changelibs.library.internal.ChangeLogAdapter; -import it.gmariotti.changelibs.library.internal.ChangeLogRow; -import it.gmariotti.changelibs.library.parser.XmlParser; - -import org.exobel.routerkeygen.R; - import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; @@ -34,182 +28,188 @@ import android.widget.AdapterView; import android.widget.ListView; +import org.exobel.routerkeygen.R; + +import it.gmariotti.changelibs.library.Constants; +import it.gmariotti.changelibs.library.internal.ChangeLog; +import it.gmariotti.changelibs.library.internal.ChangeLogAdapter; +import it.gmariotti.changelibs.library.internal.ChangeLogRow; +import it.gmariotti.changelibs.library.parser.XmlParser; + /** * ListView for ChangeLog - * - * + * + * * @author Gabriele Mariotti (gabri.mariotti@gmail.com) */ public class ChangeLogListView extends ListView implements - AdapterView.OnItemClickListener { - - // -------------------------------------------------------------------------- - // Custom Attrs - // -------------------------------------------------------------------------- - protected int mRowLayoutId = Constants.mRowLayoutId; - protected int mRowHeaderLayoutId = Constants.mRowHeaderLayoutId; - protected int mChangeLogFileResourceId = Constants.mChangeLogFileResourceId; - - // -------------------------------------------------------------------------- - protected static String TAG = "ChangeLogListView"; - // Adapter - protected ChangeLogAdapter mAdapter; - - // -------------------------------------------------------------------------- - // Constructors - // -------------------------------------------------------------------------- - - public ChangeLogListView(Context context) { - super(context); - init(null, 0); - } - - public ChangeLogListView(Context context, AttributeSet attrs) { - super(context, attrs); - init(attrs, 0); - } - - public ChangeLogListView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(attrs, defStyle); - } - - // -------------------------------------------------------------------------- - // Init - // -------------------------------------------------------------------------- - - /** - * Initialize - * - * @param attrs - * @param defStyle - */ - protected void init(AttributeSet attrs, int defStyle) { - // Init attrs - initAttrs(attrs, defStyle); - // Init adapter - initAdapter(); - - // Set divider to 0dp - setDividerHeight(0); - } - - /** - * Init custom attrs. - * - * @param attrs - * @param defStyle - */ - protected void initAttrs(AttributeSet attrs, int defStyle) { - TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, - R.styleable.ChangeLogListView, defStyle, defStyle); - - try { - // Layout for rows and header - mRowLayoutId = a.getResourceId( - R.styleable.ChangeLogListView_rowLayoutId, mRowLayoutId); - mRowHeaderLayoutId = a.getResourceId( - R.styleable.ChangeLogListView_rowHeaderLayoutId, - mRowHeaderLayoutId); - - // Changelog.xml file - mChangeLogFileResourceId = a.getResourceId( - R.styleable.ChangeLogListView_changeLogFileResourceId, - mChangeLogFileResourceId); - - // String which is used in header row for Version - // mStringVersionHeader= - // a.getResourceId(R.styleable.ChangeLogListView_StringVersionHeader,mStringVersionHeader); - - } finally { - a.recycle(); - } - } - - /** - * Init adapter - */ - protected void initAdapter() { - - try { - // Read and parse changelog.xml - XmlParser parse = new XmlParser(getContext(), - mChangeLogFileResourceId); - // ChangeLog chg=parse.readChangeLogFile(); - ChangeLog chg = new ChangeLog(); - // Create adapter and set custom attrs - mAdapter = new ChangeLogAdapter(getContext(), chg.getRows()); - mAdapter.setmRowLayoutId(mRowLayoutId); - mAdapter.setmRowHeaderLayoutId(mRowHeaderLayoutId); - - // Parse in a separate Thread to avoid UI block with large files - new ParseAsyncTask(mAdapter, parse).execute(); - setAdapter(mAdapter); - } catch (Exception e) { - Log.e(TAG, - getResources().getString( - R.string.changelog_internal_error_parsing), e); - } - - } - - /** - * Async Task to parse xml file in a separate thread - * - */ - protected class ParseAsyncTask extends AsyncTask { - - private ChangeLogAdapter mAdapter; - private XmlParser mParse; - - public ParseAsyncTask(ChangeLogAdapter adapter, XmlParser parse) { - mAdapter = adapter; - mParse = parse; - } - - @Override - protected ChangeLog doInBackground(Void... params) { - - try { - if (mParse != null) { - ChangeLog chg = mParse.readChangeLogFile(); - return chg; - } - } catch (Exception e) { - Log.e(TAG, - getResources().getString( - R.string.changelog_internal_error_parsing), e); - } - return null; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - protected void onPostExecute(ChangeLog chg) { - - // Notify data changed - if (chg != null) { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { - mAdapter.addAll(chg.getRows()); - } else { - for (ChangeLogRow c : chg.getRows()) - mAdapter.add(c); - } - mAdapter.notifyDataSetChanged(); - } - } - } - - /** - * Sets the list's adapter, enforces the use of only a ChangeLogAdapter - */ - public void setAdapter(ChangeLogAdapter adapter) { - super.setAdapter(adapter); - } - - @Override - public void onItemClick(AdapterView parent, View view, int position, - long id) { - // TODO - } + AdapterView.OnItemClickListener { + + // -------------------------------------------------------------------------- + protected static String TAG = "ChangeLogListView"; + // -------------------------------------------------------------------------- + // Custom Attrs + // -------------------------------------------------------------------------- + protected int mRowLayoutId = Constants.mRowLayoutId; + protected int mRowHeaderLayoutId = Constants.mRowHeaderLayoutId; + protected int mChangeLogFileResourceId = Constants.mChangeLogFileResourceId; + // Adapter + protected ChangeLogAdapter mAdapter; + + // -------------------------------------------------------------------------- + // Constructors + // -------------------------------------------------------------------------- + + public ChangeLogListView(Context context) { + super(context); + init(null, 0); + } + + public ChangeLogListView(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, 0); + } + + public ChangeLogListView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(attrs, defStyle); + } + + // -------------------------------------------------------------------------- + // Init + // -------------------------------------------------------------------------- + + /** + * Initialize + * + * @param attrs + * @param defStyle + */ + protected void init(AttributeSet attrs, int defStyle) { + // Init attrs + initAttrs(attrs, defStyle); + // Init adapter + initAdapter(); + + // Set divider to 0dp + setDividerHeight(0); + } + + /** + * Init custom attrs. + * + * @param attrs + * @param defStyle + */ + protected void initAttrs(AttributeSet attrs, int defStyle) { + TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, + R.styleable.ChangeLogListView, defStyle, defStyle); + + try { + // Layout for rows and header + mRowLayoutId = a.getResourceId( + R.styleable.ChangeLogListView_rowLayoutId, mRowLayoutId); + mRowHeaderLayoutId = a.getResourceId( + R.styleable.ChangeLogListView_rowHeaderLayoutId, + mRowHeaderLayoutId); + + // Changelog.xml file + mChangeLogFileResourceId = a.getResourceId( + R.styleable.ChangeLogListView_changeLogFileResourceId, + mChangeLogFileResourceId); + + // String which is used in header row for Version + // mStringVersionHeader= + // a.getResourceId(R.styleable.ChangeLogListView_StringVersionHeader,mStringVersionHeader); + + } finally { + a.recycle(); + } + } + + /** + * Init adapter + */ + protected void initAdapter() { + + try { + // Read and parse changelog.xml + XmlParser parse = new XmlParser(getContext(), + mChangeLogFileResourceId); + // ChangeLog chg=parse.readChangeLogFile(); + ChangeLog chg = new ChangeLog(); + // Create adapter and set custom attrs + mAdapter = new ChangeLogAdapter(getContext(), chg.getRows()); + mAdapter.setmRowLayoutId(mRowLayoutId); + mAdapter.setmRowHeaderLayoutId(mRowHeaderLayoutId); + + // Parse in a separate Thread to avoid UI block with large files + new ParseAsyncTask(mAdapter, parse).execute(); + setAdapter(mAdapter); + } catch (Exception e) { + Log.e(TAG, + getResources().getString( + R.string.changelog_internal_error_parsing), e); + } + + } + + /** + * Sets the list's adapter, enforces the use of only a ChangeLogAdapter + */ + public void setAdapter(ChangeLogAdapter adapter) { + super.setAdapter(adapter); + } + + @Override + public void onItemClick(AdapterView parent, View view, int position, + long id) { + // TODO + } + + /** + * Async Task to parse xml file in a separate thread + */ + protected class ParseAsyncTask extends AsyncTask { + + private ChangeLogAdapter mAdapter; + private XmlParser mParse; + + public ParseAsyncTask(ChangeLogAdapter adapter, XmlParser parse) { + mAdapter = adapter; + mParse = parse; + } + + @Override + protected ChangeLog doInBackground(Void... params) { + + try { + if (mParse != null) { + ChangeLog chg = mParse.readChangeLogFile(); + return chg; + } + } catch (Exception e) { + Log.e(TAG, + getResources().getString( + R.string.changelog_internal_error_parsing), e); + } + return null; + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + protected void onPostExecute(ChangeLog chg) { + + // Notify data changed + if (chg != null) { + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { + mAdapter.addAll(chg.getRows()); + } else { + for (ChangeLogRow c : chg.getRows()) + mAdapter.add(c); + } + mAdapter.notifyDataSetChanged(); + } + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AdsUtils.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AdsUtils.java index ff88a54..d3896bb 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AdsUtils.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AdsUtils.java @@ -1,8 +1,5 @@ package org.exobel.routerkeygen; -import java.util.HashMap; -import java.util.Map; - import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; @@ -25,171 +22,169 @@ import com.millennialmedia.android.MMSDK; import com.millennialmedia.android.RequestListener.RequestListenerImpl; +import java.util.HashMap; +import java.util.Map; + public class AdsUtils { - private AdsUtils() { - } - - // Constants for tablet sized ads (728x90) - private static final int IAB_LEADERBOARD_WIDTH = 728; - private static final int IAB_LEADERBOARD_HEIGHT = 90; - - private static final int MED_BANNER_WIDTH = 480; - private static final int MED_BANNER_HEIGHT = 60; - - // Constants for phone sized ads (320x50) - private static final int BANNER_AD_WIDTH = 320; - private static final int BANNER_AD_HEIGHT = 50; - - private static final String BANNER_APID = "136973"; - private static final String CONNECT_APID = "200804"; - private static final String STARTUP_APID = "201332"; - - private static final String CONNECT_LAST_SHOWN_TIME = "CONNECT_LAST_SHOWN_TIME"; - private static final String STARTUP_LAST_SHOWN_TIME = "STARTUP_LAST_SHOWN_TIME"; - private static final String CONNECT_LAST_SHOWN_COUNT = "CONNECT_LAST_SHOWN_COUNT"; - private static final String STARTUP_LAST_SHOWN_COUNT = "STARTUP_LAST_SHOWN_COUNT"; - - public static MMAdView loadAdIfNeeded(Activity activity) { - // Create the adView - MMAdView adView = new MMAdView(activity); - if (checkDonation(activity)) { - final View vg = activity.findViewById(R.id.adBannerRelativeLayout); - ((ViewGroup) vg.getParent()).removeView(adView); - return null; - } - // Set your apid - adView.setApid(BANNER_APID); - adView.setMMRequest(getAdRequest(activity)); - // (Highly Recommended) Set the id to preserve your ad on - // configuration changes. Save Battery! - // Each MMAdView you give requires a unique id. - adView.setId(MMSDK.getDefaultAdId()); - - int placementWidth = BANNER_AD_WIDTH; - int placementHeight = BANNER_AD_HEIGHT; - - // (Optional) Set the ad size - if (canFit(activity.getResources(), IAB_LEADERBOARD_WIDTH)) { - placementWidth = IAB_LEADERBOARD_WIDTH; - placementHeight = IAB_LEADERBOARD_HEIGHT; - } else if (canFit(activity.getResources(), MED_BANNER_WIDTH)) { - placementWidth = MED_BANNER_WIDTH; - placementHeight = MED_BANNER_HEIGHT; - } - - // (Optional) Set the AdView size based on the placement size. You - // could use WRAP_CONTENT and not specify the placement size - adView.setWidth(placementWidth); - adView.setHeight(placementHeight); - adView.getAd(); - // Add the adview to the view layout - RelativeLayout adRelativeLayout = (RelativeLayout) activity - .findViewById(R.id.adBannerRelativeLayout); - int layoutWidth = (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, placementWidth, activity - .getResources().getDisplayMetrics()); - int layoutHeight = (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, placementHeight, activity - .getResources().getDisplayMetrics()); - RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( - layoutWidth, layoutHeight); - layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); - layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); - - adRelativeLayout.addView(adView, layoutParams); - return adView; - } - - private static MMRequest getAdRequest(Activity activity) { - // Acquire a reference to the system Location Manager - final LocationManager locationManager = (LocationManager) activity - .getSystemService(Context.LOCATION_SERVICE); - final MMRequest adRequest = new MMRequest(); - final Location location = locationManager - .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - if (location != null) { - MMRequest.setUserLocation(location); - } - Map metaData = new HashMap(); - metaData.put(MMRequest.KEY_ETHNICITY, MMRequest.ETHNICITY_HISPANIC); - adRequest.setMetaValues(metaData); - return adRequest; - } - - public static void displayStartupInterstitial(Activity activity) { - displayInterstitial(activity, STARTUP_APID, STARTUP_LAST_SHOWN_COUNT, - STARTUP_LAST_SHOWN_TIME); - } - - public static void displayConnectInterstitial(Activity activity) { - displayInterstitial(activity, CONNECT_APID, CONNECT_LAST_SHOWN_COUNT, - CONNECT_LAST_SHOWN_TIME); - } - - private static final int COUNTER_LIMIT = 5; - - private static void displayInterstitial(Activity activity, - final String apid, final String countKey, final String timeKey) { - if (checkDonation(activity)) { - return; // NO ADS! - } - final SharedPreferences mPrefs = PreferenceManager - .getDefaultSharedPreferences(activity); - final SharedPreferences.Editor editor = mPrefs.edit(); - int counter = mPrefs.getInt(countKey, 0); - final long timePassed = System.currentTimeMillis() - - mPrefs.getLong(timeKey, 0); - counter++; - editor.putInt(countKey, counter); - editor.apply(); - if (timePassed > DateUtils.WEEK_IN_MILLIS || counter >= COUNTER_LIMIT) { - final MMInterstitial interstitial = new MMInterstitial(activity); - - // Add the MMRequest object to your MMInterstitial. - interstitial.setMMRequest(getAdRequest(activity)); - interstitial.setApid(apid); - interstitial.setListener(new RequestListenerImpl() { - @Override - public void requestCompleted(MMAd mmAd) { - interstitial.display(); // display the ad that was cached by - // fetch - editor.putInt(countKey, 0); - editor.putLong(timeKey, System.currentTimeMillis()); - editor.apply(); - } - }); - interstitial.fetch(); // request ad to be cached locally - } - - } - - public static boolean checkDonation(Activity activity) { - final PackageManager pm = activity.getPackageManager(); - boolean app_installed = false; - try { - pm.getPackageInfo("org.exobel.routerkeygendownloader", - PackageManager.GET_ACTIVITIES); - app_installed = true; - } catch (PackageManager.NameNotFoundException e) { - app_installed = false; - } - if (!app_installed) { - try { - pm.getPackageInfo("org.doublecheck.wifiscanner", - PackageManager.GET_ACTIVITIES); - app_installed = true; - } catch (PackageManager.NameNotFoundException e) { - } - } - return app_installed; - } - - // Determine if the requested adWidth can fit on the screen. - private static boolean canFit(Resources res, int adWidth) { - int adWidthPx = (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, adWidth, res.getDisplayMetrics()); - DisplayMetrics metrics = res.getDisplayMetrics(); - return metrics.widthPixels >= adWidthPx; - } + // Constants for tablet sized ads (728x90) + private static final int IAB_LEADERBOARD_WIDTH = 728; + private static final int IAB_LEADERBOARD_HEIGHT = 90; + private static final int MED_BANNER_WIDTH = 480; + private static final int MED_BANNER_HEIGHT = 60; + // Constants for phone sized ads (320x50) + private static final int BANNER_AD_WIDTH = 320; + private static final int BANNER_AD_HEIGHT = 50; + private static final String BANNER_APID = "136973"; + private static final String CONNECT_APID = "200804"; + private static final String STARTUP_APID = "201332"; + private static final String CONNECT_LAST_SHOWN_TIME = "CONNECT_LAST_SHOWN_TIME"; + private static final String STARTUP_LAST_SHOWN_TIME = "STARTUP_LAST_SHOWN_TIME"; + private static final String CONNECT_LAST_SHOWN_COUNT = "CONNECT_LAST_SHOWN_COUNT"; + private static final String STARTUP_LAST_SHOWN_COUNT = "STARTUP_LAST_SHOWN_COUNT"; + private static final int COUNTER_LIMIT = 5; + + private AdsUtils() { + } + + public static MMAdView loadAdIfNeeded(Activity activity) { + // Create the adView + MMAdView adView = new MMAdView(activity); + if (checkDonation(activity)) { + final View vg = activity.findViewById(R.id.adBannerRelativeLayout); + ((ViewGroup) vg.getParent()).removeView(adView); + return null; + } + // Set your apid + adView.setApid(BANNER_APID); + adView.setMMRequest(getAdRequest(activity)); + // (Highly Recommended) Set the id to preserve your ad on + // configuration changes. Save Battery! + // Each MMAdView you give requires a unique id. + adView.setId(MMSDK.getDefaultAdId()); + + int placementWidth = BANNER_AD_WIDTH; + int placementHeight = BANNER_AD_HEIGHT; + + // (Optional) Set the ad size + if (canFit(activity.getResources(), IAB_LEADERBOARD_WIDTH)) { + placementWidth = IAB_LEADERBOARD_WIDTH; + placementHeight = IAB_LEADERBOARD_HEIGHT; + } else if (canFit(activity.getResources(), MED_BANNER_WIDTH)) { + placementWidth = MED_BANNER_WIDTH; + placementHeight = MED_BANNER_HEIGHT; + } + + // (Optional) Set the AdView size based on the placement size. You + // could use WRAP_CONTENT and not specify the placement size + adView.setWidth(placementWidth); + adView.setHeight(placementHeight); + adView.getAd(); + // Add the adview to the view layout + RelativeLayout adRelativeLayout = (RelativeLayout) activity + .findViewById(R.id.adBannerRelativeLayout); + int layoutWidth = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, placementWidth, activity + .getResources().getDisplayMetrics()); + int layoutHeight = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, placementHeight, activity + .getResources().getDisplayMetrics()); + RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( + layoutWidth, layoutHeight); + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); + layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); + + adRelativeLayout.addView(adView, layoutParams); + return adView; + } + + private static MMRequest getAdRequest(Activity activity) { + // Acquire a reference to the system Location Manager + final LocationManager locationManager = (LocationManager) activity + .getSystemService(Context.LOCATION_SERVICE); + final MMRequest adRequest = new MMRequest(); + final Location location = locationManager + .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); + if (location != null) { + MMRequest.setUserLocation(location); + } + Map metaData = new HashMap(); + metaData.put(MMRequest.KEY_ETHNICITY, MMRequest.ETHNICITY_HISPANIC); + adRequest.setMetaValues(metaData); + return adRequest; + } + + public static void displayStartupInterstitial(Activity activity) { + displayInterstitial(activity, STARTUP_APID, STARTUP_LAST_SHOWN_COUNT, + STARTUP_LAST_SHOWN_TIME); + } + + public static void displayConnectInterstitial(Activity activity) { + displayInterstitial(activity, CONNECT_APID, CONNECT_LAST_SHOWN_COUNT, + CONNECT_LAST_SHOWN_TIME); + } + + private static void displayInterstitial(Activity activity, + final String apid, final String countKey, final String timeKey) { + if (checkDonation(activity)) { + return; // NO ADS! + } + final SharedPreferences mPrefs = PreferenceManager + .getDefaultSharedPreferences(activity); + final SharedPreferences.Editor editor = mPrefs.edit(); + int counter = mPrefs.getInt(countKey, 0); + final long timePassed = System.currentTimeMillis() + - mPrefs.getLong(timeKey, 0); + counter++; + editor.putInt(countKey, counter); + editor.apply(); + if (timePassed > DateUtils.WEEK_IN_MILLIS || counter >= COUNTER_LIMIT) { + final MMInterstitial interstitial = new MMInterstitial(activity); + + // Add the MMRequest object to your MMInterstitial. + interstitial.setMMRequest(getAdRequest(activity)); + interstitial.setApid(apid); + interstitial.setListener(new RequestListenerImpl() { + @Override + public void requestCompleted(MMAd mmAd) { + interstitial.display(); // display the ad that was cached by + // fetch + editor.putInt(countKey, 0); + editor.putLong(timeKey, System.currentTimeMillis()); + editor.apply(); + } + }); + interstitial.fetch(); // request ad to be cached locally + } + + } + + public static boolean checkDonation(Activity activity) { + final PackageManager pm = activity.getPackageManager(); + boolean app_installed = false; + try { + pm.getPackageInfo("org.exobel.routerkeygendownloader", + PackageManager.GET_ACTIVITIES); + app_installed = true; + } catch (PackageManager.NameNotFoundException e) { + app_installed = false; + } + if (!app_installed) { + try { + pm.getPackageInfo("org.doublecheck.wifiscanner", + PackageManager.GET_ACTIVITIES); + app_installed = true; + } catch (PackageManager.NameNotFoundException e) { + } + } + return app_installed; + } + + // Determine if the requested adWidth can fit on the screen. + private static boolean canFit(Resources res, int adWidth) { + int adWidthPx = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, adWidth, res.getDisplayMetrics()); + DisplayMetrics metrics = res.getDisplayMetrics(); + return metrics.widthPixels >= adWidthPx; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectManager.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectManager.java index f571e96..66b0d49 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectManager.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectManager.java @@ -54,9 +54,9 @@ public void onReceive(Context context, Intent intent) { } public interface onConnectionListener { - public void onFailedConnection(); + void onFailedConnection(); - public void onSuccessfulConection(); + void onSuccessfulConection(); } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectService.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectService.java index 2d684f4..61e3ea5 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectService.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/AutoConnectService.java @@ -18,10 +18,6 @@ */ package org.exobel.routerkeygen; -import java.util.List; - -import org.exobel.routerkeygen.AutoConnectManager.onConnectionListener; - import android.annotation.TargetApi; import android.app.NotificationManager; import android.app.PendingIntent; @@ -43,232 +39,232 @@ import com.farproc.wifi.connecter.Wifi; -public class AutoConnectService extends Service implements onConnectionListener { - - public final static String SCAN_RESULT = "org.exobel.routerkeygen.SCAN_RESULT"; - public final static String KEY_LIST = "org.exobel.routerkeygen.KEY_LIST"; - - private final static int DISCONNECT_WAITING_TIME = 10000; +import org.exobel.routerkeygen.AutoConnectManager.onConnectionListener; - private final static int FAILING_MINIMUM_TIME = 1500; - private final int UNIQUE_ID = R.string.app_name - + AutoConnectService.class.getName().hashCode(); +import java.util.List; - private NotificationManager mNotificationManager; - private Handler handler; +public class AutoConnectService extends Service implements onConnectionListener { - final private Binder mBinder = new LocalBinder(); - private ScanResult network; - private List keys; - private int attempts = 0; - private AutoConnectManager mReceiver; - private WifiManager wifi; - private int mNumOpenNetworksKept; - private int currentNetworkId = -1; - private boolean cancelNotification = true; + public final static String SCAN_RESULT = "org.exobel.routerkeygen.SCAN_RESULT"; + public final static String KEY_LIST = "org.exobel.routerkeygen.KEY_LIST"; - private Runnable tryAfterDisconnecting = new Runnable() { - public void run() { - tryingConnection(); - } - }; + private final static int DISCONNECT_WAITING_TIME = 10000; - @Override - public IBinder onBind(Intent intent) { - return mBinder; - } + private final static int FAILING_MINIMUM_TIME = 1500; + private final int UNIQUE_ID = R.string.app_name + + AutoConnectService.class.getName().hashCode(); + final private Binder mBinder = new LocalBinder(); + private NotificationManager mNotificationManager; + private Handler handler; + private ScanResult network; + private List keys; + private int attempts = 0; + private AutoConnectManager mReceiver; + private WifiManager wifi; + private int mNumOpenNetworksKept; + private int currentNetworkId = -1; + private boolean cancelNotification = true; + private long lastTimeDisconnected = -1; + private Runnable tryAfterDisconnecting = new Runnable() { + public void run() { + tryingConnection(); + } + }; - /** - * Class for clients to access. Because we know this service always runs in - * the same process as its clients, we don't need to deal with IPC. - */ - public class LocalBinder extends Binder { - AutoConnectService getService() { - return AutoConnectService.this; - } - } + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private static PendingIntent getDefaultPendingIntent(Context context) { + final Intent i = new Intent(context, CancelOperationActivity.class) + .putExtra(CancelOperationActivity.SERVICE_TO_TERMINATE, + AutoConnectService.class.getName()) + .putExtra(CancelOperationActivity.MESSAGE, + context.getString(R.string.cancel_auto_test)) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) + i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); + return PendingIntent.getActivity(context, 0, i, + PendingIntent.FLAG_UPDATE_CURRENT); + } - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - @SuppressWarnings("deprecation") - public void onCreate() { - handler = new Handler(); - wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); - mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } - mReceiver = new AutoConnectManager(wifi, this); + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) + @SuppressWarnings("deprecation") + public void onCreate() { + handler = new Handler(); + wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) - mNumOpenNetworksKept = Settings.Secure.getInt(getContentResolver(), - Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); - else - mNumOpenNetworksKept = Settings.Global.getInt(getContentResolver(), - Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); + mReceiver = new AutoConnectManager(wifi, this); - } + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) + mNumOpenNetworksKept = Settings.Secure.getInt(getContentResolver(), + Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); + else + mNumOpenNetworksKept = Settings.Global.getInt(getContentResolver(), + Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - if (intent == null) { - stopSelf(); - return START_NOT_STICKY; - } - attempts = 0; - currentNetworkId = -1; - network = intent.getParcelableExtra(SCAN_RESULT); - keys = intent.getStringArrayListExtra(KEY_LIST); - final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); - final NetworkInfo mWifi = connManager - .getNetworkInfo(ConnectivityManager.TYPE_WIFI); - if (mWifi.isConnected()) { - if (wifi.disconnect()) { - // besides disconnecting, we clean any previous configuration - Wifi.cleanPreviousConfiguration(wifi, network, - network.capabilities); - mNotificationManager - .notify(UNIQUE_ID, - NotificationUtils - .createProgressBar( - this, - getString(R.string.app_name), - getString(R.string.not_auto_connect_waiting), - keys.size(), - 0, - false, - getDefaultPendingIntent(getApplicationContext()))); - handler.postDelayed(tryAfterDisconnecting, - DISCONNECT_WAITING_TIME); - cancelNotification = true; - } else { - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_error_key_testing)) - .build()); - cancelNotification = false; - stopSelf(); - return START_NOT_STICKY; - } - } else { - Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities); - tryingConnection(); - } - return START_STICKY; - } + } - private void tryingConnection() { - currentNetworkId = -1; - try { - currentNetworkId = Wifi.connectToNewNetwork(this, wifi, network, - keys.get(attempts++), mNumOpenNetworksKept); - Log.d(AutoConnectManager.class.getSimpleName(), - "Trying " + keys.get(attempts - 1)); - if (currentNetworkId != -1) { - lastTimeDisconnected = System.currentTimeMillis(); - if (attempts == 1)// first try, we register the listener - registerReceiver(mReceiver, new IntentFilter( - WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)); - mNotificationManager - .notify(UNIQUE_ID, - NotificationUtils - .createProgressBar( - this, - getString(R.string.app_name), - getString( - R.string.not_auto_connect_key_testing, - keys.get(attempts - 1)), - keys.size(), - attempts, - false, - getDefaultPendingIntent(getApplicationContext()))); - cancelNotification = true; - } - } catch (Exception e) { - e.printStackTrace(); - } - if (currentNetworkId == -1) { - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_error_key_testing)).build()); - cancelNotification = false; - stopSelf(); - } - } + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent == null) { + stopSelf(); + return START_NOT_STICKY; + } + attempts = 0; + currentNetworkId = -1; + network = intent.getParcelableExtra(SCAN_RESULT); + keys = intent.getStringArrayListExtra(KEY_LIST); + final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); + final NetworkInfo mWifi = connManager + .getNetworkInfo(ConnectivityManager.TYPE_WIFI); + if (mWifi.isConnected()) { + if (wifi.disconnect()) { + // besides disconnecting, we clean any previous configuration + Wifi.cleanPreviousConfiguration(wifi, network, + network.capabilities); + mNotificationManager + .notify(UNIQUE_ID, + NotificationUtils + .createProgressBar( + this, + getString(R.string.app_name), + getString(R.string.not_auto_connect_waiting), + keys.size(), + 0, + false, + getDefaultPendingIntent(getApplicationContext()))); + handler.postDelayed(tryAfterDisconnecting, + DISCONNECT_WAITING_TIME); + cancelNotification = true; + } else { + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_error_key_testing)) + .build()); + cancelNotification = false; + stopSelf(); + return START_NOT_STICKY; + } + } else { + Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities); + tryingConnection(); + } + return START_STICKY; + } - public void onDestroy() { - super.onDestroy(); - handler.removeCallbacks(tryAfterDisconnecting); - if (cancelNotification) - mNotificationManager.cancel(UNIQUE_ID); - reenableAllHotspots(); - try { - unregisterReceiver(mReceiver); - } catch (Exception e) { - e.printStackTrace(); - } - } + private void tryingConnection() { + currentNetworkId = -1; + try { + currentNetworkId = Wifi.connectToNewNetwork(this, wifi, network, + keys.get(attempts++), mNumOpenNetworksKept); + Log.d(AutoConnectManager.class.getSimpleName(), + "Trying " + keys.get(attempts - 1)); + if (currentNetworkId != -1) { + lastTimeDisconnected = System.currentTimeMillis(); + if (attempts == 1)// first try, we register the listener + registerReceiver(mReceiver, new IntentFilter( + WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)); + mNotificationManager + .notify(UNIQUE_ID, + NotificationUtils + .createProgressBar( + this, + getString(R.string.app_name), + getString( + R.string.not_auto_connect_key_testing, + keys.get(attempts - 1)), + keys.size(), + attempts, + false, + getDefaultPendingIntent(getApplicationContext()))); + cancelNotification = true; + } + } catch (Exception e) { + e.printStackTrace(); + } + if (currentNetworkId == -1) { + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_error_key_testing)).build()); + cancelNotification = false; + stopSelf(); + } + } - private long lastTimeDisconnected = -1; + public void onDestroy() { + super.onDestroy(); + handler.removeCallbacks(tryAfterDisconnecting); + if (cancelNotification) + mNotificationManager.cancel(UNIQUE_ID); + reenableAllHotspots(); + try { + unregisterReceiver(mReceiver); + } catch (Exception e) { + e.printStackTrace(); + } + } - public void onFailedConnection() { - /* Some phone are very strange and report multiples failures */ - if ((System.currentTimeMillis() - lastTimeDisconnected) < FAILING_MINIMUM_TIME) { - Log.d(AutoConnectManager.class.getSimpleName(), "Ignoring signal"); - return; - } - lastTimeDisconnected = System.currentTimeMillis(); - wifi.removeNetwork(currentNetworkId); - if (attempts >= keys.size()) { - reenableAllHotspots(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_no_correct_keys)).build()); - cancelNotification = false; - stopSelf(); - return; - } - tryingConnection(); - } + public void onFailedConnection() { + /* Some phone are very strange and report multiples failures */ + if ((System.currentTimeMillis() - lastTimeDisconnected) < FAILING_MINIMUM_TIME) { + Log.d(AutoConnectManager.class.getSimpleName(), "Ignoring signal"); + return; + } + lastTimeDisconnected = System.currentTimeMillis(); + wifi.removeNetwork(currentNetworkId); + if (attempts >= keys.size()) { + reenableAllHotspots(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_no_correct_keys)).build()); + cancelNotification = false; + stopSelf(); + return; + } + tryingConnection(); + } - public void onSuccessfulConection() { - reenableAllHotspots(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple( - this, - getString(R.string.app_name), - getString(R.string.not_correct_key_testing, - keys.get(attempts - 1))).build()); - cancelNotification = false; - stopSelf(); + public void onSuccessfulConection() { + reenableAllHotspots(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple( + this, + getString(R.string.app_name), + getString(R.string.not_correct_key_testing, + keys.get(attempts - 1))).build()); + cancelNotification = false; + stopSelf(); - } + } - private void reenableAllHotspots() { - final List configurations = wifi - .getConfiguredNetworks(); - if (configurations != null) { - for (final WifiConfiguration config : configurations) { - wifi.enableNetwork(config.networkId, false); - } - } - } + private void reenableAllHotspots() { + final List configurations = wifi + .getConfiguredNetworks(); + if (configurations != null) { + for (final WifiConfiguration config : configurations) { + wifi.enableNetwork(config.networkId, false); + } + } + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private static PendingIntent getDefaultPendingIntent(Context context) { - final Intent i = new Intent(context, CancelOperationActivity.class) - .putExtra(CancelOperationActivity.SERVICE_TO_TERMINATE, - AutoConnectService.class.getName()) - .putExtra(CancelOperationActivity.MESSAGE, - context.getString(R.string.cancel_auto_test)) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) - i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); - return PendingIntent.getActivity(context, 0, i, - PendingIntent.FLAG_UPDATE_CURRENT); - } + /** + * Class for clients to access. Because we know this service always runs in + * the same process as its clients, we don't need to deal with IPC. + */ + public class LocalBinder extends Binder { + AutoConnectService getService() { + return AutoConnectService.this; + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Base64.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Base64.java index 447d8e0..e378507 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Base64.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Base64.java @@ -58,7 +58,7 @@ public class Base64 { public static final int URL_SAFE = 8; /** - * Flag to pass to {@link Base64OutputStream} to indicate that it + * Flag to pass to Base64OutputStream to indicate that it * should not close the output stream it is wrapping when it * itself is closed. */ @@ -68,32 +68,8 @@ public class Base64 { // shared code // -------------------------------------------------------- - /* package */ static abstract class Coder { - public byte[] output; - public int op; - - /** - * Encode/decode another block of input data. this.output is - * provided by the caller, and must be big enough to hold all - * the coded data. On exit, this.opwill be set to the length - * of the coded data. - * - * @param finish true if this is the final call to process for - * this object. Will finalize the coder state and - * include any final bytes in the output. - * - * @return true if the input so far is good; false if some - * error has been detected in the input stream.. - */ - public abstract boolean process(byte[] input, int offset, int len, boolean finish); - - /** - * @return the maximum number of bytes a call to process() - * could produce for the given number of input bytes. This may - * be an overestimate. - */ - public abstract int maxOutputSize(int len); - } + private Base64() { + } // don't instantiate // -------------------------------------------------------- // decoding @@ -102,17 +78,16 @@ public class Base64 { /** * Decode the Base64-encoded data in input and return the data in * a new byte array. - * + *

*

The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * - * @param str the input String to decode, which is converted to - * bytes using the default charset - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * + * @param str the input String to decode, which is converted to + * bytes using the default charset + * @param flags controls certain features of the decoded output. + * Pass {@code DEFAULT} to decode standard Base64. * @throws IllegalArgumentException if the input contains - * incorrect padding + * incorrect padding */ public static byte[] decode(String str, int flags) { return decode(str.getBytes(), flags); @@ -121,16 +96,15 @@ public static byte[] decode(String str, int flags) { /** * Decode the Base64-encoded data in input and return the data in * a new byte array. - * + *

*

The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the input array to decode - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * + * @param flags controls certain features of the decoded output. + * Pass {@code DEFAULT} to decode standard Base64. * @throws IllegalArgumentException if the input contains - * incorrect padding + * incorrect padding */ public static byte[] decode(byte[] input, int flags) { return decode(input, 0, input.length, flags); @@ -139,7 +113,7 @@ public static byte[] decode(byte[] input, int flags) { /** * Decode the Base64-encoded data in input and return the data in * a new byte array. - * + *

*

The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * @@ -148,14 +122,13 @@ public static byte[] decode(byte[] input, int flags) { * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. - * * @throws IllegalArgumentException if the input contains - * incorrect padding + * incorrect padding */ public static byte[] decode(byte[] input, int offset, int len, int flags) { // Allocate space for the most data the input could represent. // (It could contain less if it contains whitespace, etc.) - Decoder decoder = new Decoder(flags, new byte[len*3/4]); + Decoder decoder = new Decoder(flags, new byte[len * 3 / 4]); if (!decoder.process(input, offset, len, true)) { throw new IllegalArgumentException("bad base-64"); @@ -173,28 +146,160 @@ public static byte[] decode(byte[] input, int offset, int len, int flags) { return temp; } + /** + * Base64-encode the given data and return a newly allocated + * String with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. + * Passing {@code DEFAULT} results in output that + * adheres to RFC 2045. + */ + public static String encodeToString(byte[] input, int flags) { + try { + return new String(encode(input, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + // -------------------------------------------------------- + // encoding + // -------------------------------------------------------- + + /** + * Base64-encode the given data and return a newly allocated + * String with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to + * start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. + * Passing {@code DEFAULT} results in output that + * adheres to RFC 2045. + */ + public static String encodeToString(byte[] input, int offset, int len, int flags) { + try { + return new String(encode(input, offset, len, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + /** + * Base64-encode the given data and return a newly allocated + * byte[] with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. + * Passing {@code DEFAULT} results in output that + * adheres to RFC 2045. + */ + public static byte[] encode(byte[] input, int flags) { + return encode(input, 0, input.length, flags); + } + + /** + * Base64-encode the given data and return a newly allocated + * byte[] with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to + * start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. + * Passing {@code DEFAULT} results in output that + * adheres to RFC 2045. + */ + public static byte[] encode(byte[] input, int offset, int len, int flags) { + Encoder encoder = new Encoder(flags, null); + + // Compute the exact length of the array we will produce. + int output_len = len / 3 * 4; + + // Account for the tail of the data and the padding bytes, if any. + if (encoder.do_padding) { + if (len % 3 > 0) { + output_len += 4; + } + } else { + switch (len % 3) { + case 0: + break; + case 1: + output_len += 2; + break; + case 2: + output_len += 3; + break; + } + } + + // Account for the newlines, if any. + if (encoder.do_newline && len > 0) { + output_len += (((len - 1) / (3 * Encoder.LINE_GROUPS)) + 1) * + (encoder.do_cr ? 2 : 1); + } + + encoder.output = new byte[output_len]; + encoder.process(input, offset, len, true); + + assert encoder.op == output_len; + + return encoder.output; + } + + /* package */ static abstract class Coder { + public byte[] output; + public int op; + + /** + * Encode/decode another block of input data. this.output is + * provided by the caller, and must be big enough to hold all + * the coded data. On exit, this.opwill be set to the length + * of the coded data. + * + * @param finish true if this is the final call to process for + * this object. Will finalize the coder state and + * include any final bytes in the output. + * @return true if the input so far is good; false if some + * error has been detected in the input stream.. + */ + public abstract boolean process(byte[] input, int offset, int len, boolean finish); + + /** + * @return the maximum number of bytes a call to process() + * could produce for the given number of input bytes. This may + * be an overestimate. + */ + public abstract int maxOutputSize(int len); + } + /* package */ static class Decoder extends Coder { /** * Lookup table for turning bytes into their position in the * Base64 alphabet. */ private static final int DECODE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** @@ -202,28 +307,30 @@ public static byte[] decode(byte[] input, int offset, int len, int flags) { * sec. 4) where - and _ replace + and /. */ private static final int DECODE_WEBSAFE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; - /** Non-data values in the DECODE arrays. */ + /** + * Non-data values in the DECODE arrays. + */ private static final int SKIP = -1; private static final int EQUALS = -2; - + final private int[] alphabet; /** * States 0-3 are reading through the next input tuple. * State 4 is having read one '=' and expecting exactly @@ -236,8 +343,6 @@ public static byte[] decode(byte[] input, int offset, int len, int flags) { private int state; // state number (0 to 6) private int value; - final private int[] alphabet; - public Decoder(int flags, byte[] output) { this.output = output; @@ -251,14 +356,14 @@ public Decoder(int flags, byte[] output) { * len} bytes could decode to. */ public int maxOutputSize(int len) { - return len * 3/4 + 10; + return len * 3 / 4 + 10; } /** * Decode another block of input data. * * @return true if the state machine is still healthy. false if - * bad base-64 data has been detected in the input stream. + * bad base-64 data has been detected in the input stream. */ public boolean process(byte[] input, int offset, int len, boolean finish) { if (this.state == 6) return false; @@ -293,13 +398,13 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { // You can remove this whole block and the output should // be the same, just slower. if (state == 0) { - while (p+4 <= len && - (value = ((alphabet[input[p] & 0xff] << 18) | - (alphabet[input[p+1] & 0xff] << 12) | - (alphabet[input[p+2] & 0xff] << 6) | - (alphabet[input[p+3] & 0xff]))) >= 0) { - output[op+2] = (byte) value; - output[op+1] = (byte) (value >> 8); + while (p + 4 <= len && + (value = ((alphabet[input[p] & 0xff] << 18) | + (alphabet[input[p + 1] & 0xff] << 12) | + (alphabet[input[p + 2] & 0xff] << 6) | + (alphabet[input[p + 3] & 0xff]))) >= 0) { + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; p += 4; @@ -315,78 +420,78 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { int d = alphabet[input[p++] & 0xff]; switch (state) { - case 0: - if (d >= 0) { - value = d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 1: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 2: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect exactly one more padding character. - output[op++] = (byte) (value >> 4); - state = 4; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 3: - if (d >= 0) { - // Emit the output triple and return to state 0. - value = (value << 6) | d; - output[op+2] = (byte) value; - output[op+1] = (byte) (value >> 8); - output[op] = (byte) (value >> 16); - op += 3; - state = 0; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect no further data or padding characters. - output[op+1] = (byte) (value >> 2); - output[op] = (byte) (value >> 10); - op += 2; - state = 5; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 4: - if (d == EQUALS) { - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 5: - if (d != SKIP) { - this.state = 6; - return false; - } - break; + case 0: + if (d >= 0) { + value = d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 1: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 2: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect exactly one more padding character. + output[op++] = (byte) (value >> 4); + state = 4; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 3: + if (d >= 0) { + // Emit the output triple and return to state 0. + value = (value << 6) | d; + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); + output[op] = (byte) (value >> 16); + op += 3; + state = 0; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect no further data or padding characters. + output[op + 1] = (byte) (value >> 2); + output[op] = (byte) (value >> 10); + op += 2; + state = 5; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 4: + if (d == EQUALS) { + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 5: + if (d != SKIP) { + this.state = 6; + return false; + } + break; } } @@ -403,33 +508,33 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { // the state machine and finish up. switch (state) { - case 0: - // Output length is a multiple of three. Fine. - break; - case 1: - // Read one extra input byte, which isn't enough to - // make another output byte. Illegal. - this.state = 6; - return false; - case 2: - // Read two extra input bytes, enough to emit 1 more - // output byte. Fine. - output[op++] = (byte) (value >> 4); - break; - case 3: - // Read three extra input bytes, enough to emit 2 more - // output bytes. Fine. - output[op++] = (byte) (value >> 10); - output[op++] = (byte) (value >> 2); - break; - case 4: - // Read one padding '=' when we expected 2. Illegal. - this.state = 6; - return false; - case 5: - // Read all the padding '='s we expected and no more. - // Fine. - break; + case 0: + // Output length is a multiple of three. Fine. + break; + case 1: + // Read one extra input byte, which isn't enough to + // make another output byte. Illegal. + this.state = 6; + return false; + case 2: + // Read two extra input bytes, enough to emit 1 more + // output byte. Fine. + output[op++] = (byte) (value >> 4); + break; + case 3: + // Read three extra input bytes, enough to emit 2 more + // output bytes. Fine. + output[op++] = (byte) (value >> 10); + output[op++] = (byte) (value >> 2); + break; + case 4: + // Read one padding '=' when we expected 2. Illegal. + this.state = 6; + return false; + case 5: + // Read all the padding '='s we expected and no more. + // Fine. + break; } this.state = state; @@ -438,107 +543,6 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { } } - // -------------------------------------------------------- - // encoding - // -------------------------------------------------------- - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(byte[] input, int flags) { - try { - return new String(encode(input, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(byte[] input, int offset, int len, int flags) { - try { - return new String(encode(input, offset, len, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(byte[] input, int flags) { - return encode(input, 0, input.length, flags); - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(byte[] input, int offset, int len, int flags) { - Encoder encoder = new Encoder(flags, null); - - // Compute the exact length of the array we will produce. - int output_len = len / 3 * 4; - - // Account for the tail of the data and the padding bytes, if any. - if (encoder.do_padding) { - if (len % 3 > 0) { - output_len += 4; - } - } else { - switch (len % 3) { - case 0: break; - case 1: output_len += 2; break; - case 2: output_len += 3; break; - } - } - - // Account for the newlines, if any. - if (encoder.do_newline && len > 0) { - output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) * - (encoder.do_cr ? 2 : 1); - } - - encoder.output = new byte[output_len]; - encoder.process(input, offset, len, true); - - assert encoder.op == output_len; - - return encoder.output; - } - /* package */ static class Encoder extends Coder { /** * Emit a new line every this many output tuples. Corresponds to @@ -552,10 +556,10 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { * into output bytes. */ private static final byte ENCODE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; /** @@ -563,20 +567,18 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { * into output bytes. */ private static final byte ENCODE_WEBSAFE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', }; - - final private byte[] tail; - /* package */ int tailLen; - private int count; - final public boolean do_padding; final public boolean do_newline; final public boolean do_cr; + final private byte[] tail; final private byte[] alphabet; + /* package */ int tailLen; + private int count; public Encoder(int flags, byte[] output) { this.output = output; @@ -597,7 +599,7 @@ public Encoder(int flags, byte[] output) { * len} bytes could encode to. */ public int maxOutputSize(int len) { - return len * 8/5 + 10; + return len * 8 / 5 + 10; } public boolean process(byte[] input, int offset, int len, boolean finish) { @@ -621,22 +623,22 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { break; case 1: - if (p+2 <= len) { + if (p + 2 <= len) { // A 1-byte tail with at least 2 bytes of // input available now. v = ((tail[0] & 0xff) << 16) | - ((input[p++] & 0xff) << 8) | - (input[p++] & 0xff); + ((input[p++] & 0xff) << 8) | + (input[p++] & 0xff); tailLen = 0; - }; + } break; case 2: - if (p+1 <= len) { + if (p + 1 <= len) { // A 2-byte tail with at least 1 byte of input. v = ((tail[0] & 0xff) << 16) | - ((tail[1] & 0xff) << 8) | - (input[p++] & 0xff); + ((tail[1] & 0xff) << 8) | + (input[p++] & 0xff); tailLen = 0; } break; @@ -659,14 +661,14 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { // The main loop, turning 3 input bytes into 4 output bytes on // each iteration. - while (p+3 <= len) { + while (p + 3 <= len) { v = ((input[p] & 0xff) << 16) | - ((input[p+1] & 0xff) << 8) | - (input[p+2] & 0xff); + ((input[p + 1] & 0xff) << 8) | + (input[p + 2] & 0xff); output[op] = alphabet[(v >> 18) & 0x3f]; - output[op+1] = alphabet[(v >> 12) & 0x3f]; - output[op+2] = alphabet[(v >> 6) & 0x3f]; - output[op+3] = alphabet[v & 0x3f]; + output[op + 1] = alphabet[(v >> 12) & 0x3f]; + output[op + 2] = alphabet[(v >> 6) & 0x3f]; + output[op + 3] = alphabet[v & 0x3f]; p += 3; op += 4; if (--count == 0) { @@ -682,7 +684,7 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { // remaining in input; there should be at most two bytes // total. - if (p-tailLen == len-1) { + if (p - tailLen == len - 1) { int t = 0; v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; tailLen -= t; @@ -696,10 +698,10 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } - } else if (p-tailLen == len-2) { + } else if (p - tailLen == len - 2) { int t = 0; v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) | - (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); + (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); tailLen -= t; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; @@ -722,11 +724,11 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { // Save the leftovers in tail to be consumed on the next // call to encodeInternal. - if (p == len-1) { + if (p == len - 1) { tail[tailLen++] = input[p]; - } else if (p == len-2) { + } else if (p == len - 2) { tail[tailLen++] = input[p]; - tail[tailLen++] = input[p+1]; + tail[tailLen++] = input[p + 1]; } } @@ -736,6 +738,4 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { return true; } } - - private Base64() { } // don't instantiate } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/CancelOperationActivity.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/CancelOperationActivity.java index 65a1d29..f079eb4 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/CancelOperationActivity.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/CancelOperationActivity.java @@ -10,56 +10,56 @@ public class CancelOperationActivity extends Activity { - public static final String SERVICE_TO_TERMINATE = "terminateService"; - public static final String MESSAGE = "message"; + public static final String SERVICE_TO_TERMINATE = "terminateService"; + public static final String MESSAGE = "message"; - @SuppressWarnings("deprecation") - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_cancel_operation); - if (getIntent().getStringExtra(SERVICE_TO_TERMINATE) == null) - finish(); - else { - showDialog(0); - } - } + @SuppressWarnings("deprecation") + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_cancel_operation); + if (getIntent().getStringExtra(SERVICE_TO_TERMINATE) == null) + finish(); + else { + showDialog(0); + } + } - /* - * {@inheritDoc} - */ - @Override - protected Dialog onCreateDialog(int id) { - final AlertDialog.Builder builder = new AlertDialog.Builder(this); - String message = getIntent().getStringExtra(MESSAGE); - if (message == null) - message = getString(android.R.string.cancel) + "?"; - builder.setTitle(R.string.app_name) - .setNegativeButton(android.R.string.no, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - dialog.dismiss(); - finish(); - } - }) - .setPositiveButton(android.R.string.yes, new OnClickListener() { + /* + * {@inheritDoc} + */ + @Override + protected Dialog onCreateDialog(int id) { + final AlertDialog.Builder builder = new AlertDialog.Builder(this); + String message = getIntent().getStringExtra(MESSAGE); + if (message == null) + message = getString(android.R.string.cancel) + "?"; + builder.setTitle(R.string.app_name) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + dialog.dismiss(); + finish(); + } + }) + .setPositiveButton(android.R.string.yes, new OnClickListener() { - public void onClick(DialogInterface dialog, int which) { + public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - try { - stopService(new Intent(getApplicationContext(), - Class.forName(getIntent().getStringExtra( - SERVICE_TO_TERMINATE)))); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } + dialog.dismiss(); + try { + stopService(new Intent(getApplicationContext(), + Class.forName(getIntent().getStringExtra( + SERVICE_TO_TERMINATE)))); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } - finish(); - } - }).setMessage(message); - return builder.create(); - } + finish(); + } + }).setMessage(message); + return builder.create(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/DictionaryDownloadService.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/DictionaryDownloadService.java index 0782d57..7c1962b 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/DictionaryDownloadService.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/DictionaryDownloadService.java @@ -1,16 +1,5 @@ package org.exobel.routerkeygen; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -import org.exobel.routerkeygen.ui.Preferences; -import org.exobel.routerkeygen.utils.HashUtils; - import android.annotation.TargetApi; import android.app.IntentService; import android.app.Notification; @@ -24,295 +13,304 @@ import android.preference.PreferenceManager; import android.widget.Toast; -public class DictionaryDownloadService extends IntentService { +import org.exobel.routerkeygen.ui.Preferences; +import org.exobel.routerkeygen.utils.HashUtils; - public final static String URL_DOWNLOAD = "org.exobel.routerkeygen.DictionaryDownloadService.URL_DOWNLOAD"; - private final static String DEFAULT_DIC_NAME = "RouterKeygen.dic"; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; - private static final long MIN_TIME_BETWWEN_UPDATES = 500; +public class DictionaryDownloadService extends IntentService { - private static final byte[] DICTIONARY_HASH = { (byte) 0x8c, (byte) 0xcf, - 0x2c, (byte) 0xb2, (byte) 0xe8, (byte) 0xda, (byte) 0x13, - (byte) 0xc2, (byte) 0xd8, (byte) 0xc7, (byte) 0xbb, (byte) 0x08, - 0x2c, (byte) 0xc2, (byte) 0x1f, (byte) 0xe6 }; + public final static String URL_DOWNLOAD = "org.exobel.routerkeygen.DictionaryDownloadService.URL_DOWNLOAD"; + private final static String DEFAULT_DIC_NAME = "RouterKeygen.dic"; - public DictionaryDownloadService() { - super("DictionaryDownloadService"); - } + private static final long MIN_TIME_BETWWEN_UPDATES = 500; - private NotificationManager mNotificationManager; - private Notification update; - private boolean cancelNotification = true; + private static final byte[] DICTIONARY_HASH = {(byte) 0x8c, (byte) 0xcf, + 0x2c, (byte) 0xb2, (byte) 0xe8, (byte) 0xda, (byte) 0x13, + (byte) 0xc2, (byte) 0xd8, (byte) 0xc7, (byte) 0xbb, (byte) 0x08, + 0x2c, (byte) 0xc2, (byte) 0x1f, (byte) 0xe6}; + // Unique Identification Number for the Notification. + // We use it on Notification start, and to cancel it. + private final int UNIQUE_ID = R.string.app_name + + DictionaryDownloadService.class.getName().hashCode(); + private NotificationManager mNotificationManager; + private Notification update; + private boolean cancelNotification = true; + private int fileLen; + private boolean stopRequested = false; - @Override - public void onCreate() { - super.onCreate(); - mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - } + public DictionaryDownloadService() { + super("DictionaryDownloadService"); + } - // Unique Identification Number for the Notification. - // We use it on Notification start, and to cancel it. - private final int UNIQUE_ID = R.string.app_name - + DictionaryDownloadService.class.getName().hashCode(); - private int fileLen; - private boolean stopRequested = false; + @Override + public void onCreate() { + super.onCreate(); + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + } - public void onDestroy() { - super.onDestroy(); - stopRequested = true; - if (cancelNotification) - mNotificationManager.cancel(UNIQUE_ID); - } + public void onDestroy() { + super.onDestroy(); + stopRequested = true; + if (cancelNotification) + mNotificationManager.cancel(UNIQUE_ID); + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - protected void onHandleIntent(Intent intent) { - File myDicFile; - HttpURLConnection con = null; - DataInputStream dis = null; - FileOutputStream fos = null; - int myProgress = 0; - int byteRead; - byte[] buf; + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + protected void onHandleIntent(Intent intent) { + File myDicFile; + HttpURLConnection con = null; + DataInputStream dis = null; + FileOutputStream fos = null; + int myProgress = 0; + int byteRead; + byte[] buf; - if (!Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_nosdcard)).build()); - cancelNotification = false; - return; - } - final String dicTemp = Environment.getExternalStorageDirectory() - .getPath() - + File.separator - + "DicTemp" - + System.currentTimeMillis(); - try { + if (!Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED)) { + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_nosdcard)).build()); + cancelNotification = false; + return; + } + final String dicTemp = Environment.getExternalStorageDirectory() + .getPath() + + File.separator + + "DicTemp" + + System.currentTimeMillis(); + try { - final String urlDownload = intent.getStringExtra(URL_DOWNLOAD); + final String urlDownload = intent.getStringExtra(URL_DOWNLOAD); - con = (HttpURLConnection) new URL(urlDownload).openConnection(); + con = (HttpURLConnection) new URL(urlDownload).openConnection(); - myProgress = byteRead = 0; + myProgress = byteRead = 0; - dis = new DataInputStream(con.getInputStream()); - fileLen = con.getContentLength(); - if (noSpaceLeft(fileLen)) { - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_nomemoryonsdcard)) - .build()); - dis.close(); - con.disconnect(); - cancelNotification = false; - return; - } - String dicFile = PreferenceManager.getDefaultSharedPreferences( - getBaseContext()).getString(Preferences.dicLocalPref, null); - if (dicFile == null) { - dicFile = Environment.getExternalStorageDirectory().getPath() - + File.separator + DEFAULT_DIC_NAME; - final SharedPreferences.Editor editor = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()).edit(); - editor.putString(Preferences.dicLocalPref, dicFile); - editor.commit(); - } + dis = new DataInputStream(con.getInputStream()); + fileLen = con.getContentLength(); + if (noSpaceLeft(fileLen)) { + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_nomemoryonsdcard)) + .build()); + dis.close(); + con.disconnect(); + cancelNotification = false; + return; + } + String dicFile = PreferenceManager.getDefaultSharedPreferences( + getBaseContext()).getString(Preferences.dicLocalPref, null); + if (dicFile == null) { + dicFile = Environment.getExternalStorageDirectory().getPath() + + File.separator + DEFAULT_DIC_NAME; + final SharedPreferences.Editor editor = PreferenceManager + .getDefaultSharedPreferences(getBaseContext()).edit(); + editor.putString(Preferences.dicLocalPref, dicFile); + editor.commit(); + } - // Testing if we can write to the file - if (!canWrite(dicFile) || !canWrite(dicTemp)) { - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_no_write_permissions)) - .build()); - dis.close(); - con.disconnect(); - cancelNotification = false; - return; - } - myDicFile = new File(dicTemp); + // Testing if we can write to the file + if (!canWrite(dicFile) || !canWrite(dicTemp)) { + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_no_write_permissions)) + .build()); + dis.close(); + con.disconnect(); + cancelNotification = false; + return; + } + myDicFile = new File(dicTemp); - fos = new FileOutputStream(myDicFile, false); + fos = new FileOutputStream(myDicFile, false); - final Intent i = new Intent(getApplicationContext(), - CancelOperationActivity.class) - .putExtra(CancelOperationActivity.SERVICE_TO_TERMINATE, - DictionaryDownloadService.class.getName()) - .putExtra( - CancelOperationActivity.MESSAGE, - getApplicationContext().getString( - R.string.cancel_download)) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) - i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); - update = NotificationUtils.createProgressBar(this, - getString(R.string.msg_dl_dlingdic), "", fileLen, - myProgress, false, PendingIntent.getActivity( - getApplicationContext(), 0, i, - PendingIntent.FLAG_UPDATE_CURRENT)); - mNotificationManager.notify(UNIQUE_ID, update); - long lastNotificationTime = System.currentTimeMillis(); - buf = new byte[1024 * 512]; - while (myProgress < fileLen) { - if (stopRequested) { - mNotificationManager.cancel(UNIQUE_ID); - dis.close(); - fos.close(); - con.disconnect(); - myDicFile.delete(); - return; - } - if ((byteRead = dis.read(buf)) != -1) { - fos.write(buf, 0, byteRead); - myProgress += byteRead; - } else { - dis.close(); - fos.close(); - con.disconnect(); - myProgress = fileLen; - } - if ((System.currentTimeMillis() - lastNotificationTime) > MIN_TIME_BETWWEN_UPDATES) { - mNotificationManager.notify(UNIQUE_ID, NotificationUtils - .updateProgressBar(update, fileLen, myProgress, - false)); - lastNotificationTime = System.currentTimeMillis(); - } - } + final Intent i = new Intent(getApplicationContext(), + CancelOperationActivity.class) + .putExtra(CancelOperationActivity.SERVICE_TO_TERMINATE, + DictionaryDownloadService.class.getName()) + .putExtra( + CancelOperationActivity.MESSAGE, + getApplicationContext().getString( + R.string.cancel_download)) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) + i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); + update = NotificationUtils.createProgressBar(this, + getString(R.string.msg_dl_dlingdic), "", fileLen, + myProgress, false, PendingIntent.getActivity( + getApplicationContext(), 0, i, + PendingIntent.FLAG_UPDATE_CURRENT)); + mNotificationManager.notify(UNIQUE_ID, update); + long lastNotificationTime = System.currentTimeMillis(); + buf = new byte[1024 * 512]; + while (myProgress < fileLen) { + if (stopRequested) { + mNotificationManager.cancel(UNIQUE_ID); + dis.close(); + fos.close(); + con.disconnect(); + myDicFile.delete(); + return; + } + if ((byteRead = dis.read(buf)) != -1) { + fos.write(buf, 0, byteRead); + myProgress += byteRead; + } else { + dis.close(); + fos.close(); + con.disconnect(); + myProgress = fileLen; + } + if ((System.currentTimeMillis() - lastNotificationTime) > MIN_TIME_BETWWEN_UPDATES) { + mNotificationManager.notify(UNIQUE_ID, NotificationUtils + .updateProgressBar(update, fileLen, myProgress, + false)); + lastNotificationTime = System.currentTimeMillis(); + } + } - mNotificationManager - .notify(UNIQUE_ID, - NotificationUtils - .createProgressBar( - this, - getString(R.string.msg_dl_dlingdic), - getString(R.string.msg_wait), - 0, - 0, - true, - NotificationUtils - .getDefaultPendingIntent(getApplicationContext()))); - if (!HashUtils.checkDicMD5(dicTemp, DICTIONARY_HASH)) { - new File(dicTemp).delete(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_err_unkown)).build()); - cancelNotification = false; - return; - } - if (!renameFile(dicTemp, dicFile, true)) { - new File(dicTemp).delete(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.pref_msg_err_rename_dic)) - .build()); - cancelNotification = false; - return; - } - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.app_name), - getString(R.string.msg_dic_updated_finished)) - .build()); - cancelNotification = false; - } catch (FileNotFoundException e) { - new File(dicTemp).delete(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_nosdcard)).build()); - cancelNotification = false; - e.printStackTrace(); - } catch (Exception e) { - new File(dicTemp).delete(); - mNotificationManager.notify( - UNIQUE_ID, - NotificationUtils.getSimple(this, - getString(R.string.msg_error), - getString(R.string.msg_err_unkown)).build()); - cancelNotification = false; - e.printStackTrace(); - } finally { - if (fos != null) - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - if (dis != null) - try { - dis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - if (con != null) - con.disconnect(); - } - } + mNotificationManager + .notify(UNIQUE_ID, + NotificationUtils + .createProgressBar( + this, + getString(R.string.msg_dl_dlingdic), + getString(R.string.msg_wait), + 0, + 0, + true, + NotificationUtils + .getDefaultPendingIntent(getApplicationContext()))); + if (!HashUtils.checkDicMD5(dicTemp, DICTIONARY_HASH)) { + new File(dicTemp).delete(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_err_unkown)).build()); + cancelNotification = false; + return; + } + if (!renameFile(dicTemp, dicFile, true)) { + new File(dicTemp).delete(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.pref_msg_err_rename_dic)) + .build()); + cancelNotification = false; + return; + } + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.app_name), + getString(R.string.msg_dic_updated_finished)) + .build()); + cancelNotification = false; + } catch (FileNotFoundException e) { + new File(dicTemp).delete(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_nosdcard)).build()); + cancelNotification = false; + e.printStackTrace(); + } catch (Exception e) { + new File(dicTemp).delete(); + mNotificationManager.notify( + UNIQUE_ID, + NotificationUtils.getSimple(this, + getString(R.string.msg_error), + getString(R.string.msg_err_unkown)).build()); + cancelNotification = false; + e.printStackTrace(); + } finally { + if (fos != null) + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if (dis != null) + try { + dis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if (con != null) + con.disconnect(); + } + } - private boolean canWrite(String filename) { - File file; - while ((file = new File(filename)).exists()) { - filename += "1"; - } - try { - file.createNewFile(); - boolean ret = file.canWrite(); - file.delete(); - return ret; - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } + private boolean canWrite(String filename) { + File file; + while ((file = new File(filename)).exists()) { + filename += "1"; + } + try { + file.createNewFile(); + boolean ret = file.canWrite(); + file.delete(); + return ret; + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } - private boolean renameFile(String file, String toFile, boolean saveOld) { + private boolean renameFile(String file, String toFile, boolean saveOld) { - File toBeRenamed = new File(file); - File newFile = new File(toFile); + File toBeRenamed = new File(file); + File newFile = new File(toFile); - if (!toBeRenamed.exists() || toBeRenamed.isDirectory() - || newFile.isDirectory()) - return false; + if (!toBeRenamed.exists() || toBeRenamed.isDirectory() + || newFile.isDirectory()) + return false; - if (newFile.exists() && saveOld) { - if (!renameFile(toFile, toFile + "_backup", true)) - Toast.makeText(getBaseContext(), - R.string.pref_msg_err_backup_dic, Toast.LENGTH_SHORT) - .show(); - } + if (newFile.exists() && saveOld) { + if (!renameFile(toFile, toFile + "_backup", true)) + Toast.makeText(getBaseContext(), + R.string.pref_msg_err_backup_dic, Toast.LENGTH_SHORT) + .show(); + } - // Rename - return toBeRenamed.renameTo(newFile); - } + // Rename + return toBeRenamed.renameTo(newFile); + } - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @SuppressWarnings("deprecation") - private boolean noSpaceLeft(int fileLen) { - // Checking if external storage has enough memory ... - android.os.StatFs stat = new android.os.StatFs(Environment - .getExternalStorageDirectory().getPath()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { - long fileLenLong = fileLen; - if (stat.getBlockSizeLong() == 0) - return true; - return stat.getAvailableBlocksLong() < (fileLenLong / stat - .getBlockSizeLong()); - } else { - if (stat.getBlockSize() == 0) - return true; - return stat.getAvailableBlocks() < (fileLen / stat.getBlockSize()); - } - } + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) + @SuppressWarnings("deprecation") + private boolean noSpaceLeft(int fileLen) { + // Checking if external storage has enough memory ... + android.os.StatFs stat = new android.os.StatFs(Environment + .getExternalStorageDirectory().getPath()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { + long fileLenLong = fileLen; + if (stat.getBlockSizeLong() == 0) + return true; + return stat.getAvailableBlocksLong() < (fileLenLong / stat + .getBlockSizeLong()); + } else { + if (stat.getBlockSize() == 0) + return true; + return stat.getAvailableBlocks() < (fileLen / stat.getBlockSize()); + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Downloader.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Downloader.java index d8499c7..f8ef722 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Downloader.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/Downloader.java @@ -18,6 +18,10 @@ */ package org.exobel.routerkeygen; +import android.os.Environment; +import android.os.Handler; +import android.os.Message; + import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; @@ -25,100 +29,96 @@ import java.net.URL; import java.net.URLConnection; -import android.os.Environment; -import android.os.Handler; -import android.os.Message; - public class Downloader extends Thread { - Handler messHand; - String urlDownload; - private boolean stopRequested = false; - private boolean deleteTemp = false; - - @SuppressWarnings("deprecation") - public void run() { - File myDicFile; - URLConnection con; - DataInputStream dis; - FileOutputStream fos; - int myProgress = 0; - int fileLen, byteRead; - byte[] buf; - try { - - con = new URL(urlDownload).openConnection(); - myDicFile = new File(Environment.getExternalStorageDirectory() - .getPath() + File.separator + "DicTemp.dic"); - - // Append mode on - fos = new FileOutputStream(myDicFile, true); - - // Resuming if possible - myProgress = byteRead = (int) myDicFile.length(); - if (byteRead > 0) - con.setRequestProperty("Range", "bytes=" + byteRead + "-"); - - dis = new DataInputStream(con.getInputStream()); - fileLen = myProgress + con.getContentLength(); - messHand.sendMessage(Message.obtain(messHand, 2, myProgress, - fileLen)); - // Checking if external storage has enough memory ... - android.os.StatFs stat = new android.os.StatFs(Environment - .getExternalStorageDirectory().getPath()); - if (stat.getBlockSize() * stat.getAvailableBlocks() < fileLen) - messHand.sendEmptyMessage(1); - - buf = new byte[65536]; - while (myProgress < fileLen) { - try { - - if ((byteRead = dis.read(buf)) != -1) { - fos.write(buf, 0, byteRead); - myProgress += byteRead; - } else { - dis.close(); - fos.close(); - myProgress = fileLen; - } - } catch (Exception e) { - } - messHand.sendMessage(Message.obtain(messHand, 4, myProgress, - fileLen)); - if (isStopRequested()) { - if (isDeleteTemp()) - myDicFile.delete(); - dis.close(); - fos.close(); - return; - } - } - messHand.sendEmptyMessage(3); - } catch (FileNotFoundException e) { - messHand.sendEmptyMessage(0); - } catch (Exception e) { - messHand.sendEmptyMessage(-1); - } - } - - public Downloader(Handler messHand, String urlDownload) { - this.messHand = messHand; - this.urlDownload = urlDownload; - } - - public boolean isStopRequested() { - return stopRequested; - } - - public void setStopRequested(boolean stopRequested) { - this.stopRequested = stopRequested; - } - - public boolean isDeleteTemp() { - return deleteTemp; - } - - public void setDeleteTemp(boolean deleteTemp) { - this.deleteTemp = deleteTemp; - } + Handler messHand; + String urlDownload; + private boolean stopRequested = false; + private boolean deleteTemp = false; + + public Downloader(Handler messHand, String urlDownload) { + this.messHand = messHand; + this.urlDownload = urlDownload; + } + + @SuppressWarnings("deprecation") + public void run() { + File myDicFile; + URLConnection con; + DataInputStream dis; + FileOutputStream fos; + int myProgress = 0; + int fileLen, byteRead; + byte[] buf; + try { + + con = new URL(urlDownload).openConnection(); + myDicFile = new File(Environment.getExternalStorageDirectory() + .getPath() + File.separator + "DicTemp.dic"); + + // Append mode on + fos = new FileOutputStream(myDicFile, true); + + // Resuming if possible + myProgress = byteRead = (int) myDicFile.length(); + if (byteRead > 0) + con.setRequestProperty("Range", "bytes=" + byteRead + "-"); + + dis = new DataInputStream(con.getInputStream()); + fileLen = myProgress + con.getContentLength(); + messHand.sendMessage(Message.obtain(messHand, 2, myProgress, + fileLen)); + // Checking if external storage has enough memory ... + android.os.StatFs stat = new android.os.StatFs(Environment + .getExternalStorageDirectory().getPath()); + if (stat.getBlockSize() * stat.getAvailableBlocks() < fileLen) + messHand.sendEmptyMessage(1); + + buf = new byte[65536]; + while (myProgress < fileLen) { + try { + + if ((byteRead = dis.read(buf)) != -1) { + fos.write(buf, 0, byteRead); + myProgress += byteRead; + } else { + dis.close(); + fos.close(); + myProgress = fileLen; + } + } catch (Exception e) { + } + messHand.sendMessage(Message.obtain(messHand, 4, myProgress, + fileLen)); + if (isStopRequested()) { + if (isDeleteTemp()) + myDicFile.delete(); + dis.close(); + fos.close(); + return; + } + } + messHand.sendEmptyMessage(3); + } catch (FileNotFoundException e) { + messHand.sendEmptyMessage(0); + } catch (Exception e) { + messHand.sendEmptyMessage(-1); + } + } + + public boolean isStopRequested() { + return stopRequested; + } + + public void setStopRequested(boolean stopRequested) { + this.stopRequested = stopRequested; + } + + public boolean isDeleteTemp() { + return deleteTemp; + } + + public void setDeleteTemp(boolean deleteTemp) { + this.deleteTemp = deleteTemp; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/JenkinsHash.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/JenkinsHash.java index 873364b..e2a89dc 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/JenkinsHash.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/JenkinsHash.java @@ -26,9 +26,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -67,19 +67,19 @@ * @author yonik */ public class JenkinsHash { - /** - * A Java implementation of hashword from lookup3.c by Bob Jenkins - * (original source). - * - * @param k the key to hash - * @param offset offset of the start of the key - * @param length length of the key - * @param initval initial value to fold into the hash - * @return the 32 bit hash code - */ - - - // max value to limit it to 4 bytes + /** + * A Java implementation of hashword from lookup3.c by Bob Jenkins + * (original source). + * + * @param k the key to hash + * @param offset offset of the start of the key + * @param length length of the key + * @param initval initial value to fold into the hash + * @return the 32 bit hash code + */ + + + // max value to limit it to 4 bytes private static final long MAX_VALUE = 0xFFFFFFFFL; // internal variables used in the various calculations @@ -128,78 +128,81 @@ private long leftShift(long val, int shift) { return (val << shift) & MAX_VALUE; } - - private long rot(long val, int shift){ - return (leftShift(val, shift)|(val>>>(32-shift))) & MAX_VALUE; + + private long rot(long val, int shift) { + return (leftShift(val, shift) | (val >>> (32 - shift))) & MAX_VALUE; } + /** * Mix up the values in the hash function. */ private void hashMix() { - a = subtract(a,c); - a = xor(a, rot(c, 4)); - c = add(c, b); - b = subtract(b,a); - b = xor(b, rot(a, 6)); - a = add(a, c); - c = subtract(c,b); - c = xor(c, rot(b, 8)); - b = add(b, a); - a = subtract(a,c); - a = xor(a, rot(c, 16)); - c = add(c, b); - b = subtract(b,a); - b = xor(b, rot(a, 19)); - a = add(a, c); - c = subtract(c,b); - c = xor(c, rot(b, 4)); - b = add(b, a); + a = subtract(a, c); + a = xor(a, rot(c, 4)); + c = add(c, b); + b = subtract(b, a); + b = xor(b, rot(a, 6)); + a = add(a, c); + c = subtract(c, b); + c = xor(c, rot(b, 8)); + b = add(b, a); + a = subtract(a, c); + a = xor(a, rot(c, 16)); + c = add(c, b); + b = subtract(b, a); + b = xor(b, rot(a, 19)); + a = add(a, c); + c = subtract(c, b); + c = xor(c, rot(b, 4)); + b = add(b, a); } - @SuppressWarnings("fallthrough") - public long hashword(long[] k, int length, long initval) { - - a = b = c = 0xdeadbeef + (length<<2) + ( initval & MAX_VALUE ) ; - - int i=0; - while (length > 3) - { - a = add( a, k[i+0]); - b = add( b, k[i+1]); - c = add( c, k[i+2]); - hashMix(); - - length -= 3; - i += 3; + @SuppressWarnings("fallthrough") + public long hashword(long[] k, int length, long initval) { + + a = b = c = 0xdeadbeef + (length << 2) + (initval & MAX_VALUE); + + int i = 0; + while (length > 3) { + a = add(a, k[i + 0]); + b = add(b, k[i + 1]); + c = add(c, k[i + 2]); + hashMix(); + + length -= 3; + i += 3; + } + + switch (length) { + case 3: + c = add(c, k[i + 2]); // fall through + case 2: + b = add(b, k[i + 1]); // fall through + case 1: + a = add(a, k[i + 0]); // fall through + finalHash(); + case 0: + break; + } + return c; } - switch(length) { - case 3 : c = add( c, k[i+2]); // fall through - case 2 : b = add( b, k[i+1]); // fall through - case 1 : a = add( a, k[i+0]); // fall through - finalHash(); - case 0: - break; + void finalHash() { + c = xor(c, b); + c = subtract(c, rot(b, 14)); + a = xor(a, c); + a = subtract(a, rot(c, 11)); + b = xor(b, a); + b = subtract(b, rot(a, 25)); + c = xor(c, b); + c = subtract(c, rot(b, 16)); + a = xor(a, c); + a = subtract(a, rot(c, 4)); + b = xor(b, a); + b = subtract(b, rot(a, 14)); + c = xor(c, b); + c = subtract(c, rot(b, 24)); } - return c; - } - - void finalHash(){ - c = xor(c, b); - c = subtract(c,rot(b,14) ); - a = xor(a, c); - a = subtract(a,rot(c,11) ); - b = xor(b,a); - b = subtract(b, rot(a,25)); - c = xor(c, b); - c = subtract(c,rot(b,16) ); - a = xor(a, c); - a = subtract(a,rot(c,4) ); - b = xor(b,a); - b = subtract(b, rot(a,14)); - c = xor(c, b); - c = subtract(c,rot(b,24) ); - } - + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/NotificationUtils.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/NotificationUtils.java index ea1565c..7580427 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/NotificationUtils.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/NotificationUtils.java @@ -1,7 +1,5 @@ package org.exobel.routerkeygen; -import org.exobel.routerkeygen.ui.NetworksListActivity; - import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; @@ -11,71 +9,73 @@ import android.support.v4.app.NotificationCompat; import android.widget.RemoteViews; +import org.exobel.routerkeygen.ui.NetworksListActivity; + public final class NotificationUtils { - public static NotificationCompat.Builder getSimple(Context context, - CharSequence title, CharSequence text) { - return new NotificationCompat.Builder(context) - .setSmallIcon(R.drawable.ic_notification).setTicker(title) - .setContentTitle(title).setContentText(text) - .setOnlyAlertOnce(true).setAutoCancel(true) - .setContentIntent(getDefaultPendingIntent(context)); - } + private NotificationUtils() { + } - @TargetApi(16) - public static Notification updateProgressBar(Notification update, int max, - int progress, boolean indeterminate) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) - update.contentView.setProgressBar(android.R.id.progress, max, - progress, indeterminate); - else - update.contentView.setProgressBar(R.id.progress, max, progress, - indeterminate); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) - update.bigContentView.setProgressBar(android.R.id.progress, max, - progress, indeterminate); - return update; - } + public static NotificationCompat.Builder getSimple(Context context, + CharSequence title, CharSequence text) { + return new NotificationCompat.Builder(context) + .setSmallIcon(R.drawable.ic_notification).setTicker(title) + .setContentTitle(title).setContentText(text) + .setOnlyAlertOnce(true).setAutoCancel(true) + .setContentIntent(getDefaultPendingIntent(context)); + } - public static Notification createProgressBar(Context context, - CharSequence title, CharSequence content, int max, int progress, - boolean indeterminate, PendingIntent i) { - final NotificationCompat.Builder builder = getSimple(context, title, - content); - builder.setContentIntent(i); - builder.setOngoing(true); - builder.setAutoCancel(false); - final Notification update; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - builder.setProgress(max, progress, indeterminate); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN - && !indeterminate) { - builder.addAction( - android.R.drawable.ic_menu_close_clear_cancel, - context.getString(android.R.string.cancel), i); - } - update = builder.build(); - } else { - RemoteViews contentView = new RemoteViews(context.getPackageName(), - R.layout.notification); - contentView.setTextViewText(R.id.text1, content); - contentView.setProgressBar(R.id.progress, max, progress, - indeterminate); - update = builder.build(); - update.contentView = contentView; - } - return update; - } + @TargetApi(16) + public static Notification updateProgressBar(Notification update, int max, + int progress, boolean indeterminate) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) + update.contentView.setProgressBar(android.R.id.progress, max, + progress, indeterminate); + else + update.contentView.setProgressBar(R.id.progress, max, progress, + indeterminate); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) + update.bigContentView.setProgressBar(android.R.id.progress, max, + progress, indeterminate); + return update; + } - public static PendingIntent getDefaultPendingIntent(Context context) { - return PendingIntent.getActivity(context, 0, new Intent(context, - NetworksListActivity.class) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), // add this - // pass null - // to intent - PendingIntent.FLAG_UPDATE_CURRENT); - } + public static Notification createProgressBar(Context context, + CharSequence title, CharSequence content, int max, int progress, + boolean indeterminate, PendingIntent i) { + final NotificationCompat.Builder builder = getSimple(context, title, + content); + builder.setContentIntent(i); + builder.setOngoing(true); + builder.setAutoCancel(false); + final Notification update; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + builder.setProgress(max, progress, indeterminate); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN + && !indeterminate) { + builder.addAction( + android.R.drawable.ic_menu_close_clear_cancel, + context.getString(android.R.string.cancel), i); + } + update = builder.build(); + } else { + RemoteViews contentView = new RemoteViews(context.getPackageName(), + R.layout.notification); + contentView.setTextViewText(R.id.text1, content); + contentView.setProgressBar(R.id.progress, max, progress, + indeterminate); + update = builder.build(); + update.contentView = contentView; + } + return update; + } - private NotificationUtils() { - } + public static PendingIntent getDefaultPendingIntent(Context context) { + return PendingIntent.getActivity(context, 0, new Intent(context, + NetworksListActivity.class) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), // add this + // pass null + // to intent + PendingIntent.FLAG_UPDATE_CURRENT); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RefreshHandler.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RefreshHandler.java index 9a65ee5..da70f64 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RefreshHandler.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RefreshHandler.java @@ -1,48 +1,40 @@ package org.exobel.routerkeygen; -import java.lang.ref.WeakReference; - import android.os.Handler; import com.millennialmedia.android.MMAdView; -public class RefreshHandler extends Handler -{ +import java.lang.ref.WeakReference; + +public class RefreshHandler extends Handler { private static final long TIME_TO_REFRESH_IN_MILLIS = 15000; private static final int MSG_REFRESH_BANNER = 4; private WeakReference mmAdViewRef; - public RefreshHandler(MMAdView adView) - { - mmAdViewRef = new WeakReference(adView); + public RefreshHandler(MMAdView adView) { + mmAdViewRef = new WeakReference<>(adView); } @Override - public void handleMessage(android.os.Message msg) - { - switch(msg.what) - { - case MSG_REFRESH_BANNER: - if(mmAdViewRef != null) - { - MMAdView adView = mmAdViewRef.get(); - if(adView != null) - { - adView.getAd(); - sendEmptyMessageDelayed(MSG_REFRESH_BANNER, TIME_TO_REFRESH_IN_MILLIS); + public void handleMessage(android.os.Message msg) { + switch (msg.what) { + case MSG_REFRESH_BANNER: + if (mmAdViewRef != null) { + MMAdView adView = mmAdViewRef.get(); + if (adView != null) { + adView.getAd(); + sendEmptyMessageDelayed(MSG_REFRESH_BANNER, TIME_TO_REFRESH_IN_MILLIS); + } } - } - break; + break; } - }; + } - public void onPause() - { + public void onPause() { removeMessages(MSG_REFRESH_BANNER); } - public void onResume() - { + public void onResume() { sendEmptyMessage(MSG_REFRESH_BANNER); } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RouterKeygenApplication.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RouterKeygenApplication.java index 56b9a55..f3039ce 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RouterKeygenApplication.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/RouterKeygenApplication.java @@ -1,13 +1,5 @@ package org.exobel.routerkeygen; -import org.acra.ACRA; -import org.acra.ReportField; -import org.acra.ReportingInteractionMode; -import org.acra.annotation.ReportsCrashes; -import org.exobel.routerkeygen.ui.NetworkActivity; -import org.exobel.routerkeygen.ui.NetworksListActivity; -import org.exobel.routerkeygen.ui.Preferences; - import android.annotation.TargetApi; import android.app.Application; import android.os.Build; @@ -17,56 +9,64 @@ import com.google.android.gms.analytics.Tracker; import com.millennialmedia.android.MMSDK; +import org.acra.ACRA; +import org.acra.ReportField; +import org.acra.ReportingInteractionMode; +import org.acra.annotation.ReportsCrashes; +import org.exobel.routerkeygen.ui.NetworkActivity; +import org.exobel.routerkeygen.ui.NetworksListActivity; +import org.exobel.routerkeygen.ui.Preferences; + @ReportsCrashes(mailTo = "exobel@gmail.com", customReportContent = { - ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, - ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, - ReportField.STACK_TRACE, ReportField.LOGCAT }, mode = ReportingInteractionMode.TOAST, resToastText = R.string.crash_toast_text) + ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, + ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, + ReportField.STACK_TRACE, ReportField.LOGCAT}, mode = ReportingInteractionMode.TOAST, resToastText = R.string.crash_toast_text) public class RouterKeygenApplication extends Application { - private Tracker tracker; - - public Tracker getTracker(){ - return tracker; - } + private Tracker tracker; + public Tracker getTracker() { + return tracker; + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public void onCreate() { - super.onCreate(); - try { + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + public void onCreate() { + super.onCreate(); + try { tracker = GoogleAnalytics.getInstance(this).newTracker(R.xml.analytics); tracker.enableAdvertisingIdCollection(true); - ACRA.init(this); - } catch (Exception e) { + ACRA.init(this); + } catch (Exception e) { - } - try { - MMSDK.initialize(this); - } catch (Exception e) {} - if (BuildConfig.DEBUG) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { - StrictMode - .setThreadPolicy(new StrictMode.ThreadPolicy.Builder() - .detectAll().penaltyLog().build()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() - .detectAll() - .penaltyLog() - .setClassInstanceLimit( - CancelOperationActivity.class, 2) - .setClassInstanceLimit(NetworksListActivity.class, - 2) - .setClassInstanceLimit(NetworkActivity.class, 2) - .setClassInstanceLimit(Preferences.class, 2) - .build()); - } else { - StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() - .detectLeakedSqlLiteObjects().penaltyLog().build()); + } + try { + MMSDK.initialize(this); + } catch (Exception e) { + } + if (BuildConfig.DEBUG) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { + StrictMode + .setThreadPolicy(new StrictMode.ThreadPolicy.Builder() + .detectAll().penaltyLog().build()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() + .detectAll() + .penaltyLog() + .setClassInstanceLimit( + CancelOperationActivity.class, 2) + .setClassInstanceLimit(NetworksListActivity.class, + 2) + .setClassInstanceLimit(NetworkActivity.class, 2) + .setClassInstanceLimit(Preferences.class, 2) + .build()); + } else { + StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() + .detectLeakedSqlLiteObjects().penaltyLog().build()); - } - } - } - } + } + } + } + } } \ No newline at end of file diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/UpdateCheckerService.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/UpdateCheckerService.java index 3de6ec5..02557b1 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/UpdateCheckerService.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/UpdateCheckerService.java @@ -1,14 +1,5 @@ package org.exobel.routerkeygen; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import org.exobel.routerkeygen.ui.Preferences; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; @@ -17,98 +8,106 @@ import android.net.Uri; import android.support.v4.app.NotificationCompat; -public class UpdateCheckerService extends IntentService { +import org.exobel.routerkeygen.ui.Preferences; +import org.json.JSONException; +import org.json.JSONObject; - private final static String URL_DOWNLOAD = "https://raw.githubusercontent.com/routerkeygen/routerkeygenAndroid/master/android/routerkeygen_version.json"; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; + +public class UpdateCheckerService extends IntentService { - public UpdateCheckerService() { - super("UpdateCheckerService"); - } + private final static String URL_DOWNLOAD = "https://raw.githubusercontent.com/routerkeygen/routerkeygenAndroid/master/android/routerkeygen_version.json"; + // Unique Identification Number for the Notification. + // We use it on Notification start, and to cancel it. + private final int UNIQUE_ID = R.string.app_name + + UpdateCheckerService.class.getName().hashCode(); - public static class LastVersion { - public String version; - public String url; - } + public UpdateCheckerService() { + super("UpdateCheckerService"); + } - // Unique Identification Number for the Notification. - // We use it on Notification start, and to cancel it. - private final int UNIQUE_ID = R.string.app_name - + UpdateCheckerService.class.getName().hashCode(); + public static LastVersion getLatestVersion() { + try { + final JSONObject version = getRemoteObjectAsJson(new URL( + URL_DOWNLOAD)); + if (version == null) { + return null; + } + final LastVersion lV = new LastVersion(); + lV.version = version.getString("version"); + lV.url = version.getString("url"); + return lV; + } catch (JSONException e) { + e.printStackTrace(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return null; + } - @Override - protected void onHandleIntent(Intent intent) { - NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - final LastVersion lastVersion = getLatestVersion(); - if (lastVersion == null) - return; - if (!Preferences.VERSION.equals(lastVersion.version)) { - final NotificationCompat.Builder builder = new NotificationCompat.Builder( - this) - .setSmallIcon(R.drawable.ic_notification) - .setTicker(getString(R.string.update_title)) - .setContentTitle(getString(R.string.update_title)) - .setContentText( - getString(R.string.update_notification, - lastVersion.version)) - .setOnlyAlertOnce(true) - .setAutoCancel(true) - .setContentIntent( - PendingIntent.getActivity(getApplicationContext(), - 0, - new Intent(Intent.ACTION_VIEW).setData(Uri - .parse(lastVersion.url)), - PendingIntent.FLAG_ONE_SHOT)); - mNotificationManager.notify(UNIQUE_ID, builder.build()); - } - } + private static JSONObject getRemoteObjectAsJson(URL url) { + InputStream inputStream = null; + try { + byte[] buffer = new byte[128]; + int read = 0; + String jsonAsString = new String(); - public static LastVersion getLatestVersion() { - try { - final JSONObject version = getRemoteObjectAsJson(new URL( - URL_DOWNLOAD)); - if (version == null) { - return null; - } - final LastVersion lV = new LastVersion(); - lV.version = version.getString("version"); - lV.url = version.getString("url"); - return lV; - } catch (JSONException e) { - e.printStackTrace(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - return null; - } + inputStream = url.openStream(); - private static JSONObject getRemoteObjectAsJson(URL url) { - InputStream inputStream = null; - try { - byte[] buffer = new byte[128]; - int read = 0; - String jsonAsString = new String(); + do { + read = inputStream.read(buffer); + if (read > 0) { + jsonAsString += new String(buffer, 0, read); + } + } while (read > -1); - inputStream = url.openStream(); + return new JSONObject(jsonAsString); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + if (inputStream != null) + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } - do { - read = inputStream.read(buffer); - if (read > 0) { - jsonAsString += new String(buffer, 0, read); - } - } while (read > -1); + } - return new JSONObject(jsonAsString); - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - if (inputStream != null) - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + @Override + protected void onHandleIntent(Intent intent) { + NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + final LastVersion lastVersion = getLatestVersion(); + if (lastVersion == null) + return; + if (!Preferences.VERSION.equals(lastVersion.version)) { + final NotificationCompat.Builder builder = new NotificationCompat.Builder( + this) + .setSmallIcon(R.drawable.ic_notification) + .setTicker(getString(R.string.update_title)) + .setContentTitle(getString(R.string.update_title)) + .setContentText( + getString(R.string.update_notification, + lastVersion.version)) + .setOnlyAlertOnce(true) + .setAutoCancel(true) + .setContentIntent( + PendingIntent.getActivity(getApplicationContext(), + 0, + new Intent(Intent.ACTION_VIEW).setData(Uri + .parse(lastVersion.url)), + PendingIntent.FLAG_ONE_SHOT)); + mNotificationManager.notify(UNIQUE_ID, builder.build()); + } + } - } + public static class LastVersion { + public String version; + public String url; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiScanReceiver.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiScanReceiver.java index e37b305..793533c 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiScanReceiver.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiScanReceiver.java @@ -18,15 +18,6 @@ */ package org.exobel.routerkeygen; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.zip.ZipInputStream; - -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; @@ -39,16 +30,20 @@ import android.os.Build; import android.widget.Toast; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.zip.ZipInputStream; + public class WifiScanReceiver extends BroadcastReceiver { final private OnScanListener[] scanListeners; final private WifiManager wifi; private KeygenMatcherTask task; - public interface OnScanListener { - - public void onScanFinished(WiFiNetwork[] networks); - } - public WifiScanReceiver(WifiManager wifi, OnScanListener... scanListener) { this.scanListeners = scanListener; this.wifi = wifi; @@ -58,7 +53,7 @@ public WifiScanReceiver(WifiManager wifi, OnScanListener... scanListener) { public void onReceive(Context context, Intent intent) { if (intent == null || !intent.getAction().equals( - WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) + WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) return; if (scanListeners == null) return; @@ -75,6 +70,7 @@ public void onReceive(Context context, Intent intent) { // Single scan context.unregisterReceiver(this); } catch (Exception e) { + e.printStackTrace(); } if (task == null || task.getStatus() == Status.FINISHED) { task = new KeygenMatcherTask(results, context); @@ -89,6 +85,11 @@ public void onReceive(Context context, Intent intent) { } } + public interface OnScanListener { + + void onScanFinished(WiFiNetwork[] networks); + } + private class KeygenMatcherTask extends AsyncTask { private final List results; @@ -112,7 +113,7 @@ protected void onPostExecute(WiFiNetwork[] networks) { @Override protected WiFiNetwork[] doInBackground(Void... params) { - final Set set = new TreeSet(); + final Set set = new TreeSet<>(); for (int i = 0; i < results.size() - 1; ++i) for (int j = i + 1; j < results.size(); ++j) if (results.get(i).SSID.equals(results.get(j).SSID)) @@ -125,11 +126,8 @@ protected WiFiNetwork[] doInBackground(Void... params) { magicInfo.close(); } catch (LinkageError e) { misbuiltAPK = true; - } catch (NotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + } catch (NotFoundException | IOException e) { + e.printStackTrace(); } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiStateReceiver.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiStateReceiver.java index 95974cf..7ae50ab 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiStateReceiver.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WifiStateReceiver.java @@ -18,38 +18,38 @@ */ package org.exobel.routerkeygen; -import org.exobel.routerkeygen.ui.MessagePublisher; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.WifiManager; +import org.exobel.routerkeygen.ui.MessagePublisher; + public class WifiStateReceiver extends BroadcastReceiver { - private final WifiManager wifi; - private final MessagePublisher messagePublisher; + private final WifiManager wifi; + private final MessagePublisher messagePublisher; - public WifiStateReceiver(WifiManager wifi, MessagePublisher messagePublisher) { - this.wifi = wifi; - this.messagePublisher = messagePublisher; - } + public WifiStateReceiver(WifiManager wifi, MessagePublisher messagePublisher) { + this.wifi = wifi; + this.messagePublisher = messagePublisher; + } - @Override - public void onReceive(Context context, Intent arg1) { - if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { - wifi.startScan(); - try { - context.unregisterReceiver(this); - } catch (Exception e) { - } + @Override + public void onReceive(Context context, Intent arg1) { + if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { + wifi.startScan(); + try { + context.unregisterReceiver(this); + } catch (Exception e) { + } - messagePublisher.setMessage(R.string.msg_scanstarted); - return; - } - if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING) { - messagePublisher.setMessage(R.string.msg_nowifi); - return; - } - } + messagePublisher.setMessage(R.string.msg_scanstarted); + return; + } + if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING) { + messagePublisher.setMessage(R.string.msg_nowifi); + return; + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WirelessMatcher.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WirelessMatcher.java index 2850dcd..3c97fd5 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WirelessMatcher.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/WirelessMatcher.java @@ -1,16 +1,9 @@ package org.exobel.routerkeygen; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - import org.exobel.routerkeygen.algorithms.AliceGermanyKeygen; import org.exobel.routerkeygen.algorithms.AliceItalyKeygen; import org.exobel.routerkeygen.algorithms.AndaredKeygen; +import org.exobel.routerkeygen.algorithms.ArcadyanKeygen; import org.exobel.routerkeygen.algorithms.ArnetPirelliKeygen; import org.exobel.routerkeygen.algorithms.AxtelKeygen; import org.exobel.routerkeygen.algorithms.BelkinKeygen; @@ -19,7 +12,6 @@ import org.exobel.routerkeygen.algorithms.ConnKeygen; import org.exobel.routerkeygen.algorithms.DiscusKeygen; import org.exobel.routerkeygen.algorithms.DlinkKeygen; -import org.exobel.routerkeygen.algorithms.ArcadyanKeygen; import org.exobel.routerkeygen.algorithms.EircomKeygen; import org.exobel.routerkeygen.algorithms.HuaweiKeygen; import org.exobel.routerkeygen.algorithms.InfostradaKeygen; @@ -54,348 +46,356 @@ import org.exobel.routerkeygen.config.TeleTuConfigParser; import org.exobel.routerkeygen.config.TeleTuMagicInfo; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + public class WirelessMatcher { - private static Map> supportedAlices = null; - private static Map> supportedTeletu = null; - private static String[] supportedOTE = null; - - public synchronized static ArrayList getKeygen(String ssid, - String mac, ZipInputStream magicInfo) { - final ArrayList keygens = new ArrayList(); - - if (ssid.matches("[aA]lice-[0-9]{8}")) { - if (supportedAlices == null) { - supportedAlices = AliceConfigParser.parse(getEntry("alice.txt", - magicInfo)); - } - final List supported = supportedAlices.get(ssid - .substring(6, 9)); - if (supported != null && supported.size() > 0) { - String macProcessed = mac.replace(":", "").toUpperCase( - Locale.getDefault()); - if (macProcessed.length() < 6 - || !macProcessed.substring(0, 6).equals( - supported.get(0).getMac())) { - macProcessed = supported.get(0).getMac(); - } else { - macProcessed = mac; - } - keygens.add(new AliceItalyKeygen(ssid, macProcessed, supported)); - } - } - if (mac.startsWith("00:1E:40") || mac.startsWith("00:25:5E")) - keygens.add(new AliceGermanyKeygen(ssid, mac)); - - if (ssid.equals("Andared")) - keygens.add(new AndaredKeygen(ssid, mac)); - - if (mac.startsWith("00:12:BF") || mac.startsWith("00:1A:2A") - || mac.startsWith("00:1D:19") || mac.startsWith("00:23:08") - || mac.startsWith("00:26:4D") || mac.startsWith("50:7E:5D") - || mac.startsWith("1C:C6:3C") || mac.startsWith("74:31:70") - || mac.startsWith("7C:4F:B5") || mac.startsWith("88:25:2C") - || mac.startsWith("7E:4F:B5")) - keygens.add(new ArcadyanKeygen(ssid, mac)); - - if (mac.startsWith("00:08:27") || mac.startsWith("00:13:C8") - || mac.startsWith("00:17:C2") || mac.startsWith("00:19:3E") - || mac.startsWith("00:1C:A2") || mac.startsWith("00:1D:8B") - || mac.startsWith("00:22:33") || mac.startsWith("00:23:8E") - || mac.startsWith("00:25:53") || mac.startsWith("00:8C:54") - || mac.startsWith("30:39:F2") || mac.startsWith("38:22:9D") - || mac.startsWith("64:87:D7") || mac.startsWith("74:88:8B") - || mac.startsWith("84:26:15") || mac.startsWith("A4:52:6F") - || mac.startsWith("A4:5D:A1") || mac.startsWith("D0:D4:12") - || mac.startsWith("D4:D1:84") || mac.startsWith("DC:0B:1A") - || mac.startsWith("F0:84:2F")) { - keygens.add(new ArnetPirelliKeygen(ssid, mac)); - keygens.add(new MeoPirelliKeygen(ssid, mac)); - } - - if (ssid.matches("(AXTEL|AXTEL-XTREMO)-[0-9a-fA-F]{4}")) { - final String ssidSubpart = ssid.substring(ssid.length() - 4); - final String macShort = mac.replace(":", ""); - if (macShort.length() < 12 - || ssidSubpart.equalsIgnoreCase(macShort.substring(8))) - keygens.add(new AxtelKeygen(ssid, mac)); - } - - if (ssid.matches("^(B|b)elkin(\\.|_)[0-9a-fA-F]{3,6}$") - || mac.startsWith("94:44:52") || mac.startsWith("08:86:3B") - || mac.startsWith("EC:1A:59")) - keygens.add(new BelkinKeygen(ssid, mac)); - - if (ssid.matches("Cabovisao-[0-9a-fA-F]{4}")) { - if (mac.length() == 0 || mac.startsWith("C0:AC:54")) - keygens.add(new CabovisaoSagemKeygen(ssid, mac)); - } - - if (ssid.equals("CONN-X")) - keygens.add(new ConnKeygen(ssid, mac)); - - if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { - if (mac.length() == 12) { - keygens.add(new ConnKeygen(ssid, mac)); - } - } - - if (ssid.matches("Discus--?[0-9a-fA-F]{6}")) - keygens.add(new DiscusKeygen(ssid, mac)); - - if (ssid.matches("(DL|dl)ink-[0-9a-fA-F]{6}") - || mac.startsWith("00:05:5D") || mac.startsWith("00:0D:88") - || mac.startsWith("00:0F:3D") || mac.startsWith("00:11:95") - || mac.startsWith("00:13:46") || mac.startsWith("00:15:E9") - || mac.startsWith("00:17:9A") || mac.startsWith("00:19:5B") - || mac.startsWith("00:1B:11") || mac.startsWith("00:1C:F0") - || mac.startsWith("00:1E:58") || mac.startsWith("00:21:91") - || mac.startsWith("00:22:B0") || mac.startsWith("00:24:01") - || mac.startsWith("00:26:5A") || mac.startsWith("14:D6:4D") - || mac.startsWith("1C:7E:E5") || mac.startsWith("28:10:7B") - || mac.startsWith("34:08:04") || mac.startsWith("5C:D9:98") - || mac.startsWith("84:C9:B2") || mac.startsWith("90:94:E4") - || mac.startsWith("AC:F1:DF") || mac.startsWith("B8:A3:86") - || mac.startsWith("BC:F6:85") || mac.startsWith("C8:BE:19") - || mac.startsWith("CC:B2:55") || mac.startsWith("F0:7D:68") - || mac.startsWith("FC:75:16")) - keygens.add(new DlinkKeygen(ssid, mac)); - - if (ssid.matches("[eE]ircom[0-7]{4} ?[0-7]{4}")) { - if (mac.length() == 0) { - final String filteredSsid = ssid.replace(" ", ""); - final String end = Integer - .toHexString(Integer.parseInt(filteredSsid - .substring(filteredSsid.length() - 8), 8) ^ 0x000fcc); - mac = "00:0F:CC" + ":" + end.substring(0, 2) + ":" - + end.substring(2, 4) + ":" + end.substring(4, 6); - } - keygens.add(new EircomKeygen(ssid, mac)); - } - - if (ssid.matches("INFINITUM[0-9a-zA-Z]{4}") - || (mac.startsWith("00:25:9E") || mac.startsWith("00:25:68") - || mac.startsWith("00:22:A1") - || mac.startsWith("00:1E:10") - || mac.startsWith("00:18:82") - || mac.startsWith("00:0F:F2") - || mac.startsWith("00:E0:FC") - || mac.startsWith("28:6E:D4") - || mac.startsWith("54:A5:1B") - || mac.startsWith("F4:C7:14") - || mac.startsWith("28:5F:DB") - || mac.startsWith("30:87:30") - || mac.startsWith("4C:54:99") - || mac.startsWith("40:4D:8E") - || mac.startsWith("64:16:F0") - || mac.startsWith("78:1D:BA") - || mac.startsWith("84:A8:E4") - || mac.startsWith("04:C0:6F") - || mac.startsWith("5C:4C:A9") - || mac.startsWith("1C:1D:67") - || mac.startsWith("CC:96:A0") || mac - .startsWith("20:2B:C1"))) - keygens.add(new HuaweiKeygen(ssid, mac)); - - if (ssid.matches("InfostradaWiFi-[0-9a-zA-Z]{6}")) - keygens.add(new InfostradaKeygen(ssid, mac)); - - if (ssid.startsWith("InterCable") - && (mac.startsWith("00:15") || mac.startsWith("00:1D"))) - keygens.add(new InterCableKeygen(ssid, mac)); - - if (ssid.matches("MAXCOM[0-9a-zA-Z]{4}")) - keygens.add(new MaxcomKeygen(ssid, mac)); - - if (ssid.matches("Megared[0-9a-fA-F]{4}")) { - // the final 4 characters of the SSID should match the final - if (mac.length() == 0 - || ssid.substring(ssid.length() - 4).equals( - mac.replace(":", "").substring(8))) - keygens.add(new MegaredKeygen(ssid, mac)); - } + private static Map> supportedAlices = null; + private static Map> supportedTeletu = null; + private static String[] supportedOTE = null; + + public synchronized static ArrayList getKeygen(String ssid, + String mac, ZipInputStream magicInfo) { + final ArrayList keygens = new ArrayList(); + + if (ssid.matches("[aA]lice-[0-9]{8}")) { + if (supportedAlices == null) { + supportedAlices = AliceConfigParser.parse(getEntry("alice.txt", + magicInfo)); + } + final List supported = supportedAlices.get(ssid + .substring(6, 9)); + if (supported != null && supported.size() > 0) { + String macProcessed = mac.replace(":", "").toUpperCase( + Locale.getDefault()); + if (macProcessed.length() < 6 + || !macProcessed.substring(0, 6).equals( + supported.get(0).getMac())) { + macProcessed = supported.get(0).getMac(); + } else { + macProcessed = mac; + } + keygens.add(new AliceItalyKeygen(ssid, macProcessed, supported)); + } + } + if (mac.startsWith("00:1E:40") || mac.startsWith("00:25:5E")) + keygens.add(new AliceGermanyKeygen(ssid, mac)); + + if (ssid.equals("Andared")) + keygens.add(new AndaredKeygen(ssid, mac)); + + if (mac.startsWith("00:12:BF") || mac.startsWith("00:1A:2A") + || mac.startsWith("00:1D:19") || mac.startsWith("00:23:08") + || mac.startsWith("00:26:4D") || mac.startsWith("50:7E:5D") + || mac.startsWith("1C:C6:3C") || mac.startsWith("74:31:70") + || mac.startsWith("7C:4F:B5") || mac.startsWith("88:25:2C") + || mac.startsWith("7E:4F:B5")) + keygens.add(new ArcadyanKeygen(ssid, mac)); + + if (mac.startsWith("00:08:27") || mac.startsWith("00:13:C8") + || mac.startsWith("00:17:C2") || mac.startsWith("00:19:3E") + || mac.startsWith("00:1C:A2") || mac.startsWith("00:1D:8B") + || mac.startsWith("00:22:33") || mac.startsWith("00:23:8E") + || mac.startsWith("00:25:53") || mac.startsWith("00:8C:54") + || mac.startsWith("30:39:F2") || mac.startsWith("38:22:9D") + || mac.startsWith("64:87:D7") || mac.startsWith("74:88:8B") + || mac.startsWith("84:26:15") || mac.startsWith("A4:52:6F") + || mac.startsWith("A4:5D:A1") || mac.startsWith("D0:D4:12") + || mac.startsWith("D4:D1:84") || mac.startsWith("DC:0B:1A") + || mac.startsWith("F0:84:2F")) { + keygens.add(new ArnetPirelliKeygen(ssid, mac)); + keygens.add(new MeoPirelliKeygen(ssid, mac)); + } + + if (ssid.matches("(AXTEL|AXTEL-XTREMO)-[0-9a-fA-F]{4}")) { + final String ssidSubpart = ssid.substring(ssid.length() - 4); + final String macShort = mac.replace(":", ""); + if (macShort.length() < 12 + || ssidSubpart.equalsIgnoreCase(macShort.substring(8))) + keygens.add(new AxtelKeygen(ssid, mac)); + } + + if (ssid.matches("^(B|b)elkin(\\.|_)[0-9a-fA-F]{3,6}$") + || mac.startsWith("94:44:52") || mac.startsWith("08:86:3B") + || mac.startsWith("EC:1A:59")) + keygens.add(new BelkinKeygen(ssid, mac)); + + if (ssid.matches("Cabovisao-[0-9a-fA-F]{4}")) { + if (mac.length() == 0 || mac.startsWith("C0:AC:54")) + keygens.add(new CabovisaoSagemKeygen(ssid, mac)); + } + + if (ssid.equals("CONN-X")) + keygens.add(new ConnKeygen(ssid, mac)); + + if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { + if (mac.length() == 12) { + keygens.add(new ConnKeygen(ssid, mac)); + } + } + + if (ssid.matches("Discus--?[0-9a-fA-F]{6}")) + keygens.add(new DiscusKeygen(ssid, mac)); + + if (ssid.matches("(DL|dl)ink-[0-9a-fA-F]{6}") + || mac.startsWith("00:05:5D") || mac.startsWith("00:0D:88") + || mac.startsWith("00:0F:3D") || mac.startsWith("00:11:95") + || mac.startsWith("00:13:46") || mac.startsWith("00:15:E9") + || mac.startsWith("00:17:9A") || mac.startsWith("00:19:5B") + || mac.startsWith("00:1B:11") || mac.startsWith("00:1C:F0") + || mac.startsWith("00:1E:58") || mac.startsWith("00:21:91") + || mac.startsWith("00:22:B0") || mac.startsWith("00:24:01") + || mac.startsWith("00:26:5A") || mac.startsWith("14:D6:4D") + || mac.startsWith("1C:7E:E5") || mac.startsWith("28:10:7B") + || mac.startsWith("34:08:04") || mac.startsWith("5C:D9:98") + || mac.startsWith("84:C9:B2") || mac.startsWith("90:94:E4") + || mac.startsWith("AC:F1:DF") || mac.startsWith("B8:A3:86") + || mac.startsWith("BC:F6:85") || mac.startsWith("C8:BE:19") + || mac.startsWith("CC:B2:55") || mac.startsWith("F0:7D:68") + || mac.startsWith("FC:75:16")) + keygens.add(new DlinkKeygen(ssid, mac)); + + if (ssid.matches("[eE]ircom[0-7]{4} ?[0-7]{4}")) { + if (mac.length() == 0) { + final String filteredSsid = ssid.replace(" ", ""); + final String end = Integer + .toHexString(Integer.parseInt(filteredSsid + .substring(filteredSsid.length() - 8), 8) ^ 0x000fcc); + mac = "00:0F:CC" + ":" + end.substring(0, 2) + ":" + + end.substring(2, 4) + ":" + end.substring(4, 6); + } + keygens.add(new EircomKeygen(ssid, mac)); + } + + if (ssid.matches("INFINITUM[0-9a-zA-Z]{4}") + || (mac.startsWith("00:25:9E") || mac.startsWith("00:25:68") + || mac.startsWith("00:22:A1") + || mac.startsWith("00:1E:10") + || mac.startsWith("00:18:82") + || mac.startsWith("00:0F:F2") + || mac.startsWith("00:E0:FC") + || mac.startsWith("28:6E:D4") + || mac.startsWith("54:A5:1B") + || mac.startsWith("F4:C7:14") + || mac.startsWith("28:5F:DB") + || mac.startsWith("30:87:30") + || mac.startsWith("4C:54:99") + || mac.startsWith("40:4D:8E") + || mac.startsWith("64:16:F0") + || mac.startsWith("78:1D:BA") + || mac.startsWith("84:A8:E4") + || mac.startsWith("04:C0:6F") + || mac.startsWith("5C:4C:A9") + || mac.startsWith("1C:1D:67") + || mac.startsWith("CC:96:A0") || mac + .startsWith("20:2B:C1"))) + keygens.add(new HuaweiKeygen(ssid, mac)); + + if (ssid.matches("InfostradaWiFi-[0-9a-zA-Z]{6}")) + keygens.add(new InfostradaKeygen(ssid, mac)); + + if (ssid.startsWith("InterCable") + && (mac.startsWith("00:15") || mac.startsWith("00:1D"))) + keygens.add(new InterCableKeygen(ssid, mac)); + + if (ssid.matches("MAXCOM[0-9a-zA-Z]{4}")) + keygens.add(new MaxcomKeygen(ssid, mac)); + + if (ssid.matches("Megared[0-9a-fA-F]{4}")) { + // the final 4 characters of the SSID should match the final + if (mac.length() == 0 + || ssid.substring(ssid.length() - 4).equals( + mac.replace(":", "").substring(8))) + keygens.add(new MegaredKeygen(ssid, mac)); + } /* ssid must be of the form P1XXXXXX0000X or p1XXXXXX0000X */ - if (ssid.matches("[Pp]1[0-9]{6}0{4}[0-9]")) - keygens.add(new OnoKeygen(ssid, mac)); + if (ssid.matches("[Pp]1[0-9]{6}0{4}[0-9]")) + keygens.add(new OnoKeygen(ssid, mac)); - if (ssid.matches("OTE[0-9a-fA-F]{4}") && (mac.startsWith("00:13:33"))) - keygens.add(new OteBAUDKeygen(ssid, mac)); + if (ssid.matches("OTE[0-9a-fA-F]{4}") && (mac.startsWith("00:13:33"))) + keygens.add(new OteBAUDKeygen(ssid, mac)); - if (ssid.matches("OTE[0-9a-fA-F]{6}")) - /* - * && ((mac.startsWith("C8:7B:5B")) || (mac.startsWith("FC:C8:97")) + if (ssid.matches("OTE[0-9a-fA-F]{6}")) + /* + * && ((mac.startsWith("C8:7B:5B")) || (mac.startsWith("FC:C8:97")) * || (mac.startsWith("68:1A:B2")) || (mac.startsWith("B0:75:D5")) * || (mac .startsWith("38:46:08")))) */ - keygens.add(new OteKeygen(ssid, mac)); - - if (ssid.toUpperCase(Locale.getDefault()).startsWith("OTE") - && (mac.startsWith("E8:39:DF:F5") - || mac.startsWith("E8:39:DF:F6") || mac - .startsWith("E8:39:DF:FD"))) { - if (supportedOTE == null) { - supportedOTE = OTEHuaweiConfigParser.parse(getEntry( - "ote_huawei.txt", magicInfo)); - } - final String filteredMac = mac.replace(":", ""); - final int target = Integer.parseInt(filteredMac.substring(8), 16); - if (filteredMac.length() == 12 - && target > (OteHuaweiKeygen.MAGIC_NUMBER - supportedOTE.length)) - keygens.add(new OteHuaweiKeygen(ssid, mac, - supportedOTE[OteHuaweiKeygen.MAGIC_NUMBER - target])); - } - - if (ssid.matches("PBS-[0-9a-fA-F]{6}") || mac.startsWith("00:08:27") - || mac.startsWith("00:13:C8") || mac.startsWith("00:17:C2") - || mac.startsWith("00:19:3E") || mac.startsWith("00:1C:A2") - || mac.startsWith("00:1D:8B") || mac.startsWith("00:22:33") - || mac.startsWith("00:23:8E") || mac.startsWith("00:25:53") - || mac.startsWith("30:39:F2") || mac.startsWith("38:22:9D") - || mac.startsWith("64:87:D7") || mac.startsWith("74:88:8B") - || mac.startsWith("A4:52:6F") || mac.startsWith("D4:D1:84")) - keygens.add(new PBSKeygen(ssid, mac)); - - if (ssid.matches("FASTWEB-1-(000827|0013C8|0017C2|00193E|001CA2|001D8B|" - + "002233|00238E|002553|00A02F|080018|3039F2|38229D|6487D7)[0-9A-Fa-f]{6}")) { - if (mac.length() == 0) { - final String end = ssid.substring(ssid.length() - 12); - mac = end.substring(0, 2) + ":" + end.substring(2, 4) + ":" - + end.substring(4, 6) + ":" + end.substring(6, 8) + ":" - + end.substring(8, 10) + ":" + end.substring(10, 12); - } - keygens.add(new PirelliKeygen(ssid, mac)); - } - - if (ssid.matches("(PTV-|ptv|ptv-)[0-9a-zA-Z]{6}")) - keygens.add(new PtvKeygen(ssid, mac)); - - if (mac.startsWith("00:0C:F6")) - keygens.add(new SitecomKeygen(ssid, mac)); - - if (ssid.matches("SKY[0-9]{5}") - && (mac.startsWith("C4:3D:C7") || mac.startsWith("E0:46:9A") - || mac.startsWith("E0:91:F5") - || mac.startsWith("00:09:5B") - || mac.startsWith("00:0F:B5") - || mac.startsWith("00:14:6C") - || mac.startsWith("00:18:4D") - || mac.startsWith("00:26:F2") - || mac.startsWith("C0:3F:0E") - || mac.startsWith("30:46:9A") - || mac.startsWith("00:1B:2F") - || mac.startsWith("A0:21:B7") - || mac.startsWith("00:1E:2A") - || mac.startsWith("00:1F:33") - || mac.startsWith("00:22:3F") || mac - .startsWith("00:24:B2"))) - keygens.add(new SkyV1Keygen(ssid, mac)); - - if (ssid.matches("WLAN-[0-9a-fA-F]{6}") - && (mac.startsWith("00:12:BF") || mac.startsWith("00:1A:2A") || mac - .startsWith("00:1D:19"))) - keygens.add(new Speedport500Keygen(ssid, mac)); - - if (ssid.matches("TECOM-AH4(021|222)-[0-9a-zA-Z]{6}")) - keygens.add(new TecomKeygen(ssid, mac)); - - if (ssid.toLowerCase(Locale.getDefault()).startsWith("teletu")) { - if (supportedTeletu == null) { - supportedTeletu = TeleTuConfigParser.parse(getEntry( - "tele2.txt", magicInfo)); - } - String filteredMac = mac.replace(":", ""); - if (filteredMac.length() != 12 - && ssid.matches("TeleTu_[0-9a-fA-F]{12}")) - mac = filteredMac = ssid.substring(7); - if (filteredMac.length() == 12) { - final List supported = supportedTeletu - .get(filteredMac.substring(0, 6)); - if (supported != null && supported.size() > 0) { - final int macIntValue = Integer.parseInt( - filteredMac.substring(6), 16); - for (TeleTuMagicInfo magic : supported) { - if (macIntValue >= magic.getRange()[0] - && macIntValue <= magic.getRange()[1]) { - keygens.add(new TeleTuKeygen(ssid, mac, magic)); - } - } - } - } - } - - if (ssid.matches("FASTWEB-(1|2)-(002196|00036F)[0-9A-Fa-f]{6}")) { - if (mac.length() == 0) { - final String end = ssid.substring(ssid.length() - 12); - mac = end.substring(0, 2) + ":" + end.substring(2, 4) + ":" - + end.substring(4, 6) + ":" + end.substring(6, 8) + ":" - + end.substring(8, 10) + ":" + end.substring(10, 12); - } - keygens.add(new TelseyKeygen(ssid, mac)); - } - - if (ssid.matches("(Thomson|Blink|SpeedTouch|O2Wireless|O2wireless|Orange-|ORANGE-|INFINITUM|" - + "BigPond|Otenet|Bbox-|DMAX|privat|TN_private_|CYTA|Vodafone-|Optimus|OptimusFibra|MEO-)[0-9a-fA-F]{6}")) - keygens.add(new ThomsonKeygen(ssid, mac)); - - if (mac.startsWith("F8:D1:11")) - keygens.add(new TplinkKeygen(ssid, mac)); - - if (ssid.length() == 5 - && (mac.startsWith("00:1F:90") || mac.startsWith("A8:39:44") - || mac.startsWith("00:18:01") - || mac.startsWith("00:20:E0") - || mac.startsWith("00:0F:B3") - || mac.startsWith("00:1E:A7") - || mac.startsWith("00:15:05") - || mac.startsWith("00:24:7B") - || mac.startsWith("00:26:62") || mac - .startsWith("00:26:B8"))) - keygens.add(new VerizonKeygen(ssid, mac)); - - if (ssid.matches("wifimedia_R-[0-9a-zA-Z]{4}") - && mac.replace(":", "").length() == 12) - keygens.add(new WifimediaRKeygen(ssid, mac)); - - if (ssid.matches("WLAN_[0-9a-fA-F]{2}") - && (mac.startsWith("00:01:38") || mac.startsWith("00:16:38") - || mac.startsWith("00:01:13") - || mac.startsWith("00:01:1B") || mac - .startsWith("00:19:5B"))) - keygens.add(new Wlan2Keygen(ssid, mac)); - - if (ssid.matches("(WLAN|WiFi|YaCom)[0-9a-zA-Z]{6}")) - keygens.add(new Wlan6Keygen(ssid, mac)); - - if (ssid.matches("(WLAN|JAZZTEL)_[0-9a-fA-F]{4}")) { - if (mac.startsWith("00:1F:A4") || mac.startsWith("F4:3E:61") - || mac.startsWith("40:4A:03")) - keygens.add(new ZyxelKeygen(ssid, mac)); - - if (mac.startsWith("00:1B:20") || mac.startsWith("64:68:0C") - || mac.startsWith("00:1D:20") || mac.startsWith("00:23:F8") - || mac.startsWith("38:72:C0") || mac.startsWith("30:39:F2") - || mac.startsWith("8C:0C:A3") || mac.startsWith("5C:33:8E") - || mac.startsWith("C8:6C:87") || mac.startsWith("D0:AE:EC") - || mac.startsWith("00:19:15") || mac.startsWith("00:1A:2B")) - keygens.add(new ComtrendKeygen(ssid, mac)); - } - - return keygens; - } - - private static InputStream getEntry(String filename, - ZipInputStream magicInfo) { - ZipEntry entry = null; - try { - do { - entry = magicInfo.getNextEntry(); - } while (entry != null && !filename.equals(entry.getName())); - } catch (Exception e) { - e.printStackTrace(); - } - if (entry != null) - return magicInfo; - return null; - } + keygens.add(new OteKeygen(ssid, mac)); + + if (ssid.toUpperCase(Locale.getDefault()).startsWith("OTE") + && (mac.startsWith("E8:39:DF:F5") + || mac.startsWith("E8:39:DF:F6") || mac + .startsWith("E8:39:DF:FD"))) { + if (supportedOTE == null) { + supportedOTE = OTEHuaweiConfigParser.parse(getEntry( + "ote_huawei.txt", magicInfo)); + } + final String filteredMac = mac.replace(":", ""); + final int target = Integer.parseInt(filteredMac.substring(8), 16); + if (filteredMac.length() == 12 + && target > (OteHuaweiKeygen.MAGIC_NUMBER - supportedOTE.length)) + keygens.add(new OteHuaweiKeygen(ssid, mac, + supportedOTE[OteHuaweiKeygen.MAGIC_NUMBER - target])); + } + + if (ssid.matches("PBS-[0-9a-fA-F]{6}") || mac.startsWith("00:08:27") + || mac.startsWith("00:13:C8") || mac.startsWith("00:17:C2") + || mac.startsWith("00:19:3E") || mac.startsWith("00:1C:A2") + || mac.startsWith("00:1D:8B") || mac.startsWith("00:22:33") + || mac.startsWith("00:23:8E") || mac.startsWith("00:25:53") + || mac.startsWith("30:39:F2") || mac.startsWith("38:22:9D") + || mac.startsWith("64:87:D7") || mac.startsWith("74:88:8B") + || mac.startsWith("A4:52:6F") || mac.startsWith("D4:D1:84")) + keygens.add(new PBSKeygen(ssid, mac)); + + if (ssid.matches("FASTWEB-1-(000827|0013C8|0017C2|00193E|001CA2|001D8B|" + + "002233|00238E|002553|00A02F|080018|3039F2|38229D|6487D7)[0-9A-Fa-f]{6}")) { + if (mac.length() == 0) { + final String end = ssid.substring(ssid.length() - 12); + mac = end.substring(0, 2) + ":" + end.substring(2, 4) + ":" + + end.substring(4, 6) + ":" + end.substring(6, 8) + ":" + + end.substring(8, 10) + ":" + end.substring(10, 12); + } + keygens.add(new PirelliKeygen(ssid, mac)); + } + + if (ssid.matches("(PTV-|ptv|ptv-)[0-9a-zA-Z]{6}")) + keygens.add(new PtvKeygen(ssid, mac)); + + if (mac.startsWith("00:0C:F6")) + keygens.add(new SitecomKeygen(ssid, mac)); + + if (ssid.matches("SKY[0-9]{5}") + && (mac.startsWith("C4:3D:C7") || mac.startsWith("E0:46:9A") + || mac.startsWith("E0:91:F5") + || mac.startsWith("00:09:5B") + || mac.startsWith("00:0F:B5") + || mac.startsWith("00:14:6C") + || mac.startsWith("00:18:4D") + || mac.startsWith("00:26:F2") + || mac.startsWith("C0:3F:0E") + || mac.startsWith("30:46:9A") + || mac.startsWith("00:1B:2F") + || mac.startsWith("A0:21:B7") + || mac.startsWith("00:1E:2A") + || mac.startsWith("00:1F:33") + || mac.startsWith("00:22:3F") || mac + .startsWith("00:24:B2"))) + keygens.add(new SkyV1Keygen(ssid, mac)); + + if (ssid.matches("WLAN-[0-9a-fA-F]{6}") + && (mac.startsWith("00:12:BF") || mac.startsWith("00:1A:2A") || mac + .startsWith("00:1D:19"))) + keygens.add(new Speedport500Keygen(ssid, mac)); + + if (ssid.matches("TECOM-AH4(021|222)-[0-9a-zA-Z]{6}")) + keygens.add(new TecomKeygen(ssid, mac)); + + if (ssid.toLowerCase(Locale.getDefault()).startsWith("teletu")) { + if (supportedTeletu == null) { + supportedTeletu = TeleTuConfigParser.parse(getEntry( + "tele2.txt", magicInfo)); + } + String filteredMac = mac.replace(":", ""); + if (filteredMac.length() != 12 + && ssid.matches("TeleTu_[0-9a-fA-F]{12}")) + mac = filteredMac = ssid.substring(7); + if (filteredMac.length() == 12) { + final List supported = supportedTeletu + .get(filteredMac.substring(0, 6)); + if (supported != null && supported.size() > 0) { + final int macIntValue = Integer.parseInt( + filteredMac.substring(6), 16); + for (TeleTuMagicInfo magic : supported) { + if (macIntValue >= magic.getRange()[0] + && macIntValue <= magic.getRange()[1]) { + keygens.add(new TeleTuKeygen(ssid, mac, magic)); + } + } + } + } + } + + if (ssid.matches("FASTWEB-(1|2)-(002196|00036F)[0-9A-Fa-f]{6}")) { + if (mac.length() == 0) { + final String end = ssid.substring(ssid.length() - 12); + mac = end.substring(0, 2) + ":" + end.substring(2, 4) + ":" + + end.substring(4, 6) + ":" + end.substring(6, 8) + ":" + + end.substring(8, 10) + ":" + end.substring(10, 12); + } + keygens.add(new TelseyKeygen(ssid, mac)); + } + + if (ssid.matches("(Thomson|Blink|SpeedTouch|O2Wireless|O2wireless|Orange-|ORANGE-|INFINITUM|" + + "BigPond|Otenet|Bbox-|DMAX|privat|TN_private_|CYTA|Vodafone-|Optimus|OptimusFibra|MEO-)[0-9a-fA-F]{6}")) + keygens.add(new ThomsonKeygen(ssid, mac)); + + if (mac.startsWith("F8:D1:11")) + keygens.add(new TplinkKeygen(ssid, mac)); + + if (ssid.length() == 5 + && (mac.startsWith("00:1F:90") || mac.startsWith("A8:39:44") + || mac.startsWith("00:18:01") + || mac.startsWith("00:20:E0") + || mac.startsWith("00:0F:B3") + || mac.startsWith("00:1E:A7") + || mac.startsWith("00:15:05") + || mac.startsWith("00:24:7B") + || mac.startsWith("00:26:62") || mac + .startsWith("00:26:B8"))) + keygens.add(new VerizonKeygen(ssid, mac)); + + if (ssid.matches("wifimedia_R-[0-9a-zA-Z]{4}") + && mac.replace(":", "").length() == 12) + keygens.add(new WifimediaRKeygen(ssid, mac)); + + if (ssid.matches("WLAN_[0-9a-fA-F]{2}") + && (mac.startsWith("00:01:38") || mac.startsWith("00:16:38") + || mac.startsWith("00:01:13") + || mac.startsWith("00:01:1B") || mac + .startsWith("00:19:5B"))) + keygens.add(new Wlan2Keygen(ssid, mac)); + + if (ssid.matches("(WLAN|WiFi|YaCom)[0-9a-zA-Z]{6}")) + keygens.add(new Wlan6Keygen(ssid, mac)); + + if (ssid.matches("(WLAN|JAZZTEL)_[0-9a-fA-F]{4}")) { + if (mac.startsWith("00:1F:A4") || mac.startsWith("F4:3E:61") + || mac.startsWith("40:4A:03")) + keygens.add(new ZyxelKeygen(ssid, mac)); + + if (mac.startsWith("00:1B:20") || mac.startsWith("64:68:0C") + || mac.startsWith("00:1D:20") || mac.startsWith("00:23:F8") + || mac.startsWith("38:72:C0") || mac.startsWith("30:39:F2") + || mac.startsWith("8C:0C:A3") || mac.startsWith("5C:33:8E") + || mac.startsWith("C8:6C:87") || mac.startsWith("D0:AE:EC") + || mac.startsWith("00:19:15") || mac.startsWith("00:1A:2B")) + keygens.add(new ComtrendKeygen(ssid, mac)); + } + + return keygens; + } + + private static InputStream getEntry(String filename, + ZipInputStream magicInfo) { + ZipEntry entry = null; + try { + do { + entry = magicInfo.getNextEntry(); + } while (entry != null && !filename.equals(entry.getName())); + } catch (Exception e) { + e.printStackTrace(); + } + if (entry != null) + return magicInfo; + return null; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceGermanyKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceGermanyKeygen.java index f4deb1d..a214fea 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceGermanyKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceGermanyKeygen.java @@ -18,84 +18,83 @@ */ package org.exobel.routerkeygen.algorithms; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.Base64; import org.exobel.routerkeygen.R; import org.exobel.routerkeygen.utils.StringUtils; -import android.os.Parcel; -import android.os.Parcelable; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Locale; /** * The algortihm is described on the link below * Link:http://www.wardriving-forum.de/wiki/Standardpassw%C3%B6rter#ALICE - * + * * @author Rui Araújo - * */ public class AliceGermanyKeygen extends Keygen { - public AliceGermanyKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AliceGermanyKeygen createFromParcel(Parcel in) { + return new AliceGermanyKeygen(in); + } - @Override - public int getSupportState() { - if (getSsidName().matches("ALICE-WLAN[0-9a-fA-F]{2}")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } + public AliceGermanyKeygen[] newArray(int size) { + return new AliceGermanyKeygen[size]; + } + }; - @Override - public List getKeys() { - MessageDigest md; - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - try { - int macEthInt = Integer.parseInt(mac.substring(6), 16) - 1; - if (macEthInt < 0) - macEthInt = 0xFFFFFF; - String macEth = Integer.toHexString(macEthInt); - while (macEth.length() < 6) - macEth = "0" + macEth; - macEth = mac.substring(0, 6) + macEth; - md.reset(); - md.update(macEth.toLowerCase(Locale.getDefault()).getBytes("ASCII")); - final byte[] hash = StringUtils.getHexString(md.digest()) - .substring(0, 12).getBytes("ASCII"); - addPassword(Base64.encodeToString(hash, Base64.DEFAULT).trim()); - return getResults(); - } catch (UnsupportedEncodingException e) { - } - return null; - } + public AliceGermanyKeygen(String ssid, String mac) { + super(ssid, mac); + } - private AliceGermanyKeygen(Parcel in) { - super(in); - } + private AliceGermanyKeygen(Parcel in) { + super(in); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public AliceGermanyKeygen createFromParcel(Parcel in) { - return new AliceGermanyKeygen(in); - } + @Override + public int getSupportState() { + if (getSsidName().matches("ALICE-WLAN[0-9a-fA-F]{2}")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - public AliceGermanyKeygen[] newArray(int size) { - return new AliceGermanyKeygen[size]; - } - }; + @Override + public List getKeys() { + MessageDigest md; + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + try { + int macEthInt = Integer.parseInt(mac.substring(6), 16) - 1; + if (macEthInt < 0) + macEthInt = 0xFFFFFF; + String macEth = Integer.toHexString(macEthInt); + while (macEth.length() < 6) + macEth = "0" + macEth; + macEth = mac.substring(0, 6) + macEth; + md.reset(); + md.update(macEth.toLowerCase(Locale.getDefault()).getBytes("ASCII")); + final byte[] hash = StringUtils.getHexString(md.digest()) + .substring(0, 12).getBytes("ASCII"); + addPassword(Base64.encodeToString(hash, Base64.DEFAULT).trim()); + return getResults(); + } catch (UnsupportedEncodingException e) { + } + return null; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceItalyKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceItalyKeygen.java index bdf301e..d07cf04 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceItalyKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AliceItalyKeygen.java @@ -18,146 +18,143 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.config.AliceMagicInfo; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Locale; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.config.AliceMagicInfo; - -import android.os.Parcel; -import android.os.Parcelable; - public class AliceItalyKeygen extends Keygen { - private MessageDigest md; - final private String ssidIdentifier; - final private List supportedAlice; - - public AliceItalyKeygen(String ssid, String mac, - List supportedAlice) { - super(ssid, mac); - this.ssidIdentifier = ssid.substring(ssid.length() - 8); - this.supportedAlice = supportedAlice; - } - - final static private String preInitCharset = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvWxyz0123"; - - public final static byte ALICE_SEED[/* 32 */] = { 0x64, (byte) 0xC6, - (byte) 0xDD, (byte) 0xE3, (byte) 0xE5, 0x79, (byte) 0xB6, - (byte) 0xD9, (byte) 0x86, (byte) 0x96, (byte) 0x8D, 0x34, 0x45, - (byte) 0xD2, 0x3B, 0x15, (byte) 0xCA, (byte) 0xAF, 0x12, - (byte) 0x84, 0x02, (byte) 0xAC, 0x56, 0x00, 0x05, (byte) 0xCE, - 0x20, 0x75, (byte) 0x91, 0x3F, (byte) 0xDC, (byte) 0xE8 }; - - @Override - public List getKeys() { - if (supportedAlice == null || supportedAlice.isEmpty()) { - setErrorCode(R.string.msg_erralicenotsupported); - return null; - } - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha256); - return null; - } - for (int j = 0; j < supportedAlice.size(); ++j) {/* For pre AGPF 4.5.0sx */ - String serialStr = supportedAlice.get(j).getSerial() + "X"; - int k = supportedAlice.get(j).getMagic()[0]; - int Q = supportedAlice.get(j).getMagic()[1]; - int serial = (Integer.valueOf(ssidIdentifier) - Q) / k; - String tmp = Integer.toString(serial); - for (int i = 0; i < 7 - tmp.length(); i++) { - serialStr += "0"; - } - serialStr += tmp; - - byte[] mac = new byte[6]; - String key = ""; - byte[] hash; - - if (getMacAddress().length() == 12) { - - for (int i = 0; i < 12; i += 2) - mac[i / 2] = (byte) ((Character.digit(getMacAddress() - .charAt(i), 16) << 4) + Character.digit( - getMacAddress().charAt(i + 1), 16)); - - md.reset(); - md.update(ALICE_SEED); - try { - md.update(serialStr.getBytes("ASCII")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - md.update(mac); - hash = md.digest(); - for (int i = 0; i < 24; ++i) { - key += preInitCharset.charAt(hash[i] & 0xFF); - } - addPassword(key); - } + public final static byte ALICE_SEED[/* 32 */] = {0x64, (byte) 0xC6, + (byte) 0xDD, (byte) 0xE3, (byte) 0xE5, 0x79, (byte) 0xB6, + (byte) 0xD9, (byte) 0x86, (byte) 0x96, (byte) 0x8D, 0x34, 0x45, + (byte) 0xD2, 0x3B, 0x15, (byte) 0xCA, (byte) 0xAF, 0x12, + (byte) 0x84, 0x02, (byte) 0xAC, 0x56, 0x00, 0x05, (byte) 0xCE, + 0x20, 0x75, (byte) 0x91, 0x3F, (byte) 0xDC, (byte) 0xE8}; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AliceItalyKeygen createFromParcel(Parcel in) { + return new AliceItalyKeygen(in); + } + + public AliceItalyKeygen[] newArray(int size) { + return new AliceItalyKeygen[size]; + } + }; + final static private String preInitCharset = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvWxyz0123"; + final private String ssidIdentifier; + final private List supportedAlice; + private MessageDigest md; + + public AliceItalyKeygen(String ssid, String mac, + List supportedAlice) { + super(ssid, mac); + this.ssidIdentifier = ssid.substring(ssid.length() - 8); + this.supportedAlice = supportedAlice; + } + + @SuppressWarnings("unchecked") + private AliceItalyKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + supportedAlice = in + .readArrayList(AliceMagicInfo.class.getClassLoader()); + } + + @Override + public List getKeys() { + if (supportedAlice == null || supportedAlice.isEmpty()) { + setErrorCode(R.string.msg_erralicenotsupported); + return null; + } + try { + md = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha256); + return null; + } + for (int j = 0; j < supportedAlice.size(); ++j) {/* For pre AGPF 4.5.0sx */ + String serialStr = supportedAlice.get(j).getSerial() + "X"; + int k = supportedAlice.get(j).getMagic()[0]; + int Q = supportedAlice.get(j).getMagic()[1]; + int serial = (Integer.valueOf(ssidIdentifier) - Q) / k; + String tmp = Integer.toString(serial); + for (int i = 0; i < 7 - tmp.length(); i++) { + serialStr += "0"; + } + serialStr += tmp; + + byte[] mac = new byte[6]; + String key = ""; + byte[] hash; + + if (getMacAddress().length() == 12) { + + for (int i = 0; i < 12; i += 2) + mac[i / 2] = (byte) ((Character.digit(getMacAddress() + .charAt(i), 16) << 4) + Character.digit( + getMacAddress().charAt(i + 1), 16)); + + md.reset(); + md.update(ALICE_SEED); + try { + md.update(serialStr.getBytes("ASCII")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + md.update(mac); + hash = md.digest(); + for (int i = 0; i < 24; ++i) { + key += preInitCharset.charAt(hash[i] & 0xFF); + } + addPassword(key); + } /* For post AGPF 4.5.0sx */ - String macEth = getMacAddress().substring(0, 6); - - for (int extraNumber = 0; extraNumber < 10; extraNumber++) { - String calc = Integer.toHexString( - Integer.valueOf(extraNumber + ssidIdentifier)) - .toUpperCase(Locale.getDefault()); - if (macEth.charAt(5) == calc.charAt(0)) { - macEth += calc.substring(1); - break; - } - } - if (macEth.equals(getMacAddress().substring(0, 6))) { - continue; - } - for (int i = 0; i < 12; i += 2) - mac[i / 2] = (byte) ((Character.digit(macEth.charAt(i), 16) << 4) + Character - .digit(macEth.charAt(i + 1), 16)); - md.reset(); - md.update(ALICE_SEED); - try { - md.update(serialStr.getBytes("ASCII")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - md.update(mac); - key = ""; - hash = md.digest(); - for (int i = 0; i < 24; ++i) - key += preInitCharset.charAt(hash[i] & 0xFF); - addPassword(key); - } - return getResults(); - } - - @SuppressWarnings("unchecked") - private AliceItalyKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - supportedAlice = in - .readArrayList(AliceMagicInfo.class.getClassLoader()); - } - - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - dest.writeList(supportedAlice); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public AliceItalyKeygen createFromParcel(Parcel in) { - return new AliceItalyKeygen(in); - } - - public AliceItalyKeygen[] newArray(int size) { - return new AliceItalyKeygen[size]; - } - }; + String macEth = getMacAddress().substring(0, 6); + + for (int extraNumber = 0; extraNumber < 10; extraNumber++) { + String calc = Integer.toHexString( + Integer.valueOf(extraNumber + ssidIdentifier)) + .toUpperCase(Locale.getDefault()); + if (macEth.charAt(5) == calc.charAt(0)) { + macEth += calc.substring(1); + break; + } + } + if (macEth.equals(getMacAddress().substring(0, 6))) { + continue; + } + for (int i = 0; i < 12; i += 2) + mac[i / 2] = (byte) ((Character.digit(macEth.charAt(i), 16) << 4) + Character + .digit(macEth.charAt(i + 1), 16)); + md.reset(); + md.update(ALICE_SEED); + try { + md.update(serialStr.getBytes("ASCII")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + md.update(mac); + key = ""; + hash = md.digest(); + for (int i = 0; i < 24; ++i) + key += preInitCharset.charAt(hash[i] & 0xFF); + addPassword(key); + } + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + dest.writeList(supportedAlice); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AndaredKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AndaredKeygen.java index 27ca0ac..71dab61 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AndaredKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AndaredKeygen.java @@ -18,31 +18,17 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; - import android.os.Parcel; import android.os.Parcelable; +import java.util.List; + /* * This is not actual an algorithm as * it is just a default WPA password. */ public class AndaredKeygen extends Keygen { - public AndaredKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - addPassword("6b629f4c299371737494c61b5a101693a2d4e9e1f3e1320f3ebf9ae379cecf32"); - return getResults(); - } - - private AndaredKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public AndaredKeygen createFromParcel(Parcel in) { return new AndaredKeygen(in); @@ -52,6 +38,20 @@ public AndaredKeygen[] newArray(int size) { return new AndaredKeygen[size]; } }; - + + public AndaredKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private AndaredKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + addPassword("6b629f4c299371737494c61b5a101693a2d4e9e1f3e1320f3ebf9ae379cecf32"); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArcadyanKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArcadyanKeygen.java index 607a289..e03d246 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArcadyanKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArcadyanKeygen.java @@ -1,98 +1,98 @@ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; public class ArcadyanKeygen extends Keygen { - public ArcadyanKeygen(String ssid, String mac) { - super(ssid, mac); - } - - @Override - public int getSupportState() { - if (getSsidName().matches( - "(Arcor|EasyBox|Vodafone|WLAN)(-| )[0-9a-fA-F]{6}") - || getSsidName().matches("Vodafone[0-9a-zA-Z]{4}")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } - - @Override - public List getKeys() { - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - String C1 = Integer.toString(Integer.parseInt(mac.substring(8), 16)); - - while (C1.length() < 5) - C1 = "0" + C1; - - final char S7 = C1.charAt(1); - final char S8 = C1.charAt(2); - final char S9 = C1.charAt(3); - final char S10 = C1.charAt(4); - final char M9 = mac.charAt(8); - final char M10 = mac.charAt(9); - final char M11 = mac.charAt(10); - final char M12 = mac.charAt(11); - - final String tmpK1 = Integer.toHexString(Character.digit(S7, 16) - + Character.digit(S8, 16) + Character.digit(M11, 16) - + Character.digit(M12, 16)); - final String tmpK2 = Integer.toHexString(Character.digit(M9, 16) - + Character.digit(M10, 16) + Character.digit(S9, 16) - + Character.digit(S10, 16)); - - final char K1 = tmpK1.charAt(tmpK1.length() - 1); - final char K2 = tmpK2.charAt(tmpK2.length() - 1); - - final String X1 = Integer.toHexString(Character.digit(K1, 16) - ^ Character.digit(S10, 16)); - final String X2 = Integer.toHexString(Character.digit(K1, 16) - ^ Character.digit(S9, 16)); - final String X3 = Integer.toHexString(Character.digit(K1, 16) - ^ Character.digit(S8, 16)); - final String Y1 = Integer.toHexString(Character.digit(K2, 16) - ^ Character.digit(M10, 16)); - final String Y2 = Integer.toHexString(Character.digit(K2, 16) - ^ Character.digit(M11, 16)); - final String Y3 = Integer.toHexString(Character.digit(K2, 16) - ^ Character.digit(M12, 16)); - final String Z1 = Integer.toHexString(Character.digit(M11, 16) - ^ Character.digit(S10, 16)); - final String Z2 = Integer.toHexString(Character.digit(M12, 16) - ^ Character.digit(S9, 16)); - final String Z3 = Integer.toHexString(Character.digit(K1, 16) - ^ Character.digit(K2, 16)); - - final String wpaKey = X1 + Y1 + Z1 + X2 + Y2 + Z2 + X3 + Y3 + Z3; - addPassword(wpaKey.toUpperCase(Locale.getDefault())); - - if (wpaKey.indexOf('0')!=-1) { - addPassword(wpaKey.replace("0", "1").toUpperCase(Locale.getDefault())); - } - return getResults(); - } - - private ArcadyanKeygen(Parcel in) { - super(in); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ArcadyanKeygen createFromParcel(Parcel in) { - return new ArcadyanKeygen(in); - } - - public ArcadyanKeygen[] newArray(int size) { - return new ArcadyanKeygen[size]; - } - }; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArcadyanKeygen createFromParcel(Parcel in) { + return new ArcadyanKeygen(in); + } + + public ArcadyanKeygen[] newArray(int size) { + return new ArcadyanKeygen[size]; + } + }; + + public ArcadyanKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private ArcadyanKeygen(Parcel in) { + super(in); + } + + @Override + public int getSupportState() { + if (getSsidName().matches( + "(Arcor|EasyBox|Vodafone|WLAN)(-| )[0-9a-fA-F]{6}") + || getSsidName().matches("Vodafone[0-9a-zA-Z]{4}")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } + + @Override + public List getKeys() { + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + String C1 = Integer.toString(Integer.parseInt(mac.substring(8), 16)); + + while (C1.length() < 5) + C1 = "0" + C1; + + final char S7 = C1.charAt(1); + final char S8 = C1.charAt(2); + final char S9 = C1.charAt(3); + final char S10 = C1.charAt(4); + final char M9 = mac.charAt(8); + final char M10 = mac.charAt(9); + final char M11 = mac.charAt(10); + final char M12 = mac.charAt(11); + + final String tmpK1 = Integer.toHexString(Character.digit(S7, 16) + + Character.digit(S8, 16) + Character.digit(M11, 16) + + Character.digit(M12, 16)); + final String tmpK2 = Integer.toHexString(Character.digit(M9, 16) + + Character.digit(M10, 16) + Character.digit(S9, 16) + + Character.digit(S10, 16)); + + final char K1 = tmpK1.charAt(tmpK1.length() - 1); + final char K2 = tmpK2.charAt(tmpK2.length() - 1); + + final String X1 = Integer.toHexString(Character.digit(K1, 16) + ^ Character.digit(S10, 16)); + final String X2 = Integer.toHexString(Character.digit(K1, 16) + ^ Character.digit(S9, 16)); + final String X3 = Integer.toHexString(Character.digit(K1, 16) + ^ Character.digit(S8, 16)); + final String Y1 = Integer.toHexString(Character.digit(K2, 16) + ^ Character.digit(M10, 16)); + final String Y2 = Integer.toHexString(Character.digit(K2, 16) + ^ Character.digit(M11, 16)); + final String Y3 = Integer.toHexString(Character.digit(K2, 16) + ^ Character.digit(M12, 16)); + final String Z1 = Integer.toHexString(Character.digit(M11, 16) + ^ Character.digit(S10, 16)); + final String Z2 = Integer.toHexString(Character.digit(M12, 16) + ^ Character.digit(S9, 16)); + final String Z3 = Integer.toHexString(Character.digit(K1, 16) + ^ Character.digit(K2, 16)); + + final String wpaKey = X1 + Y1 + Z1 + X2 + Y2 + Z2 + X3 + Y3 + Z3; + addPassword(wpaKey.toUpperCase(Locale.getDefault())); + + if (wpaKey.indexOf('0') != -1) { + addPassword(wpaKey.replace("0", "1").toUpperCase(Locale.getDefault())); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArnetPirelliKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArnetPirelliKeygen.java index 4b0b5dd..402e16f 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArnetPirelliKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ArnetPirelliKeygen.java @@ -18,80 +18,79 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; -import org.exobel.routerkeygen.R; - -import android.os.Parcel; -import android.os.Parcelable; - public class ArnetPirelliKeygen extends Keygen { - private final static String LOOKUP = "0123456789abcdefghijklmnopqrstuvwxyz"; - protected MessageDigest md; - - public ArnetPirelliKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArnetPirelliKeygen createFromParcel(Parcel in) { + return new ArnetPirelliKeygen(in); + } - @Override - public int getSupportState() { - if (getSsidName().startsWith("WiFi-Arnet-")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } + public ArnetPirelliKeygen[] newArray(int size) { + return new ArnetPirelliKeygen[size]; + } + }; + private final static String LOOKUP = "0123456789abcdefghijklmnopqrstuvwxyz"; + protected MessageDigest md; - protected void generateKey(String mac, int length) { - byte[] macBytes = new byte[6]; - for (int i = 0; i < 12; i += 2) { - macBytes[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + Character - .digit(mac.charAt(i + 1), 16)); - } - md.reset(); - md.update(AliceItalyKeygen.ALICE_SEED); - try { - md.update("1236790".getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - } - md.update(macBytes); - final byte[] hash = md.digest(); - final StringBuilder key = new StringBuilder(); - for (int i = 0; i < length; ++i) { - key.append(LOOKUP.charAt((hash[i] & 0xFF) % LOOKUP.length())); - } - addPassword(key.toString()); - } + public ArnetPirelliKeygen(String ssid, String mac) { + super(ssid, mac); + } - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha256); - return null; - } - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_nomac); - return null; - } - generateKey(incrementMac(getMacAddress(), 1), 10); - return getResults(); - } + protected ArnetPirelliKeygen(Parcel in) { + super(in); + } - protected ArnetPirelliKeygen(Parcel in) { - super(in); - } + @Override + public int getSupportState() { + if (getSsidName().startsWith("WiFi-Arnet-")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ArnetPirelliKeygen createFromParcel(Parcel in) { - return new ArnetPirelliKeygen(in); - } + protected void generateKey(String mac, int length) { + byte[] macBytes = new byte[6]; + for (int i = 0; i < 12; i += 2) { + macBytes[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + Character + .digit(mac.charAt(i + 1), 16)); + } + md.reset(); + md.update(AliceItalyKeygen.ALICE_SEED); + try { + md.update("1236790".getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + } + md.update(macBytes); + final byte[] hash = md.digest(); + final StringBuilder key = new StringBuilder(); + for (int i = 0; i < length; ++i) { + key.append(LOOKUP.charAt((hash[i] & 0xFF) % LOOKUP.length())); + } + addPassword(key.toString()); + } - public ArnetPirelliKeygen[] newArray(int size) { - return new ArnetPirelliKeygen[size]; - } - }; + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha256); + return null; + } + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + generateKey(incrementMac(getMacAddress(), 1), 10); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AxtelKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AxtelKeygen.java index f145a46..7e62130 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AxtelKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/AxtelKeygen.java @@ -18,42 +18,42 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; public class AxtelKeygen extends Keygen { - public AxtelKeygen(String ssid, String mac) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword(getMacAddress().substring(2).toUpperCase(Locale.getDefault())); - return getResults(); - } - - private AxtelKeygen(Parcel in) { - super(in); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public AxtelKeygen createFromParcel(Parcel in) { - return new AxtelKeygen(in); - } - - public AxtelKeygen[] newArray(int size) { - return new AxtelKeygen[size]; - } - }; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AxtelKeygen createFromParcel(Parcel in) { + return new AxtelKeygen(in); + } + + public AxtelKeygen[] newArray(int size) { + return new AxtelKeygen[size]; + } + }; + + public AxtelKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private AxtelKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword(getMacAddress().substring(2).toUpperCase(Locale.getDefault())); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/BelkinKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/BelkinKeygen.java index a225244..2800183 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/BelkinKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/BelkinKeygen.java @@ -18,94 +18,93 @@ */ package org.exobel.routerkeygen.algorithms; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; public class BelkinKeygen extends Keygen { - private final static int[][] ORDERS = { { 6, 2, 3, 8, 5, 1, 7, 4 }, - { 1, 2, 3, 8, 5, 1, 7, 4 }, { 1, 2, 3, 8, 5, 6, 7, 4 } }; - private final static String[] CHARSETS = { "024613578ACE9BDF", - "944626378ace9bdf" }; - protected MessageDigest md; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public BelkinKeygen createFromParcel(Parcel in) { + return new BelkinKeygen(in); + } - public BelkinKeygen(String ssid, String mac) { - super(ssid, mac); - } + public BelkinKeygen[] newArray(int size) { + return new BelkinKeygen[size]; + } + }; + private final static int[][] ORDERS = {{6, 2, 3, 8, 5, 1, 7, 4}, + {1, 2, 3, 8, 5, 1, 7, 4}, {1, 2, 3, 8, 5, 6, 7, 4}}; + private final static String[] CHARSETS = {"024613578ACE9BDF", + "944626378ace9bdf"}; + protected MessageDigest md; - @Override - public int getSupportState() { - if (getSsidName().matches("^(B|b)elkin(\\.|_)[0-9a-fA-F]{3,6}$")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } - - protected void generateKey(String mac, String charset, int [] order) { - StringBuilder key = new StringBuilder(); - if ( mac.length() != 8 ) { - return; - } - for ( int i = 0; i < mac.length(); ++i ){ - String k = mac.substring(order[i]-1, order[i]); - key.append(charset.charAt(Integer.parseInt(k, 16))); - } - addPassword(key.toString()); - } + public BelkinKeygen(String ssid, String mac) { + super(ssid, mac); + } - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha256); - return null; - } - String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_nomac); - return null; - } - String ssid = getSsidName(); - if (ssid.startsWith("B")) { - generateKey(mac.substring(4), CHARSETS[0], ORDERS[0]); - } else if (ssid.startsWith("b")) { - mac = incrementMac(mac, 1); - generateKey(mac.substring(4), CHARSETS[1], ORDERS[0]); - if (!mac.startsWith("944452")) { - generateKey(mac.substring(4), CHARSETS[1], ORDERS[2]); - mac = incrementMac(mac, 1); - generateKey(mac.substring(4), CHARSETS[1], ORDERS[0]); - } - } else { - //Bruteforcing - for (int i = 0; i < 3; ++i) { - for ( int j = 0; j < ORDERS.length; ++j ) { - generateKey(mac.substring(4), CHARSETS[0], ORDERS[j]); - generateKey(mac.substring(4), CHARSETS[1], ORDERS[j]); - } - mac = incrementMac(mac, 1); - } - } - return getResults(); - } + protected BelkinKeygen(Parcel in) { + super(in); + } - protected BelkinKeygen(Parcel in) { - super(in); - } + @Override + public int getSupportState() { + if (getSsidName().matches("^(B|b)elkin(\\.|_)[0-9a-fA-F]{3,6}$")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public BelkinKeygen createFromParcel(Parcel in) { - return new BelkinKeygen(in); - } + protected void generateKey(String mac, String charset, int[] order) { + StringBuilder key = new StringBuilder(); + if (mac.length() != 8) { + return; + } + for (int i = 0; i < mac.length(); ++i) { + String k = mac.substring(order[i] - 1, order[i]); + key.append(charset.charAt(Integer.parseInt(k, 16))); + } + addPassword(key.toString()); + } - public BelkinKeygen[] newArray(int size) { - return new BelkinKeygen[size]; - } - }; + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha256); + return null; + } + String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + String ssid = getSsidName(); + if (ssid.startsWith("B")) { + generateKey(mac.substring(4), CHARSETS[0], ORDERS[0]); + } else if (ssid.startsWith("b")) { + mac = incrementMac(mac, 1); + generateKey(mac.substring(4), CHARSETS[1], ORDERS[0]); + if (!mac.startsWith("944452")) { + generateKey(mac.substring(4), CHARSETS[1], ORDERS[2]); + mac = incrementMac(mac, 1); + generateKey(mac.substring(4), CHARSETS[1], ORDERS[0]); + } + } else { + //Bruteforcing + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < ORDERS.length; ++j) { + generateKey(mac.substring(4), CHARSETS[0], ORDERS[j]); + generateKey(mac.substring(4), CHARSETS[1], ORDERS[j]); + } + mac = incrementMac(mac, 1); + } + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/CabovisaoSagemKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/CabovisaoSagemKeygen.java index e36ac73..d920bc8 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/CabovisaoSagemKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/CabovisaoSagemKeygen.java @@ -18,12 +18,12 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; - import android.os.Parcel; import android.os.Parcelable; +import java.util.List; +import java.util.Locale; + /* * This is not actual an algorithm as * it is just the base string followed by a character in the range a-e and then @@ -31,32 +31,6 @@ * Source: http://jb.ptsec.info/cabovisao/ */ public class CabovisaoSagemKeygen extends Keygen { - private final static String KEY_BASE = "2ce412e"; - final private String ssidIdentifier; - public CabovisaoSagemKeygen(String ssid, String mac ) { - super(ssid, mac); - this.ssidIdentifier = ssid.substring(ssid.length()-4).toLowerCase(Locale.getDefault()); - } - - @Override - public List getKeys() { - addPassword(KEY_BASE + 'a' + ssidIdentifier); - addPassword(KEY_BASE + 'b' + ssidIdentifier); - addPassword(KEY_BASE + 'c' + ssidIdentifier); - addPassword(KEY_BASE + 'd' + ssidIdentifier); - return getResults(); - } - - private CabovisaoSagemKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } - - - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public CabovisaoSagemKeygen createFromParcel(Parcel in) { return new CabovisaoSagemKeygen(in); @@ -66,6 +40,32 @@ public CabovisaoSagemKeygen[] newArray(int size) { return new CabovisaoSagemKeygen[size]; } }; - + private final static String KEY_BASE = "2ce412e"; + final private String ssidIdentifier; + + public CabovisaoSagemKeygen(String ssid, String mac) { + super(ssid, mac); + this.ssidIdentifier = ssid.substring(ssid.length() - 4).toLowerCase(Locale.getDefault()); + } + + private CabovisaoSagemKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } + + @Override + public List getKeys() { + addPassword(KEY_BASE + 'a' + ssidIdentifier); + addPassword(KEY_BASE + 'b' + ssidIdentifier); + addPassword(KEY_BASE + 'c' + ssidIdentifier); + addPassword(KEY_BASE + 'd' + ssidIdentifier); + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ComtrendKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ComtrendKeygen.java index 20e8afa..e1d9075 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ComtrendKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ComtrendKeygen.java @@ -18,97 +18,95 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.utils.StringUtils; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Locale; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.utils.StringUtils; - -import android.os.Parcel; -import android.os.Parcelable; - public class ComtrendKeygen extends Keygen { - private MessageDigest md; - - public ComtrendKeygen(String ssid, String mac) { - super(ssid, mac); - } - - static final String magic = "bcgbghgg"; - static final String lowermagic = "64680C"; - static final String highermagic = "3872C0"; - static final String mac001a2b = "001A2B"; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ComtrendKeygen createFromParcel(Parcel in) { + return new ComtrendKeygen(in); + } - @Override - public List getKeys() { - final String ssidIdentifier = getSsidName().substring( - getSsidName().length() - 4); - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - try { - if (mac.substring(0, 6).equalsIgnoreCase(mac001a2b)) { - for (int i = 0; i < 512; i++) { - md.reset(); - md.update(magic.getBytes("ASCII")); - String xx; - if (i < 256) { - md.update(lowermagic.getBytes("ASCII")); - xx = Integer.toHexString(i).toUpperCase(Locale.US); - } else { - md.update(highermagic.getBytes("ASCII")); - xx = Integer.toHexString(i - 256).toUpperCase(Locale.US); - } - while (xx.length() < 2) - xx = "0" + xx; - md.update(xx.getBytes("ASCII")); - md.update(ssidIdentifier.getBytes("ASCII")); - md.update(mac.getBytes("ASCII")); - byte[] hash = md.digest(); - addPassword(StringUtils.getHexString(hash).substring(0, 20)); - } - } else { - final String macMod = mac.substring(0, 8) + ssidIdentifier; - md.reset(); - md.update(magic.getBytes("ASCII")); - md.update(macMod.toUpperCase(Locale.getDefault()).getBytes( - "ASCII")); - md.update(mac.toUpperCase(Locale.getDefault()) - .getBytes("ASCII")); - byte[] hash = md.digest(); - addPassword(StringUtils.getHexString(hash).substring(0, 20)); + public ComtrendKeygen[] newArray(int size) { + return new ComtrendKeygen[size]; + } + }; + static final String magic = "bcgbghgg"; + static final String lowermagic = "64680C"; + static final String highermagic = "3872C0"; + static final String mac001a2b = "001A2B"; + private MessageDigest md; - } - return getResults(); - } catch (UnsupportedEncodingException e) { - } - return null; - } + public ComtrendKeygen(String ssid, String mac) { + super(ssid, mac); + } - private ComtrendKeygen(Parcel in) { - super(in); - } + private ComtrendKeygen(Parcel in) { + super(in); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ComtrendKeygen createFromParcel(Parcel in) { - return new ComtrendKeygen(in); - } + @Override + public List getKeys() { + final String ssidIdentifier = getSsidName().substring( + getSsidName().length() - 4); + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + try { + if (mac.substring(0, 6).equalsIgnoreCase(mac001a2b)) { + for (int i = 0; i < 512; i++) { + md.reset(); + md.update(magic.getBytes("ASCII")); + String xx; + if (i < 256) { + md.update(lowermagic.getBytes("ASCII")); + xx = Integer.toHexString(i).toUpperCase(Locale.US); + } else { + md.update(highermagic.getBytes("ASCII")); + xx = Integer.toHexString(i - 256).toUpperCase(Locale.US); + } + while (xx.length() < 2) + xx = "0" + xx; + md.update(xx.getBytes("ASCII")); + md.update(ssidIdentifier.getBytes("ASCII")); + md.update(mac.getBytes("ASCII")); + byte[] hash = md.digest(); + addPassword(StringUtils.getHexString(hash).substring(0, 20)); + } + } else { + final String macMod = mac.substring(0, 8) + ssidIdentifier; + md.reset(); + md.update(magic.getBytes("ASCII")); + md.update(macMod.toUpperCase(Locale.getDefault()).getBytes( + "ASCII")); + md.update(mac.toUpperCase(Locale.getDefault()) + .getBytes("ASCII")); + byte[] hash = md.digest(); + addPassword(StringUtils.getHexString(hash).substring(0, 20)); - public ComtrendKeygen[] newArray(int size) { - return new ComtrendKeygen[size]; - } - }; + } + return getResults(); + } catch (UnsupportedEncodingException e) { + } + return null; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ConnKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ConnKeygen.java index 2ea6834..8f23bae 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ConnKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ConnKeygen.java @@ -18,13 +18,13 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; /* * This is not actual an algorithm as @@ -33,57 +33,57 @@ */ public class ConnKeygen extends Keygen { - public ConnKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ConnKeygen createFromParcel(Parcel in) { + return new ConnKeygen(in); + } - @Override - public int getSupportState() { - final String ssid = getSsidName(); - if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { - final String mac = getMacAddress(); - if (mac.length() == 12) { - final String macShort = mac.replace(":", ""); - final String ssidSubpart = ssid.substring(ssid.length() - 6); - if (macShort.equalsIgnoreCase(ssidSubpart)) - return SUPPORTED; - else - return UNLIKELY_SUPPORTED; - } else - return UNSUPPORTED; // Should not happen because WireMatcher - // filter thiss - } - return SUPPORTED; - } + public ConnKeygen[] newArray(int size) { + return new ConnKeygen[size]; + } + }; - @Override - public List getKeys() { - final String ssid = getSsidName(); - if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { - final String mac = getMacAddress(); - if (mac.length() == 12) { - addPassword(getMacAddress().toLowerCase(Locale.getDefault())); - } else { - setErrorCode(R.string.msg_nomac); - return null; - } - } else { - addPassword("1234567890123"); - } - return getResults(); - } + public ConnKeygen(String ssid, String mac) { + super(ssid, mac); + } - private ConnKeygen(Parcel in) { - super(in); - } + private ConnKeygen(Parcel in) { + super(in); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ConnKeygen createFromParcel(Parcel in) { - return new ConnKeygen(in); - } + @Override + public int getSupportState() { + final String ssid = getSsidName(); + if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { + final String mac = getMacAddress(); + if (mac.length() == 12) { + final String macShort = mac.replace(":", ""); + final String ssidSubpart = ssid.substring(ssid.length() - 6); + if (macShort.equalsIgnoreCase(ssidSubpart)) + return SUPPORTED; + else + return UNLIKELY_SUPPORTED; + } else + return UNSUPPORTED; // Should not happen because WireMatcher + // filter thiss + } + return SUPPORTED; + } - public ConnKeygen[] newArray(int size) { - return new ConnKeygen[size]; - } - }; + @Override + public List getKeys() { + final String ssid = getSsidName(); + if (ssid.matches("conn-x[0-9a-fA-F]{6}")) { + final String mac = getMacAddress(); + if (mac.length() == 12) { + addPassword(getMacAddress().toLowerCase(Locale.getDefault())); + } else { + setErrorCode(R.string.msg_nomac); + return null; + } + } else { + addPassword("1234567890123"); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DiscusKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DiscusKeygen.java index 9678f72..1cc04f7 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DiscusKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DiscusKeygen.java @@ -19,38 +19,20 @@ package org.exobel.routerkeygen.algorithms; -import java.util.List; - import android.os.Parcel; import android.os.Parcelable; +import java.util.List; + /** * The algortihm is described on the pdf below * Link:http://www.remote-exploit.org/content/Pirelli_Discus_DRG_A225_WiFi_router.pdf - * @author Rui Araújo * + * @author Rui Araújo */ public class DiscusKeygen extends Keygen { - public DiscusKeygen(String ssid, String mac) { - super(ssid, mac); - } - - static final int essidConst = 0xD0EC31; - - @Override - public List getKeys() { - int routerEssid = Integer.parseInt( getSsidName().substring(getSsidName().length()-6) , 16); - int result = ( routerEssid - essidConst )>>2; - addPassword("YW0" + Integer.toString(result)); - return getResults(); - } - - private DiscusKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public DiscusKeygen createFromParcel(Parcel in) { return new DiscusKeygen(in); @@ -60,4 +42,21 @@ public DiscusKeygen[] newArray(int size) { return new DiscusKeygen[size]; } }; + static final int essidConst = 0xD0EC31; + + public DiscusKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private DiscusKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + int routerEssid = Integer.parseInt(getSsidName().substring(getSsidName().length() - 6), 16); + int result = (routerEssid - essidConst) >> 2; + addPassword("YW0" + Integer.toString(result)); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DlinkKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DlinkKeygen.java index 6f3f91b..7a18963 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DlinkKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/DlinkKeygen.java @@ -18,105 +18,20 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /** - * * Link:http://fodi.me/codigo-fonte-wpa-dlink-php-c/ - * @author Rui Araújo * + * @author Rui Araújo */ public class DlinkKeygen extends Keygen { - public DlinkKeygen(String ssid, String mac) { - super(ssid, mac); - } - - - @Override - public int getSupportState() { - if (getSsidName().matches("(DL|dl)ink-[0-9a-fA-F]{6}")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } - - final static char hash[] = { 'X', 'r', 'q', 'a', 'H', 'N', - 'p', 'd', 'S', 'Y', 'w', - '8', '6', '2', '1', '5'}; - - @Override - public List getKeys() { - if ( getMacAddress().equals("") ) - { - setErrorCode(R.string.msg_nomac); - return null; - } - final char[] key = new char[20]; - final String mac = getMacAddress(); - key[0]=mac.charAt(11); - key[1]=mac.charAt(0); - - key[2]=mac.charAt(10); - key[3]=mac.charAt(1); - - key[4]=mac.charAt(9); - key[5]=mac.charAt(2); - - key[6]=mac.charAt(8); - key[7]=mac.charAt(3); - - key[8]=mac.charAt(7); - key[9]=mac.charAt(4); - - key[10]=mac.charAt(6); - key[11]=mac.charAt(5); - - key[12]=mac.charAt(1); - key[13]=mac.charAt(6); - - key[14]=mac.charAt(8); - key[15]=mac.charAt(9); - - key[16]=mac.charAt(11); - key[17]=mac.charAt(2); - - key[18]=mac.charAt(4); - key[19]=mac.charAt(10); - char [] newkey = new char[20]; - char t; - int index = 0; - for (int i=0; i < 20 ; i++) - { - t=key[i]; - if ((t >= '0') && (t <= '9')) - index = t-'0'; - else - { - t=Character.toUpperCase(t); - if ((t >= 'A') && (t <= 'F')) - index = t-'A'+10; - else - { - setErrorCode(R.string.msg_dlinkerror); - return null; - } - } - newkey[i]=hash[index]; - } - addPassword(String.valueOf(newkey, 0, 20)); - return getResults(); - } - - - private DlinkKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public DlinkKeygen createFromParcel(Parcel in) { return new DlinkKeygen(in); @@ -126,5 +41,82 @@ public DlinkKeygen[] newArray(int size) { return new DlinkKeygen[size]; } }; + final static char hash[] = {'X', 'r', 'q', 'a', 'H', 'N', + 'p', 'd', 'S', 'Y', 'w', + '8', '6', '2', '1', '5'}; + + public DlinkKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private DlinkKeygen(Parcel in) { + super(in); + } + + @Override + public int getSupportState() { + if (getSsidName().matches("(DL|dl)ink-[0-9a-fA-F]{6}")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } + + @Override + public List getKeys() { + if (getMacAddress().equals("")) { + setErrorCode(R.string.msg_nomac); + return null; + } + final char[] key = new char[20]; + final String mac = getMacAddress(); + key[0] = mac.charAt(11); + key[1] = mac.charAt(0); + + key[2] = mac.charAt(10); + key[3] = mac.charAt(1); + + key[4] = mac.charAt(9); + key[5] = mac.charAt(2); + + key[6] = mac.charAt(8); + key[7] = mac.charAt(3); + + key[8] = mac.charAt(7); + key[9] = mac.charAt(4); + + key[10] = mac.charAt(6); + key[11] = mac.charAt(5); + + key[12] = mac.charAt(1); + key[13] = mac.charAt(6); + + key[14] = mac.charAt(8); + key[15] = mac.charAt(9); + + key[16] = mac.charAt(11); + key[17] = mac.charAt(2); + + key[18] = mac.charAt(4); + key[19] = mac.charAt(10); + char[] newkey = new char[20]; + char t; + int index = 0; + for (int i = 0; i < 20; i++) { + t = key[i]; + if ((t >= '0') && (t <= '9')) + index = t - '0'; + else { + t = Character.toUpperCase(t); + if ((t >= 'A') && (t <= 'F')) + index = t - 'A' + 10; + else { + setErrorCode(R.string.msg_dlinkerror); + return null; + } + } + newkey[i] = hash[index]; + } + addPassword(String.valueOf(newkey, 0, 20)); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/EircomKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/EircomKeygen.java index a33b9bc..dda96f7 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/EircomKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/EircomKeygen.java @@ -18,61 +18,23 @@ */ package org.exobel.routerkeygen.algorithms; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; import org.exobel.routerkeygen.utils.StringUtils; -import android.os.Parcel; -import android.os.Parcelable; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; /* * Eircom algorithm published here: * http://www.bacik.org/eircomwep/howto.html */ -public class EircomKeygen extends Keygen { - - private MessageDigest md; - public EircomKeygen(String ssid, String mac ) { - super(ssid, mac); - } +public class EircomKeygen extends Keygen { - @Override - public List getKeys() { - String mac = getMacAddress().substring(6); - try { - md = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha1); - return null; - } - byte [] routerMAC = new byte[4]; - routerMAC[0] = 1; - for (int i = 0; i < 6; i += 2) - routerMAC[i / 2 + 1] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) - + Character.digit(mac.charAt(i + 1), 16)); - int macDec = ( (0xFF & routerMAC[0]) << 24 ) | ( (0xFF & routerMAC[1]) << 16 ) | - ( (0xFF & routerMAC[2]) << 8 ) | (0xFF & routerMAC[3]); - mac = StringUtils.dectoString(macDec) + "Although your world wonders me, "; - md.reset(); - md.update(mac.getBytes()); - byte [] hash = md.digest(); - try { - addPassword(StringUtils.getHexString(hash).substring(0,26)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return getResults(); - } - - - private EircomKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public EircomKeygen createFromParcel(Parcel in) { return new EircomKeygen(in); @@ -82,4 +44,42 @@ public EircomKeygen[] newArray(int size) { return new EircomKeygen[size]; } }; + private MessageDigest md; + + public EircomKeygen(String ssid, String mac) { + super(ssid, mac); + } + + + private EircomKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + String mac = getMacAddress().substring(6); + try { + md = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha1); + return null; + } + byte[] routerMAC = new byte[4]; + routerMAC[0] = 1; + for (int i = 0; i < 6; i += 2) + routerMAC[i / 2 + 1] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + + Character.digit(mac.charAt(i + 1), 16)); + int macDec = ((0xFF & routerMAC[0]) << 24) | ((0xFF & routerMAC[1]) << 16) | + ((0xFF & routerMAC[2]) << 8) | (0xFF & routerMAC[3]); + mac = StringUtils.dectoString(macDec) + "Although your world wonders me, "; + md.reset(); + md.update(mac.getBytes()); + byte[] hash = md.digest(); + try { + addPassword(StringUtils.getHexString(hash).substring(0, 26)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/HuaweiKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/HuaweiKeygen.java index a0d2258..c5a0abc 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/HuaweiKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/HuaweiKeygen.java @@ -18,12 +18,12 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /* * @@ -34,155 +34,153 @@ * */ public class HuaweiKeygen extends Keygen { - final private String ssidIdentifier; - - public HuaweiKeygen(String ssid, String mac) { - super(ssid, mac); - if (getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) - ssidIdentifier = ssid.substring(ssid.length() - 4); - else - ssidIdentifier = ""; - } - - // Java adaptation of mac2wepkey.py from - // http://websec.ca/blog/view/mac2wepkey_huawei - final int[] a0 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - final int[] a1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; - final int[] a2 = { 0, 13, 10, 7, 5, 8, 15, 2, 10, 7, 0, 13, 15, 2, 5, 8 }; - final int[] a3 = { 0, 1, 3, 2, 7, 6, 4, 5, 15, 14, 12, 13, 8, 9, 11, 10 }; - final int[] a4 = { 0, 5, 11, 14, 7, 2, 12, 9, 15, 10, 4, 1, 8, 13, 3, 6 }; - final int[] a5 = { 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12 }; - final int[] a6 = { 0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8 }; - final int[] a7 = { 0, 8, 0, 8, 1, 9, 1, 9, 2, 10, 2, 10, 3, 11, 3, 11 }; - final int[] a8 = { 0, 5, 11, 14, 6, 3, 13, 8, 12, 9, 7, 2, 10, 15, 1, 4 }; - final int[] a9 = { 0, 9, 2, 11, 5, 12, 7, 14, 10, 3, 8, 1, 15, 6, 13, 4 }; - final int[] a10 = { 0, 14, 13, 3, 11, 5, 6, 8, 6, 8, 11, 5, 13, 3, 0, 14 }; - final int[] a11 = { 0, 12, 8, 4, 1, 13, 9, 5, 2, 14, 10, 6, 3, 15, 11, 7 }; - final int[] a12 = { 0, 4, 9, 13, 2, 6, 11, 15, 4, 0, 13, 9, 6, 2, 15, 11 }; - final int[] a13 = { 0, 8, 1, 9, 3, 11, 2, 10, 6, 14, 7, 15, 5, 13, 4, 12 }; - final int[] a14 = { 0, 1, 3, 2, 7, 6, 4, 5, 14, 15, 13, 12, 9, 8, 10, 11 }; - final int[] a15 = { 0, 1, 3, 2, 6, 7, 5, 4, 13, 12, 14, 15, 11, 10, 8, 9 }; - final int[] n1 = { 0, 14, 10, 4, 8, 6, 2, 12, 0, 14, 10, 4, 8, 6, 2, 12 }; - final int[] n2 = { 0, 8, 0, 8, 3, 11, 3, 11, 6, 14, 6, 14, 5, 13, 5, 13 }; - final int[] n3 = { 0, 0, 3, 3, 2, 2, 1, 1, 4, 4, 7, 7, 6, 6, 5, 5 }; - final int[] n4 = { 0, 11, 12, 7, 15, 4, 3, 8, 14, 5, 2, 9, 1, 10, 13, 6 }; - final int[] n5 = { 0, 5, 1, 4, 6, 3, 7, 2, 12, 9, 13, 8, 10, 15, 11, 14 }; - final int[] n6 = { 0, 14, 4, 10, 11, 5, 15, 1, 6, 8, 2, 12, 13, 3, 9, 7 }; - final int[] n7 = { 0, 9, 0, 9, 5, 12, 5, 12, 10, 3, 10, 3, 15, 6, 15, 6 }; - final int[] n8 = { 0, 5, 11, 14, 2, 7, 9, 12, 12, 9, 7, 2, 14, 11, 5, 0 }; - final int[] n9 = { 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4 }; - final int[] n10 = { 0, 8, 1, 9, 3, 11, 2, 10, 5, 13, 4, 12, 6, 14, 7, 15 }; - final int[] n11 = { 0, 14, 13, 3, 9, 7, 4, 10, 6, 8, 11, 5, 15, 1, 2, 12 }; - final int[] n12 = { 0, 13, 10, 7, 4, 9, 14, 3, 10, 7, 0, 13, 14, 3, 4, 9 }; - final int[] n13 = { 0, 1, 3, 2, 6, 7, 5, 4, 15, 14, 12, 13, 9, 8, 10, 11 }; - final int[] n14 = { 0, 1, 3, 2, 4, 5, 7, 6, 12, 13, 15, 14, 8, 9, 11, 10 }; - final int[] n15 = { 0, 6, 12, 10, 9, 15, 5, 3, 2, 4, 14, 8, 11, 13, 7, 1 }; - final int[] n16 = { 0, 11, 6, 13, 13, 6, 11, 0, 11, 0, 13, 6, 6, 13, 0, 11 }; - final int[] n17 = { 0, 12, 8, 4, 1, 13, 9, 5, 3, 15, 11, 7, 2, 14, 10, 6 }; - final int[] n18 = { 0, 12, 9, 5, 2, 14, 11, 7, 5, 9, 12, 0, 7, 11, 14, 2 }; - final int[] n19 = { 0, 6, 13, 11, 10, 12, 7, 1, 5, 3, 8, 14, 15, 9, 2, 4 }; - final int[] n20 = { 0, 9, 3, 10, 7, 14, 4, 13, 14, 7, 13, 4, 9, 0, 10, 3 }; - final int[] n21 = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 }; - final int[] n22 = { 0, 1, 2, 3, 5, 4, 7, 6, 11, 10, 9, 8, 14, 15, 12, 13 }; - final int[] n23 = { 0, 7, 15, 8, 14, 9, 1, 6, 12, 11, 3, 4, 2, 5, 13, 10 }; - final int[] n24 = { 0, 5, 10, 15, 4, 1, 14, 11, 8, 13, 2, 7, 12, 9, 6, 3 }; - final int[] n25 = { 0, 11, 6, 13, 13, 6, 11, 0, 10, 1, 12, 7, 7, 12, 1, 10 }; - final int[] n26 = { 0, 13, 10, 7, 4, 9, 14, 3, 8, 5, 2, 15, 12, 1, 6, 11 }; - final int[] n27 = { 0, 4, 9, 13, 2, 6, 11, 15, 5, 1, 12, 8, 7, 3, 14, 10 }; - final int[] n28 = { 0, 14, 12, 2, 8, 6, 4, 10, 0, 14, 12, 2, 8, 6, 4, 10 }; - final int[] n29 = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 }; - final int[] n30 = { 0, 15, 14, 1, 12, 3, 2, 13, 8, 7, 6, 9, 4, 11, 10, 5 }; - final int[] n31 = { 0, 10, 4, 14, 9, 3, 13, 7, 2, 8, 6, 12, 11, 1, 15, 5 }; - final int[] n32 = { 0, 10, 5, 15, 11, 1, 14, 4, 6, 12, 3, 9, 13, 7, 8, 2 }; - final int[] n33 = { 0, 4, 9, 13, 3, 7, 10, 14, 7, 3, 14, 10, 4, 0, 13, 9 }; - final int[] key = { 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 61, 62, 63, 64, - 65, 66 }; - final char[] ssid = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public HuaweiKeygen createFromParcel(Parcel in) { + return new HuaweiKeygen(in); + } - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - int[] mac = new int[12]; - for (int i = 0; i < 12; ++i) { - mac[i] = Integer.parseInt(getMacAddress().substring(i, i + 1), 16); - } - int s1 = (n1[mac[0]]) ^ (a4[mac[1]]) ^ (a6[mac[2]]) ^ (a1[mac[3]]) - ^ (a11[mac[4]]) ^ (n20[mac[5]]) ^ (a10[mac[6]]) ^ (a4[mac[7]]) - ^ (a8[mac[8]]) ^ (a2[mac[9]]) ^ (a5[mac[10]]) ^ (a9[mac[11]]) - ^ 5; - int s2 = (n2[mac[0]]) ^ (n8[mac[1]]) ^ (n15[mac[2]]) ^ (n17[mac[3]]) - ^ (a12[mac[4]]) ^ (n21[mac[5]]) ^ (n24[mac[6]]) ^ (a9[mac[7]]) - ^ (n27[mac[8]]) ^ (n29[mac[9]]) ^ (a11[mac[10]]) - ^ (n32[mac[11]]) ^ 10; - int s3 = (n3[mac[0]]) ^ (n9[mac[1]]) ^ (a5[mac[2]]) ^ (a9[mac[3]]) - ^ (n19[mac[4]]) ^ (n22[mac[5]]) ^ (a12[mac[6]]) ^ (n25[mac[7]]) - ^ (a11[mac[8]]) ^ (a13[mac[9]]) ^ (n30[mac[10]]) - ^ (n33[mac[11]]) ^ 11; - int s4 = (n4[mac[0]]) ^ (n10[mac[1]]) ^ (n16[mac[2]]) ^ (n18[mac[3]]) - ^ (a13[mac[4]]) ^ (n23[mac[5]]) ^ (a1[mac[6]]) ^ (n26[mac[7]]) - ^ (n28[mac[8]]) ^ (a3[mac[9]]) ^ (a6[mac[10]]) ^ (a0[mac[11]]) - ^ 10; - String ssidFinal = Character.toString(ssid[s1]) - + Character.toString(ssid[s2]) + Character.toString(ssid[s3]) - + Character.toString(ssid[s4]); - int ya = (a2[mac[0]]) ^ (n11[mac[1]]) ^ (a7[mac[2]]) ^ (a8[mac[3]]) - ^ (a14[mac[4]]) ^ (a5[mac[5]]) ^ (a5[mac[6]]) ^ (a2[mac[7]]) - ^ (a0[mac[8]]) ^ (a1[mac[9]]) ^ (a15[mac[10]]) ^ (a0[mac[11]]) - ^ 13; - int yb = (n5[mac[0]]) ^ (n12[mac[1]]) ^ (a5[mac[2]]) ^ (a7[mac[3]]) - ^ (a2[mac[4]]) ^ (a14[mac[5]]) ^ (a1[mac[6]]) ^ (a5[mac[7]]) - ^ (a0[mac[8]]) ^ (a0[mac[9]]) ^ (n31[mac[10]]) ^ (a15[mac[11]]) - ^ 4; - int yc = (a3[mac[0]]) ^ (a5[mac[1]]) ^ (a2[mac[2]]) ^ (a10[mac[3]]) - ^ (a7[mac[4]]) ^ (a8[mac[5]]) ^ (a14[mac[6]]) ^ (a5[mac[7]]) - ^ (a5[mac[8]]) ^ (a2[mac[9]]) ^ (a0[mac[10]]) ^ (a1[mac[11]]) - ^ 7; - int yd = (n6[mac[0]]) ^ (n13[mac[1]]) ^ (a8[mac[2]]) ^ (a2[mac[3]]) - ^ (a5[mac[4]]) ^ (a7[mac[5]]) ^ (a2[mac[6]]) ^ (a14[mac[7]]) - ^ (a1[mac[8]]) ^ (a5[mac[9]]) ^ (a0[mac[10]]) ^ (a0[mac[11]]) - ^ 14; - int ye = (n7[mac[0]]) ^ (n14[mac[1]]) ^ (a3[mac[2]]) ^ (a5[mac[3]]) - ^ (a2[mac[4]]) ^ (a10[mac[5]]) ^ (a7[mac[6]]) ^ (a8[mac[7]]) - ^ (a14[mac[8]]) ^ (a5[mac[9]]) ^ (a5[mac[10]]) ^ (a2[mac[11]]) - ^ 7; - addPassword(Integer.toString(key[ya]) + Integer.toString(key[yb]) - + Integer.toString(key[yc]) + Integer.toString(key[yd]) - + Integer.toString(key[ye])); - if (!ssidIdentifier.equalsIgnoreCase(ssidFinal) - && getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) { - setErrorCode(R.string.msg_err_essid_no_match); - } - return getResults(); - } + public HuaweiKeygen[] newArray(int size) { + return new HuaweiKeygen[size]; + } + }; + // Java adaptation of mac2wepkey.py from + // http://websec.ca/blog/view/mac2wepkey_huawei + final int[] a0 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + final int[] a1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + final int[] a2 = {0, 13, 10, 7, 5, 8, 15, 2, 10, 7, 0, 13, 15, 2, 5, 8}; + final int[] a3 = {0, 1, 3, 2, 7, 6, 4, 5, 15, 14, 12, 13, 8, 9, 11, 10}; + final int[] a4 = {0, 5, 11, 14, 7, 2, 12, 9, 15, 10, 4, 1, 8, 13, 3, 6}; + final int[] a5 = {0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12}; + final int[] a6 = {0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8}; + final int[] a7 = {0, 8, 0, 8, 1, 9, 1, 9, 2, 10, 2, 10, 3, 11, 3, 11}; + final int[] a8 = {0, 5, 11, 14, 6, 3, 13, 8, 12, 9, 7, 2, 10, 15, 1, 4}; + final int[] a9 = {0, 9, 2, 11, 5, 12, 7, 14, 10, 3, 8, 1, 15, 6, 13, 4}; + final int[] a10 = {0, 14, 13, 3, 11, 5, 6, 8, 6, 8, 11, 5, 13, 3, 0, 14}; + final int[] a11 = {0, 12, 8, 4, 1, 13, 9, 5, 2, 14, 10, 6, 3, 15, 11, 7}; + final int[] a12 = {0, 4, 9, 13, 2, 6, 11, 15, 4, 0, 13, 9, 6, 2, 15, 11}; + final int[] a13 = {0, 8, 1, 9, 3, 11, 2, 10, 6, 14, 7, 15, 5, 13, 4, 12}; + final int[] a14 = {0, 1, 3, 2, 7, 6, 4, 5, 14, 15, 13, 12, 9, 8, 10, 11}; + final int[] a15 = {0, 1, 3, 2, 6, 7, 5, 4, 13, 12, 14, 15, 11, 10, 8, 9}; + final int[] n1 = {0, 14, 10, 4, 8, 6, 2, 12, 0, 14, 10, 4, 8, 6, 2, 12}; + final int[] n2 = {0, 8, 0, 8, 3, 11, 3, 11, 6, 14, 6, 14, 5, 13, 5, 13}; + final int[] n3 = {0, 0, 3, 3, 2, 2, 1, 1, 4, 4, 7, 7, 6, 6, 5, 5}; + final int[] n4 = {0, 11, 12, 7, 15, 4, 3, 8, 14, 5, 2, 9, 1, 10, 13, 6}; + final int[] n5 = {0, 5, 1, 4, 6, 3, 7, 2, 12, 9, 13, 8, 10, 15, 11, 14}; + final int[] n6 = {0, 14, 4, 10, 11, 5, 15, 1, 6, 8, 2, 12, 13, 3, 9, 7}; + final int[] n7 = {0, 9, 0, 9, 5, 12, 5, 12, 10, 3, 10, 3, 15, 6, 15, 6}; + final int[] n8 = {0, 5, 11, 14, 2, 7, 9, 12, 12, 9, 7, 2, 14, 11, 5, 0}; + final int[] n9 = {0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4}; + final int[] n10 = {0, 8, 1, 9, 3, 11, 2, 10, 5, 13, 4, 12, 6, 14, 7, 15}; + final int[] n11 = {0, 14, 13, 3, 9, 7, 4, 10, 6, 8, 11, 5, 15, 1, 2, 12}; + final int[] n12 = {0, 13, 10, 7, 4, 9, 14, 3, 10, 7, 0, 13, 14, 3, 4, 9}; + final int[] n13 = {0, 1, 3, 2, 6, 7, 5, 4, 15, 14, 12, 13, 9, 8, 10, 11}; + final int[] n14 = {0, 1, 3, 2, 4, 5, 7, 6, 12, 13, 15, 14, 8, 9, 11, 10}; + final int[] n15 = {0, 6, 12, 10, 9, 15, 5, 3, 2, 4, 14, 8, 11, 13, 7, 1}; + final int[] n16 = {0, 11, 6, 13, 13, 6, 11, 0, 11, 0, 13, 6, 6, 13, 0, 11}; + final int[] n17 = {0, 12, 8, 4, 1, 13, 9, 5, 3, 15, 11, 7, 2, 14, 10, 6}; + final int[] n18 = {0, 12, 9, 5, 2, 14, 11, 7, 5, 9, 12, 0, 7, 11, 14, 2}; + final int[] n19 = {0, 6, 13, 11, 10, 12, 7, 1, 5, 3, 8, 14, 15, 9, 2, 4}; + final int[] n20 = {0, 9, 3, 10, 7, 14, 4, 13, 14, 7, 13, 4, 9, 0, 10, 3}; + final int[] n21 = {0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}; + final int[] n22 = {0, 1, 2, 3, 5, 4, 7, 6, 11, 10, 9, 8, 14, 15, 12, 13}; + final int[] n23 = {0, 7, 15, 8, 14, 9, 1, 6, 12, 11, 3, 4, 2, 5, 13, 10}; + final int[] n24 = {0, 5, 10, 15, 4, 1, 14, 11, 8, 13, 2, 7, 12, 9, 6, 3}; + final int[] n25 = {0, 11, 6, 13, 13, 6, 11, 0, 10, 1, 12, 7, 7, 12, 1, 10}; + final int[] n26 = {0, 13, 10, 7, 4, 9, 14, 3, 8, 5, 2, 15, 12, 1, 6, 11}; + final int[] n27 = {0, 4, 9, 13, 2, 6, 11, 15, 5, 1, 12, 8, 7, 3, 14, 10}; + final int[] n28 = {0, 14, 12, 2, 8, 6, 4, 10, 0, 14, 12, 2, 8, 6, 4, 10}; + final int[] n29 = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; + final int[] n30 = {0, 15, 14, 1, 12, 3, 2, 13, 8, 7, 6, 9, 4, 11, 10, 5}; + final int[] n31 = {0, 10, 4, 14, 9, 3, 13, 7, 2, 8, 6, 12, 11, 1, 15, 5}; + final int[] n32 = {0, 10, 5, 15, 11, 1, 14, 4, 6, 12, 3, 9, 13, 7, 8, 2}; + final int[] n33 = {0, 4, 9, 13, 3, 7, 10, 14, 7, 3, 14, 10, 4, 0, 13, 9}; + final int[] key = {30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 61, 62, 63, 64, + 65, 66}; + final char[] ssid = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f'}; + final private String ssidIdentifier; - @Override - public int getSupportState() { - if (getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } + public HuaweiKeygen(String ssid, String mac) { + super(ssid, mac); + if (getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) + ssidIdentifier = ssid.substring(ssid.length() - 4); + else + ssidIdentifier = ""; + } - private HuaweiKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } + private HuaweiKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + int[] mac = new int[12]; + for (int i = 0; i < 12; ++i) { + mac[i] = Integer.parseInt(getMacAddress().substring(i, i + 1), 16); + } + int s1 = (n1[mac[0]]) ^ (a4[mac[1]]) ^ (a6[mac[2]]) ^ (a1[mac[3]]) + ^ (a11[mac[4]]) ^ (n20[mac[5]]) ^ (a10[mac[6]]) ^ (a4[mac[7]]) + ^ (a8[mac[8]]) ^ (a2[mac[9]]) ^ (a5[mac[10]]) ^ (a9[mac[11]]) + ^ 5; + int s2 = (n2[mac[0]]) ^ (n8[mac[1]]) ^ (n15[mac[2]]) ^ (n17[mac[3]]) + ^ (a12[mac[4]]) ^ (n21[mac[5]]) ^ (n24[mac[6]]) ^ (a9[mac[7]]) + ^ (n27[mac[8]]) ^ (n29[mac[9]]) ^ (a11[mac[10]]) + ^ (n32[mac[11]]) ^ 10; + int s3 = (n3[mac[0]]) ^ (n9[mac[1]]) ^ (a5[mac[2]]) ^ (a9[mac[3]]) + ^ (n19[mac[4]]) ^ (n22[mac[5]]) ^ (a12[mac[6]]) ^ (n25[mac[7]]) + ^ (a11[mac[8]]) ^ (a13[mac[9]]) ^ (n30[mac[10]]) + ^ (n33[mac[11]]) ^ 11; + int s4 = (n4[mac[0]]) ^ (n10[mac[1]]) ^ (n16[mac[2]]) ^ (n18[mac[3]]) + ^ (a13[mac[4]]) ^ (n23[mac[5]]) ^ (a1[mac[6]]) ^ (n26[mac[7]]) + ^ (n28[mac[8]]) ^ (a3[mac[9]]) ^ (a6[mac[10]]) ^ (a0[mac[11]]) + ^ 10; + String ssidFinal = Character.toString(ssid[s1]) + + Character.toString(ssid[s2]) + Character.toString(ssid[s3]) + + Character.toString(ssid[s4]); + int ya = (a2[mac[0]]) ^ (n11[mac[1]]) ^ (a7[mac[2]]) ^ (a8[mac[3]]) + ^ (a14[mac[4]]) ^ (a5[mac[5]]) ^ (a5[mac[6]]) ^ (a2[mac[7]]) + ^ (a0[mac[8]]) ^ (a1[mac[9]]) ^ (a15[mac[10]]) ^ (a0[mac[11]]) + ^ 13; + int yb = (n5[mac[0]]) ^ (n12[mac[1]]) ^ (a5[mac[2]]) ^ (a7[mac[3]]) + ^ (a2[mac[4]]) ^ (a14[mac[5]]) ^ (a1[mac[6]]) ^ (a5[mac[7]]) + ^ (a0[mac[8]]) ^ (a0[mac[9]]) ^ (n31[mac[10]]) ^ (a15[mac[11]]) + ^ 4; + int yc = (a3[mac[0]]) ^ (a5[mac[1]]) ^ (a2[mac[2]]) ^ (a10[mac[3]]) + ^ (a7[mac[4]]) ^ (a8[mac[5]]) ^ (a14[mac[6]]) ^ (a5[mac[7]]) + ^ (a5[mac[8]]) ^ (a2[mac[9]]) ^ (a0[mac[10]]) ^ (a1[mac[11]]) + ^ 7; + int yd = (n6[mac[0]]) ^ (n13[mac[1]]) ^ (a8[mac[2]]) ^ (a2[mac[3]]) + ^ (a5[mac[4]]) ^ (a7[mac[5]]) ^ (a2[mac[6]]) ^ (a14[mac[7]]) + ^ (a1[mac[8]]) ^ (a5[mac[9]]) ^ (a0[mac[10]]) ^ (a0[mac[11]]) + ^ 14; + int ye = (n7[mac[0]]) ^ (n14[mac[1]]) ^ (a3[mac[2]]) ^ (a5[mac[3]]) + ^ (a2[mac[4]]) ^ (a10[mac[5]]) ^ (a7[mac[6]]) ^ (a8[mac[7]]) + ^ (a14[mac[8]]) ^ (a5[mac[9]]) ^ (a5[mac[10]]) ^ (a2[mac[11]]) + ^ 7; + addPassword(Integer.toString(key[ya]) + Integer.toString(key[yb]) + + Integer.toString(key[yc]) + Integer.toString(key[yd]) + + Integer.toString(key[ye])); + if (!ssidIdentifier.equalsIgnoreCase(ssidFinal) + && getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) { + setErrorCode(R.string.msg_err_essid_no_match); + } + return getResults(); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public HuaweiKeygen createFromParcel(Parcel in) { - return new HuaweiKeygen(in); - } + @Override + public int getSupportState() { + if (getSsidName().matches("INFINITUM[0-9a-zA-Z]{4}")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - public HuaweiKeygen[] newArray(int size) { - return new HuaweiKeygen[size]; - } - }; + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InfostradaKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InfostradaKeygen.java index 4ca07e4..a429368 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InfostradaKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InfostradaKeygen.java @@ -18,13 +18,13 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; /* * This is not actual an algorithm @@ -33,25 +33,6 @@ */ public class InfostradaKeygen extends Keygen { - public InfostradaKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if ( getMacAddress().length() != 12 ) - { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword("2"+getMacAddress().toUpperCase(Locale.getDefault())); - return getResults(); - } - - private InfostradaKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public InfostradaKeygen createFromParcel(Parcel in) { return new InfostradaKeygen(in); @@ -62,4 +43,22 @@ public InfostradaKeygen[] newArray(int size) { } }; + public InfostradaKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private InfostradaKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword("2" + getMacAddress().toUpperCase(Locale.getDefault())); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InterCableKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InterCableKeygen.java index 23fccb3..5d70f73 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InterCableKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/InterCableKeygen.java @@ -18,51 +18,51 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; public class InterCableKeygen extends Keygen { - public InterCableKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public InterCableKeygen createFromParcel(Parcel in) { + return new InterCableKeygen(in); + } - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_nomac); - return null; - } - String wep = "m" + getMacAddress().substring(0, 10).toLowerCase(Locale.getDefault()); - String hex = getMacAddress().substring(10, 12); - int intValue = Integer.parseInt(hex, 16); - intValue += 1; // we add 1 and then convert again to hex - hex = Integer.toHexString(intValue).toLowerCase(Locale.getDefault()); - addPassword(wep+hex); - //There's a version where 2 is added so we repeat again - intValue += 1; // we add 1 and then convert again to hex - hex = Integer.toHexString(intValue).toLowerCase(Locale.getDefault()); - addPassword(wep+hex); - return getResults(); - } + public InterCableKeygen[] newArray(int size) { + return new InterCableKeygen[size]; + } + }; - private InterCableKeygen(Parcel in) { - super(in); - } + public InterCableKeygen(String ssid, String mac) { + super(ssid, mac); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public InterCableKeygen createFromParcel(Parcel in) { - return new InterCableKeygen(in); - } + private InterCableKeygen(Parcel in) { + super(in); + } - public InterCableKeygen[] newArray(int size) { - return new InterCableKeygen[size]; - } - }; + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + String wep = "m" + getMacAddress().substring(0, 10).toLowerCase(Locale.getDefault()); + String hex = getMacAddress().substring(10, 12); + int intValue = Integer.parseInt(hex, 16); + intValue += 1; // we add 1 and then convert again to hex + hex = Integer.toHexString(intValue).toLowerCase(Locale.getDefault()); + addPassword(wep + hex); + //There's a version where 2 is added so we repeat again + intValue += 1; // we add 1 and then convert again to hex + hex = Integer.toHexString(intValue).toLowerCase(Locale.getDefault()); + addPassword(wep + hex); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Keygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Keygen.java index 4f1cf3e..938e84b 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Keygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Keygen.java @@ -18,117 +18,115 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + import java.util.ArrayList; import java.util.List; import java.util.Locale; -import android.os.Parcel; -import android.os.Parcelable; - public abstract class Keygen implements Parcelable { - public static final int SUPPORTED = 2; - public static final int UNLIKELY_SUPPORTED = 1; - public static final int UNSUPPORTED = 0; - final private String ssidName; - final private String macAddress; - private List pwList; - - private boolean stopRequested = false; - private int errorCode; - - public Keygen(final String ssid, final String mac) { - this.ssidName = ssid; - this.macAddress = mac.replace(":", "").toUpperCase(Locale.getDefault()); - this.pwList = new ArrayList(); - } - - public synchronized boolean isStopRequested() { - return stopRequested; - } - - public synchronized void setStopRequested(boolean stopRequested) { - this.stopRequested = stopRequested; - } - - public String getMacAddress() { - return macAddress; - } - - public String getSsidName() { - return ssidName; - } - - protected void addPassword(final String key) { - if (!pwList.contains(key)) - pwList.add(key); - } - - protected List getResults() { - return pwList; - } - - abstract public List getKeys(); - - public int getErrorCode() { - return errorCode; - } - - public void setErrorCode(int errorCode) { - this.errorCode = errorCode; - } - - public int getSupportState() { - return SUPPORTED; - } - - public int describeContents() { - return 0; - } - - protected static String incrementMac(String mac, int increment) { - String incremented = Long.toHexString(Long.parseLong(mac, 16) + increment) - .toLowerCase(Locale.getDefault()); - //Any leading zeros will disappear in this process. - //TODO: add tests for this. - final int leadingZerosCount = mac.length() - incremented.length(); - for (int i = 0; i < leadingZerosCount; ++i) { - incremented = "0" + incremented; - } - return incremented; - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(ssidName); - dest.writeInt(macAddress != null ? 1 : 0); - if (macAddress != null) - dest.writeString(macAddress); - dest.writeInt(errorCode); - dest.writeInt(stopRequested ? 1 : 0); - dest.writeStringList(pwList); - } - - protected Keygen(Parcel in) { - ssidName = in.readString(); - if (in.readInt() == 1) - macAddress = in.readString(); - else - macAddress = ""; - errorCode = in.readInt(); - stopRequested = in.readInt() == 1; - pwList = in.createStringArrayList(); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - public Keygen[] newArray(int size) { - return new Keygen[size]; - } - - @Override - public Keygen createFromParcel(Parcel source) { - return null; - } - }; + public static final int SUPPORTED = 2; + public static final int UNLIKELY_SUPPORTED = 1; + public static final int UNSUPPORTED = 0; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + + public Keygen[] newArray(int size) { + return new Keygen[size]; + } + + @Override + public Keygen createFromParcel(Parcel source) { + return null; + } + }; + final private String ssidName; + final private String macAddress; + private List pwList; + private boolean stopRequested = false; + private int errorCode; + + public Keygen(final String ssid, final String mac) { + this.ssidName = ssid; + this.macAddress = mac.replace(":", "").toUpperCase(Locale.getDefault()); + this.pwList = new ArrayList(); + } + + protected Keygen(Parcel in) { + ssidName = in.readString(); + if (in.readInt() == 1) + macAddress = in.readString(); + else + macAddress = ""; + errorCode = in.readInt(); + stopRequested = in.readInt() == 1; + pwList = in.createStringArrayList(); + } + + protected static String incrementMac(String mac, int increment) { + String incremented = Long.toHexString(Long.parseLong(mac, 16) + increment) + .toLowerCase(Locale.getDefault()); + //Any leading zeros will disappear in this process. + //TODO: add tests for this. + final int leadingZerosCount = mac.length() - incremented.length(); + for (int i = 0; i < leadingZerosCount; ++i) { + incremented = "0" + incremented; + } + return incremented; + } + + public synchronized boolean isStopRequested() { + return stopRequested; + } + + public synchronized void setStopRequested(boolean stopRequested) { + this.stopRequested = stopRequested; + } + + public String getMacAddress() { + return macAddress; + } + + public String getSsidName() { + return ssidName; + } + + protected void addPassword(final String key) { + if (!pwList.contains(key)) + pwList.add(key); + } + + protected List getResults() { + return pwList; + } + + abstract public List getKeys(); + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public int getSupportState() { + return SUPPORTED; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(ssidName); + dest.writeInt(macAddress != null ? 1 : 0); + if (macAddress != null) + dest.writeString(macAddress); + dest.writeInt(errorCode); + dest.writeInt(stopRequested ? 1 : 0); + dest.writeStringList(pwList); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MaxcomKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MaxcomKeygen.java index 999b7f9..0f01336 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MaxcomKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MaxcomKeygen.java @@ -18,13 +18,13 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; /* * This is not actual an algorithm as @@ -32,24 +32,6 @@ */ public class MaxcomKeygen extends Keygen { - public MaxcomKeygen(String ssid, String mac) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword(getMacAddress().toUpperCase(Locale.getDefault())); - return getResults(); - } - - private MaxcomKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public MaxcomKeygen createFromParcel(Parcel in) { return new MaxcomKeygen(in); @@ -59,6 +41,24 @@ public MaxcomKeygen[] newArray(int size) { return new MaxcomKeygen[size]; } }; - + + public MaxcomKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private MaxcomKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword(getMacAddress().toUpperCase(Locale.getDefault())); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MegaredKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MegaredKeygen.java index dd595c0..9d50cf8 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MegaredKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MegaredKeygen.java @@ -18,12 +18,12 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /* * This is not actual an algorithm as @@ -31,24 +31,6 @@ */ public class MegaredKeygen extends Keygen { - public MegaredKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword(getMacAddress().substring(2)); - return getResults(); - } - - private MegaredKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public MegaredKeygen createFromParcel(Parcel in) { return new MegaredKeygen(in); @@ -58,6 +40,24 @@ public MegaredKeygen[] newArray(int size) { return new MegaredKeygen[size]; } }; - + + public MegaredKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private MegaredKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword(getMacAddress().substring(2)); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MeoPirelliKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MeoPirelliKeygen.java index 6846d82..080c979 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MeoPirelliKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/MeoPirelliKeygen.java @@ -18,56 +18,56 @@ */ package org.exobel.routerkeygen.algorithms; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; public class MeoPirelliKeygen extends ArnetPirelliKeygen { - public MeoPirelliKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public MeoPirelliKeygen createFromParcel(Parcel in) { + return new MeoPirelliKeygen(in); + } - @Override - public int getSupportState() { - if (getSsidName().matches("ADSLPT-AB[0-9]{5}")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } + public MeoPirelliKeygen[] newArray(int size) { + return new MeoPirelliKeygen[size]; + } + }; - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha256); - return null; - } - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_nomac); - return null; - } - generateKey(incrementMac(getMacAddress(), -1), 8); - return getResults(); - } + public MeoPirelliKeygen(String ssid, String mac) { + super(ssid, mac); + } - private MeoPirelliKeygen(Parcel in) { - super(in); - } + private MeoPirelliKeygen(Parcel in) { + super(in); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public MeoPirelliKeygen createFromParcel(Parcel in) { - return new MeoPirelliKeygen(in); - } + @Override + public int getSupportState() { + if (getSsidName().matches("ADSLPT-AB[0-9]{5}")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - public MeoPirelliKeygen[] newArray(int size) { - return new MeoPirelliKeygen[size]; - } - }; + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha256); + return null; + } + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + generateKey(incrementMac(getMacAddress(), -1), 8); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/NativeThomson.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/NativeThomson.java index c4766ab..9112e92 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/NativeThomson.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/NativeThomson.java @@ -18,139 +18,138 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.ArrayList; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.ArrayList; +import java.util.List; public class NativeThomson extends Keygen { - final private String ssidIdentifier; - final private List tasks; - - private final static int MAGIC_NUMBER = 46657; - - public NativeThomson(Keygen keygen) { - super(keygen.getSsidName(), keygen.getMacAddress()); - ssidIdentifier = keygen.getSsidName().substring( - keygen.getSsidName().length() - 6); - tasks = new ArrayList(); - } - - @Override - public synchronized void setStopRequested(boolean stopRequested) { - super.setStopRequested(stopRequested); - for (ThomsonTask t : tasks) - t.stopRequested = true; - } - - static { - System.loadLibrary("thomson"); - } - - /** - * Native processing without a dictionary. - */ - public native String[] thomson(byte[] essid, int start, int end); - - @Override - public List getKeys() { - if (ssidIdentifier.length() != 6) { - setErrorCode(R.string.msg_shortessid6); - return null; - } - byte[] routerESSID = new byte[3]; - - for (int i = 0; i < 6; i += 2) - routerESSID[i / 2] = (byte) ((Character.digit( - ssidIdentifier.charAt(i), 16) << 4) + Character.digit( - ssidIdentifier.charAt(i + 1), 16)); - int cores = Runtime.getRuntime().availableProcessors(); - if (cores <= 0) - cores = 1;// WTF?? HOW? :P - int work = MAGIC_NUMBER / cores; - int beggining = 0; - for (int i = 1; i < cores; ++i) { - tasks.add(new ThomsonTask(this, routerESSID, beggining, beggining - + work)); - tasks.get(tasks.size() - 1).start(); - beggining += work; - } - tasks.add(new ThomsonTask(this, routerESSID, beggining, MAGIC_NUMBER)); - tasks.get(tasks.size() - 1).start(); - for (ThomsonTask t : tasks) { - try { - t.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - continue; - } - final String[] results = t.results; - if ( t.error ) - setErrorCode(R.string.msg_err_native); - if (isStopRequested()) - return null; - for (int i = 0; i < results.length; ++i) - addPassword(results[i]); - } - if (getResults().size() == 0) - setErrorCode(R.string.msg_errnomatches); - return getResults(); - } - - private NativeThomson(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - tasks = new ArrayList(); - } - - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public NativeThomson createFromParcel(Parcel in) { - return new NativeThomson(in); - } - - public NativeThomson[] newArray(int size) { - return new NativeThomson[size]; - } - }; - - public static class ThomsonTask extends Thread { - private final NativeThomson keygen; - private final byte[] routerESSID; - private final int begin; - private final int end; - private boolean error = false; - private String[] results; - @SuppressWarnings("unused") - //This is read in the native code - private boolean stopRequested = false; - - static { - System.loadLibrary("thomson"); - } - - public ThomsonTask(NativeThomson keygen, byte[] routerESSID, int begin, - int end) { - this.keygen = keygen; - this.routerESSID = routerESSID; - this.begin = begin; - this.end = end; - } - - @Override - public void run() { - try { - results = keygen.thomson(routerESSID, begin, end); - } catch (Exception e) { - error = true; - } - } - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public NativeThomson createFromParcel(Parcel in) { + return new NativeThomson(in); + } + + public NativeThomson[] newArray(int size) { + return new NativeThomson[size]; + } + }; + private final static int MAGIC_NUMBER = 46657; + + static { + System.loadLibrary("thomson"); + } + + final private String ssidIdentifier; + final private List tasks; + + public NativeThomson(Keygen keygen) { + super(keygen.getSsidName(), keygen.getMacAddress()); + ssidIdentifier = keygen.getSsidName().substring( + keygen.getSsidName().length() - 6); + tasks = new ArrayList(); + } + + private NativeThomson(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + tasks = new ArrayList(); + } + + @Override + public synchronized void setStopRequested(boolean stopRequested) { + super.setStopRequested(stopRequested); + for (ThomsonTask t : tasks) + t.stopRequested = true; + } + + /** + * Native processing without a dictionary. + */ + public native String[] thomson(byte[] essid, int start, int end); + + @Override + public List getKeys() { + if (ssidIdentifier.length() != 6) { + setErrorCode(R.string.msg_shortessid6); + return null; + } + byte[] routerESSID = new byte[3]; + + for (int i = 0; i < 6; i += 2) + routerESSID[i / 2] = (byte) ((Character.digit( + ssidIdentifier.charAt(i), 16) << 4) + Character.digit( + ssidIdentifier.charAt(i + 1), 16)); + int cores = Runtime.getRuntime().availableProcessors(); + if (cores <= 0) + cores = 1;// WTF?? HOW? :P + int work = MAGIC_NUMBER / cores; + int beggining = 0; + for (int i = 1; i < cores; ++i) { + tasks.add(new ThomsonTask(this, routerESSID, beggining, beggining + + work)); + tasks.get(tasks.size() - 1).start(); + beggining += work; + } + tasks.add(new ThomsonTask(this, routerESSID, beggining, MAGIC_NUMBER)); + tasks.get(tasks.size() - 1).start(); + for (ThomsonTask t : tasks) { + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + continue; + } + final String[] results = t.results; + if (t.error) + setErrorCode(R.string.msg_err_native); + if (isStopRequested()) + return null; + for (int i = 0; i < results.length; ++i) + addPassword(results[i]); + } + if (getResults().size() == 0) + setErrorCode(R.string.msg_errnomatches); + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } + + public static class ThomsonTask extends Thread { + static { + System.loadLibrary("thomson"); + } + + private final NativeThomson keygen; + private final byte[] routerESSID; + private final int begin; + private final int end; + private boolean error = false; + private String[] results; + @SuppressWarnings("unused") + //This is read in the native code + private boolean stopRequested = false; + + public ThomsonTask(NativeThomson keygen, byte[] routerESSID, int begin, + int end) { + this.keygen = keygen; + this.routerESSID = routerESSID; + this.begin = begin; + this.end = end; + } + + @Override + public void run() { + try { + results = keygen.thomson(routerESSID, begin, end); + } catch (Exception e) { + error = true; + } + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OnoKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OnoKeygen.java index e9b0c48..d4d495d 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OnoKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OnoKeygen.java @@ -18,16 +18,17 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.utils.StringUtils; + import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Locale; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.utils.StringUtils; - -import android.os.Parcel; -import android.os.Parcelable; /* * The algorithm for the type of network * whose SSID must be in the form of [pP]1XXXXXX0000X @@ -43,74 +44,6 @@ * */ public class OnoKeygen extends Keygen { - private MessageDigest md; - - public OnoKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if ( getSsidName().length() != 13 ) - { - setErrorCode(R.string.msg_shortessid13); - return null; - } - String val = getSsidName().substring(0,11)+ - Integer.toString(Integer.parseInt(getSsidName().substring(11))+1); - if ( val.length() < 13 ) - val = getSsidName().substring(0,11)+ "0" + getSsidName().substring(11); - int [] pseed = new int[4]; - pseed[0] = 0; - pseed[1] = 0; - pseed[2] = 0; - pseed[3] = 0; - int randNumber = 0; - String key = ""; - for (int i = 0; i < val.length(); i++) - { - pseed[i%4] ^= (int) val.charAt(i); - } - randNumber = pseed[0] | (pseed[1] << 8) | (pseed[2] << 16) | (pseed[3] << 24); - short tmp = 0; - for (int j = 0; j < 5; j++) - { - randNumber = (randNumber * 0x343fd + 0x269ec3) & 0xffffffff; - tmp = (short) ((randNumber >> 16) & 0xff); - key += StringUtils.getHexString(tmp).toUpperCase(Locale.getDefault()); - } - addPassword(key); - key = ""; - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - md.reset(); - md.update(padto64(val).getBytes()); - byte [] hash = md.digest(); - for ( int i = 0 ; i < 13 ; ++i ) - key += StringUtils.getHexString((short)hash[i]); - addPassword(key.toUpperCase(Locale.getDefault())); - return getResults(); - } - - - private String padto64( String val ){ - if ( val.equals("") ) - return ""; - String ret = ""; - for ( int i = 0; i < ( 1 + (64 / (val.length())) ) ; ++i) - ret += val; - return ret.substring(0,64); - } - - - private OnoKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public OnoKeygen createFromParcel(Parcel in) { return new OnoKeygen(in); @@ -120,5 +53,68 @@ public OnoKeygen[] newArray(int size) { return new OnoKeygen[size]; } }; + private MessageDigest md; + + public OnoKeygen(String ssid, String mac) { + super(ssid, mac); + } + + + private OnoKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getSsidName().length() != 13) { + setErrorCode(R.string.msg_shortessid13); + return null; + } + String val = getSsidName().substring(0, 11) + + Integer.toString(Integer.parseInt(getSsidName().substring(11)) + 1); + if (val.length() < 13) + val = getSsidName().substring(0, 11) + "0" + getSsidName().substring(11); + int[] pseed = new int[4]; + pseed[0] = 0; + pseed[1] = 0; + pseed[2] = 0; + pseed[3] = 0; + int randNumber = 0; + String key = ""; + for (int i = 0; i < val.length(); i++) { + pseed[i % 4] ^= (int) val.charAt(i); + } + randNumber = pseed[0] | (pseed[1] << 8) | (pseed[2] << 16) | (pseed[3] << 24); + short tmp = 0; + for (int j = 0; j < 5; j++) { + randNumber = (randNumber * 0x343fd + 0x269ec3) & 0xffffffff; + tmp = (short) ((randNumber >> 16) & 0xff); + key += StringUtils.getHexString(tmp).toUpperCase(Locale.getDefault()); + } + addPassword(key); + key = ""; + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + md.reset(); + md.update(padto64(val).getBytes()); + byte[] hash = md.digest(); + for (int i = 0; i < 13; ++i) + key += StringUtils.getHexString((short) hash[i]); + addPassword(key.toUpperCase(Locale.getDefault())); + return getResults(); + } + + private String padto64(String val) { + if (val.equals("")) + return ""; + String ret = ""; + for (int i = 0; i < (1 + (64 / (val.length()))); ++i) + ret += val; + return ret.substring(0, 64); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteBAUDKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteBAUDKeygen.java index 7dd7f6f..4dad94e 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteBAUDKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteBAUDKeygen.java @@ -1,34 +1,15 @@ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; public class OteBAUDKeygen extends Keygen { - public OteBAUDKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if ( getMacAddress().length() != 12 ) - { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword("0"+getMacAddress().toLowerCase(Locale.getDefault())); - return getResults(); - } - - private OteBAUDKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public OteBAUDKeygen createFromParcel(Parcel in) { return new OteBAUDKeygen(in); @@ -39,5 +20,23 @@ public OteBAUDKeygen[] newArray(int size) { } }; + public OteBAUDKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private OteBAUDKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword("0" + getMacAddress().toLowerCase(Locale.getDefault())); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteHuaweiKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteHuaweiKeygen.java index b9795e6..c28ecc6 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteHuaweiKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteHuaweiKeygen.java @@ -1,66 +1,65 @@ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; public class OteHuaweiKeygen extends Keygen { - public final static int MAGIC_NUMBER = 65535; - private final String magicValues; - - public OteHuaweiKeygen(String ssid, String mac, - String magicValues) { - super(ssid, mac); - this.magicValues = magicValues; - } + public final static int MAGIC_NUMBER = 65535; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public OteHuaweiKeygen createFromParcel(Parcel in) { + return new OteHuaweiKeygen(in); + } - @Override - public List getKeys() { - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - final String[] magic = magicValues.split(" "); - final String series = mac.substring(0, 2) + mac.substring(6, 8); - final int point; - if (series.equals("E8FD")) - point = 0; - else if (series.equals("E8F5")) - point = 1; - else if (series.equals("E8F6")) - point = 2; - else - return getResults(); - if (point >= magic.length) - return getResults(); - final String pass = "000000" + magic[point]; - addPassword(pass.substring(pass.length() - 8)); - return getResults(); - } + public OteHuaweiKeygen[] newArray(int size) { + return new OteHuaweiKeygen[size]; + } + }; + private final String magicValues; - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(magicValues); - } + public OteHuaweiKeygen(String ssid, String mac, + String magicValues) { + super(ssid, mac); + this.magicValues = magicValues; + } - private OteHuaweiKeygen(Parcel in) { - super(in); - magicValues = in.readString(); - } + private OteHuaweiKeygen(Parcel in) { + super(in); + magicValues = in.readString(); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public OteHuaweiKeygen createFromParcel(Parcel in) { - return new OteHuaweiKeygen(in); - } + @Override + public List getKeys() { + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + final String[] magic = magicValues.split(" "); + final String series = mac.substring(0, 2) + mac.substring(6, 8); + final int point; + if (series.equals("E8FD")) + point = 0; + else if (series.equals("E8F5")) + point = 1; + else if (series.equals("E8F6")) + point = 2; + else + return getResults(); + if (point >= magic.length) + return getResults(); + final String pass = "000000" + magic[point]; + addPassword(pass.substring(pass.length() - 8)); + return getResults(); + } - public OteHuaweiKeygen[] newArray(int size) { - return new OteHuaweiKeygen[size]; - } - }; + @Override + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(magicValues); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteKeygen.java index dedc3d2..08b98a2 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/OteKeygen.java @@ -18,12 +18,12 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; - import android.os.Parcel; import android.os.Parcelable; +import java.util.List; +import java.util.Locale; + /* * This is not actual an algorithm as * it is just needed to use the mac address. @@ -31,38 +31,38 @@ */ public class OteKeygen extends Keygen { - public OteKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public OteKeygen createFromParcel(Parcel in) { + return new OteKeygen(in); + } - @Override - public List getKeys() { - if (getMacAddress().length() == 12) { - addPassword(getMacAddress().toLowerCase(Locale.getDefault())); - } else { - final String ssidIdentifier = getSsidName().substring(getSsidName().length()-4); - addPassword("c87b5b" + ssidIdentifier); - addPassword("fcc897" + ssidIdentifier); - addPassword("681ab2" + ssidIdentifier); - addPassword("b075d5" + ssidIdentifier); - addPassword("384608" + ssidIdentifier); - } - return getResults(); - } + public OteKeygen[] newArray(int size) { + return new OteKeygen[size]; + } + }; - private OteKeygen(Parcel in) { - super(in); + public OteKeygen(String ssid, String mac) { + super(ssid, mac); + } - } + private OteKeygen(Parcel in) { + super(in); - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public OteKeygen createFromParcel(Parcel in) { - return new OteKeygen(in); - } + } - public OteKeygen[] newArray(int size) { - return new OteKeygen[size]; - } - }; + @Override + public List getKeys() { + if (getMacAddress().length() == 12) { + addPassword(getMacAddress().toLowerCase(Locale.getDefault())); + } else { + final String ssidIdentifier = getSsidName().substring(getSsidName().length() - 4); + addPassword("c87b5b" + ssidIdentifier); + addPassword("fcc897" + ssidIdentifier); + addPassword("681ab2" + ssidIdentifier); + addPassword("b075d5" + ssidIdentifier); + addPassword("384608" + ssidIdentifier); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PBSKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PBSKeygen.java index fe8556b..b569ce2 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PBSKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PBSKeygen.java @@ -18,99 +18,95 @@ */ package org.exobel.routerkeygen.algorithms; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; /** * The link for this algorithm is: * http://sviehb.wordpress.com/2011/12/04/prg-eav4202n * -default-wpa-key-algorithm/ - * + * * @author Rui Araújo - * */ public class PBSKeygen extends Keygen { - transient private MessageDigest md; - - public PBSKeygen(String ssid, String mac) { - super(ssid, mac); - } - - @Override - public int getSupportState() { - final String mac = getMacAddress(); - if (mac.length() != 12) - return UNSUPPORTED; - //Support seems to be very rare if it exist at all. - /*final String ssidEnd = Integer.toHexString(Integer.parseInt(mac - .substring(6),16) - 5); + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public PBSKeygen createFromParcel(Parcel in) { + return new PBSKeygen(in); + } + + public PBSKeygen[] newArray(int size) { + return new PBSKeygen[size]; + } + }; + final static byte[] saltSHA256 = {0x54, 0x45, 0x4F, 0x74, 0x65, 0x6C, + (byte) 0xB6, (byte) 0xD9, (byte) 0x86, (byte) 0x96, (byte) 0x8D, + 0x34, 0x45, (byte) 0xD2, 0x3B, 0x15, (byte) 0xCA, (byte) 0xAF, + 0x12, (byte) 0x84, 0x02, (byte) 0xAC, 0x56, 0x00, 0x05, + (byte) 0xCE, 0x20, 0x75, (byte) 0x94, 0x3F, (byte) 0xDC, + (byte) 0xE8}; + final static String lookup = "0123456789ABCDEFGHIKJLMNOPQRSTUVWXYZabcdefghikjlmnopqrstuvwxyz"; + transient private MessageDigest md; + + public PBSKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private PBSKeygen(Parcel in) { + super(in); + } + + @Override + public int getSupportState() { + final String mac = getMacAddress(); + if (mac.length() != 12) + return UNSUPPORTED; + //Support seems to be very rare if it exist at all. + /*final String ssidEnd = Integer.toHexString(Integer.parseInt(mac + .substring(6),16) - 5); final String ssid = getSsidName(); if (ssid.substring(4).equalsIgnoreCase(ssidEnd)) return SUPPORTED;*/ - return UNLIKELY_SUPPORTED; - } - - final static byte[] saltSHA256 = { 0x54, 0x45, 0x4F, 0x74, 0x65, 0x6C, - (byte) 0xB6, (byte) 0xD9, (byte) 0x86, (byte) 0x96, (byte) 0x8D, - 0x34, 0x45, (byte) 0xD2, 0x3B, 0x15, (byte) 0xCA, (byte) 0xAF, - 0x12, (byte) 0x84, 0x02, (byte) 0xAC, 0x56, 0x00, 0x05, - (byte) 0xCE, 0x20, 0x75, (byte) 0x94, 0x3F, (byte) 0xDC, - (byte) 0xE8 }; - - final static String lookup = "0123456789ABCDEFGHIKJLMNOPQRSTUVWXYZabcdefghikjlmnopqrstuvwxyz"; - - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha256); - return null; - } - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - - byte[] macHex = new byte[6]; - for (int i = 0; i < 12; i += 2) - macHex[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + Character - .digit(mac.charAt(i + 1), 16)); - macHex[5] -= 5; - - md.reset(); - md.update(saltSHA256); - md.update(macHex); - byte[] hash = md.digest(); - StringBuilder key = new StringBuilder(); - for (int i = 0; i < 13; ++i) { - key.append(lookup.charAt((hash[i] >= 0 ? hash[i] : 256 + hash[i]) - % lookup.length())); - } - addPassword(key.toString()); - return getResults(); - } - - private PBSKeygen(Parcel in) { - super(in); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public PBSKeygen createFromParcel(Parcel in) { - return new PBSKeygen(in); - } - - public PBSKeygen[] newArray(int size) { - return new PBSKeygen[size]; - } - }; + return UNLIKELY_SUPPORTED; + } + + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha256); + return null; + } + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + + byte[] macHex = new byte[6]; + for (int i = 0; i < 12; i += 2) + macHex[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + Character + .digit(mac.charAt(i + 1), 16)); + macHex[5] -= 5; + + md.reset(); + md.update(saltSHA256); + md.update(macHex); + byte[] hash = md.digest(); + StringBuilder key = new StringBuilder(); + for (int i = 0; i < 13; ++i) { + key.append(lookup.charAt((hash[i] >= 0 ? hash[i] : 256 + hash[i]) + % lookup.length())); + } + addPassword(key.toString()); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PirelliKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PirelliKeygen.java index eb9a085..cb19379 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PirelliKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PirelliKeygen.java @@ -18,84 +18,20 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.utils.StringUtils; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.utils.StringUtils; - -import android.os.Parcel; -import android.os.Parcelable; +public class PirelliKeygen extends Keygen { -public class PirelliKeygen extends Keygen{ - - private MessageDigest md; - final private String ssidIdentifier; - - public PirelliKeygen(String ssid, String mac ) { - super(ssid, mac); - ssidIdentifier = ssid.substring(ssid.length()-12); - } - - final static byte[] saltMD5 = { - 0x22, 0x33, 0x11, 0x34, 0x02, - (byte) 0x81, (byte) 0xFA, 0x22, 0x11, 0x41, - 0x68, 0x11, 0x12, 0x01, 0x05, - 0x22, 0x71, 0x42, 0x10, 0x66 }; - - - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - if ( ssidIdentifier.length() != 12 ) - { - setErrorCode(R.string.msg_errpirelli); - return null; - } - - byte [] routerESSID = new byte[6]; - for (int i = 0; i < 12; i += 2) - routerESSID[i / 2] = (byte) ((Character.digit(ssidIdentifier.charAt(i), 16) << 4) - + Character.digit(ssidIdentifier.charAt(i + 1), 16)); - - md.reset(); - md.update(routerESSID); - md.update(saltMD5); - byte [] hash = md.digest(); - short [] key = new short[5]; - /*Grouping in five groups of five bits*/ - key[0] = (short)( (hash[0] & 0xF8) >> 3 ); - key[1] = (short)(( (hash[0] & 0x07) << 2) | ( (hash[1] & 0xC0) >>6 )); - key[2] = (short)((hash[1] & 0x3E) >> 1 ); - key[3] = (short)(( (hash[1] & 0x01) << 4) | ((hash[2] & 0xF0) >> 4)); - key[4] = (short)(( (hash[2] & 0x0F) << 1) | ((hash[3] & 0x80) >> 7) ); - for ( int i = 0 ; i < 5 ; ++i ) - if ( key[i] >= 0x0A ) - key[i] += 0x57; - try { - addPassword(StringUtils.getHexString(key)); - } catch (UnsupportedEncodingException e) {} - return getResults(); - } - - private PirelliKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } - - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public PirelliKeygen createFromParcel(Parcel in) { return new PirelliKeygen(in); @@ -105,6 +41,68 @@ public PirelliKeygen[] newArray(int size) { return new PirelliKeygen[size]; } }; + final static byte[] saltMD5 = { + 0x22, 0x33, 0x11, 0x34, 0x02, + (byte) 0x81, (byte) 0xFA, 0x22, 0x11, 0x41, + 0x68, 0x11, 0x12, 0x01, 0x05, + 0x22, 0x71, 0x42, 0x10, 0x66}; + final private String ssidIdentifier; + private MessageDigest md; + + + public PirelliKeygen(String ssid, String mac) { + super(ssid, mac); + ssidIdentifier = ssid.substring(ssid.length() - 12); + } + + private PirelliKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } + + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + if (ssidIdentifier.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + + byte[] routerESSID = new byte[6]; + for (int i = 0; i < 12; i += 2) + routerESSID[i / 2] = (byte) ((Character.digit(ssidIdentifier.charAt(i), 16) << 4) + + Character.digit(ssidIdentifier.charAt(i + 1), 16)); + + md.reset(); + md.update(routerESSID); + md.update(saltMD5); + byte[] hash = md.digest(); + short[] key = new short[5]; + /*Grouping in five groups of five bits*/ + key[0] = (short) ((hash[0] & 0xF8) >> 3); + key[1] = (short) (((hash[0] & 0x07) << 2) | ((hash[1] & 0xC0) >> 6)); + key[2] = (short) ((hash[1] & 0x3E) >> 1); + key[3] = (short) (((hash[1] & 0x01) << 4) | ((hash[2] & 0xF0) >> 4)); + key[4] = (short) (((hash[2] & 0x0F) << 1) | ((hash[3] & 0x80) >> 7)); + for (int i = 0; i < 5; ++i) + if (key[i] >= 0x0A) + key[i] += 0x57; + try { + addPassword(StringUtils.getHexString(key)); + } catch (UnsupportedEncodingException e) { + } + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PtvKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PtvKeygen.java index 88f9f41..fbba82a 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PtvKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/PtvKeygen.java @@ -18,12 +18,12 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /* * This is not actual an algorithm as @@ -31,24 +31,6 @@ */ public class PtvKeygen extends Keygen { - public PtvKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword(getMacAddress().substring(2)); - return getResults(); - } - - private PtvKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public PtvKeygen createFromParcel(Parcel in) { return new PtvKeygen(in); @@ -58,6 +40,24 @@ public PtvKeygen[] newArray(int size) { return new PtvKeygen[size]; } }; - + + public PtvKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private PtvKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword(getMacAddress().substring(2)); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SitecomKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SitecomKeygen.java index 63709cf..ed3b18c 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SitecomKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SitecomKeygen.java @@ -1,77 +1,77 @@ package org.exobel.routerkeygen.algorithms; +import org.exobel.routerkeygen.R; + import java.util.List; import java.util.Locale; -import org.exobel.routerkeygen.R; - public class SitecomKeygen extends Keygen { - private final static String CHARSET = "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; // without - // i,l,o,0 + private final static String CHARSET = "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; // without + // i,l,o,0 - public SitecomKeygen(String ssid, String mac) { - super(ssid, mac); - } + public SitecomKeygen(String ssid, String mac) { + super(ssid, mac); + } - @Override - public int getSupportState() { - if (getSsidName().toLowerCase(Locale.getDefault()) - .startsWith("sitecom")) - return SUPPORTED; - return UNLIKELY_SUPPORTED; - } + @Override + public int getSupportState() { + if (getSsidName().toLowerCase(Locale.getDefault()) + .startsWith("sitecom")) + return SUPPORTED; + return UNLIKELY_SUPPORTED; + } - private void generateKey(String mac) { - StringBuilder key = new StringBuilder(); - int numericMac = Integer.parseInt("0" - + mac.substring(6).split("[A-Fa-f]")[0]); - key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(5)) * (mac - .charAt(9) + mac.charAt(3) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(6)) * (mac - .charAt(8) + mac.charAt(10) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(3) + mac.charAt(5)) * (mac - .charAt(7) + mac.charAt(9) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(7) + mac.charAt(6)) * (mac - .charAt(5) + mac.charAt(4) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(7) + mac.charAt(6)) * (mac - .charAt(8) + mac.charAt(9) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(5)) * (mac - .charAt(3) + mac.charAt(4) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(4)) * (mac - .charAt(6) + mac.charAt(8) + mac.charAt(11))) - % CHARSET.length())); - key.append(CHARSET.charAt(((numericMac + mac.charAt(10) + mac - .charAt(11)) * (mac.charAt(7) + mac.charAt(8) + mac.charAt(11))) - % CHARSET.length())); - addPassword(key.toString()); - } + private void generateKey(String mac) { + StringBuilder key = new StringBuilder(); + int numericMac = Integer.parseInt("0" + + mac.substring(6).split("[A-Fa-f]")[0]); + key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(5)) * (mac + .charAt(9) + mac.charAt(3) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(6)) * (mac + .charAt(8) + mac.charAt(10) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(3) + mac.charAt(5)) * (mac + .charAt(7) + mac.charAt(9) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(7) + mac.charAt(6)) * (mac + .charAt(5) + mac.charAt(4) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(7) + mac.charAt(6)) * (mac + .charAt(8) + mac.charAt(9) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(5)) * (mac + .charAt(3) + mac.charAt(4) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(11) + mac.charAt(4)) * (mac + .charAt(6) + mac.charAt(8) + mac.charAt(11))) + % CHARSET.length())); + key.append(CHARSET.charAt(((numericMac + mac.charAt(10) + mac + .charAt(11)) * (mac.charAt(7) + mac.charAt(8) + mac.charAt(11))) + % CHARSET.length())); + addPassword(key.toString()); + } - @Override - public List getKeys() { - String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - generateKey(mac); - final String shortMac = mac.substring(0, 11); - int lastChar = Integer.parseInt(mac.substring(11), 16); - lastChar = (lastChar + 1) % 0x10; - generateKey(shortMac - + Integer.toHexString(lastChar) - .toUpperCase(Locale.getDefault())); - lastChar = (lastChar + 1) % 0x10; - generateKey(shortMac - + Integer.toHexString(lastChar) - .toUpperCase(Locale.getDefault())); - return getResults(); - } + @Override + public List getKeys() { + String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + generateKey(mac); + final String shortMac = mac.substring(0, 11); + int lastChar = Integer.parseInt(mac.substring(11), 16); + lastChar = (lastChar + 1) % 0x10; + generateKey(shortMac + + Integer.toHexString(lastChar) + .toUpperCase(Locale.getDefault())); + lastChar = (lastChar + 1) % 0x10; + generateKey(shortMac + + Integer.toHexString(lastChar) + .toUpperCase(Locale.getDefault())); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SkyV1Keygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SkyV1Keygen.java index e97990c..2a49cf4 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SkyV1Keygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/SkyV1Keygen.java @@ -18,14 +18,14 @@ */ package org.exobel.routerkeygen.algorithms; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; /* @@ -37,48 +37,8 @@ * Use theses numbers, modulus 26, to find the correct letter * and append to the key. */ -public class SkyV1Keygen extends Keygen{ - - private MessageDigest md; - public SkyV1Keygen(String ssid, String mac ) { - super(ssid, mac); - } - - final static String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +public class SkyV1Keygen extends Keygen { - - @Override - public List getKeys() { - if ( getMacAddress().length() != 12 ) - { - setErrorCode(R.string.msg_nomac); - return null; - } - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - md.reset(); - md.update(getMacAddress().getBytes()); - byte [] hash = md.digest(); - String key =""; - for ( int i = 1 ; i <= 15 ; i += 2 ) - { - int index = hash[i] & 0xFF; - index %= 26; - key += ALPHABET.substring(index,index+1 ); - } - - addPassword(key); - return getResults(); - } - - private SkyV1Keygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public SkyV1Keygen createFromParcel(Parcel in) { return new SkyV1Keygen(in); @@ -88,5 +48,42 @@ public SkyV1Keygen[] newArray(int size) { return new SkyV1Keygen[size]; } }; - + final static String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private MessageDigest md; + + + public SkyV1Keygen(String ssid, String mac) { + super(ssid, mac); + } + + private SkyV1Keygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + md.reset(); + md.update(getMacAddress().getBytes()); + byte[] hash = md.digest(); + String key = ""; + for (int i = 1; i <= 15; i += 2) { + int index = hash[i] & 0xFF; + index %= 26; + key += ALPHABET.substring(index, index + 1); + } + + addPassword(key); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Speedport500Keygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Speedport500Keygen.java index 26da792..9a90c98 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Speedport500Keygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Speedport500Keygen.java @@ -18,54 +18,53 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /** * The algortihm is described on the link below * Link:http://www.wardriving-forum. * de/wiki/Standardpassw%C3%B6rter#Diverse_Speedport-Modelle - * + * * @author Rui Araújo - * */ public class Speedport500Keygen extends Keygen { - public Speedport500Keygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Speedport500Keygen createFromParcel(Parcel in) { + return new Speedport500Keygen(in); + } - @Override - public List getKeys() { - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - final String ssid = getSsidName(); - final String block = ssid.charAt(10) + mac.substring(9); - for (int x = 0; x < 10; ++x) - for (int y = 0; y < 10; ++y) - for (int z = 0; z < 10; ++z) - addPassword("SP-" + ssid.charAt(9) + z + block + x + y + z); - return getResults(); - } + public Speedport500Keygen[] newArray(int size) { + return new Speedport500Keygen[size]; + } + }; - private Speedport500Keygen(Parcel in) { - super(in); - } + public Speedport500Keygen(String ssid, String mac) { + super(ssid, mac); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public Speedport500Keygen createFromParcel(Parcel in) { - return new Speedport500Keygen(in); - } + private Speedport500Keygen(Parcel in) { + super(in); + } - public Speedport500Keygen[] newArray(int size) { - return new Speedport500Keygen[size]; - } - }; + @Override + public List getKeys() { + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + final String ssid = getSsidName(); + final String block = ssid.charAt(10) + mac.substring(9); + for (int x = 0; x < 10; ++x) + for (int y = 0; y < 10; ++y) + for (int z = 0; z < 10; ++z) + addPassword("SP-" + ssid.charAt(9) + z + block + x + y + z); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TecomKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TecomKeygen.java index 3c22f01..375c215 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TecomKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TecomKeygen.java @@ -18,16 +18,16 @@ */ package org.exobel.routerkeygen.algorithms; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; import org.exobel.routerkeygen.utils.StringUtils; -import android.os.Parcel; -import android.os.Parcelable; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; /* * This is the algorithm to generate the WPA passphrase @@ -37,35 +37,6 @@ */ public class TecomKeygen extends Keygen { - private MessageDigest md; - - public TecomKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nosha1); - return null; - } - md.reset(); - md.update(getSsidName().getBytes()); - byte [] hash = md.digest(); - try { - addPassword(StringUtils.getHexString(hash).substring(0,26)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return getResults(); - } - - private TecomKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public TecomKeygen createFromParcel(Parcel in) { return new TecomKeygen(in); @@ -75,4 +46,32 @@ public TecomKeygen[] newArray(int size) { return new TecomKeygen[size]; } }; + private MessageDigest md; + + public TecomKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private TecomKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nosha1); + return null; + } + md.reset(); + md.update(getSsidName().getBytes()); + byte[] hash = md.digest(); + try { + addPassword(StringUtils.getHexString(hash).substring(0, 26)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TeleTuKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TeleTuKeygen.java index 07d5ce7..be9e216 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TeleTuKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TeleTuKeygen.java @@ -18,13 +18,14 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; import org.exobel.routerkeygen.config.TeleTuMagicInfo; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; + /* * Using the last 6 bytes of the mac address which should be in a certain range * in the config file, we calculate the end of the serial number @@ -35,48 +36,47 @@ */ public class TeleTuKeygen extends Keygen { - final private TeleTuMagicInfo magicInfo; - - public TeleTuKeygen(String ssid, String mac, - TeleTuMagicInfo magicInfo) { - super(ssid, mac); - this.magicInfo = magicInfo; - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public TeleTuKeygen createFromParcel(Parcel in) { + return new TeleTuKeygen(in); + } - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - String serialEnd = Integer.toString((Integer.parseInt(getMacAddress() - .substring(6), 16) - magicInfo.getBase()) - / magicInfo.getDivider()); - while (serialEnd.length() < 7) { - serialEnd = "0" + serialEnd; - } - addPassword(magicInfo.getSerial() + "Y" + serialEnd); - return getResults(); - } + public TeleTuKeygen[] newArray(int size) { + return new TeleTuKeygen[size]; + } + }; + final private TeleTuMagicInfo magicInfo; - private TeleTuKeygen(Parcel in) { - super(in); - magicInfo = in.readParcelable(TeleTuMagicInfo.class.getClassLoader()); - } + public TeleTuKeygen(String ssid, String mac, + TeleTuMagicInfo magicInfo) { + super(ssid, mac); + this.magicInfo = magicInfo; + } - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeParcelable(magicInfo, flags); - } + private TeleTuKeygen(Parcel in) { + super(in); + magicInfo = in.readParcelable(TeleTuMagicInfo.class.getClassLoader()); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public TeleTuKeygen createFromParcel(Parcel in) { - return new TeleTuKeygen(in); - } + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + String serialEnd = Integer.toString((Integer.parseInt(getMacAddress() + .substring(6), 16) - magicInfo.getBase()) + / magicInfo.getDivider()); + while (serialEnd.length() < 7) { + serialEnd = "0" + serialEnd; + } + addPassword(magicInfo.getSerial() + "Y" + serialEnd); + return getResults(); + } - public TeleTuKeygen[] newArray(int size) { - return new TeleTuKeygen[size]; - } - }; + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeParcelable(magicInfo, flags); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TelseyKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TelseyKeygen.java index b1d16d5..38c5f53 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TelseyKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TelseyKeygen.java @@ -18,13 +18,13 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.JenkinsHash; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /* * The algorithm for the FASTWEB Telsey @@ -48,200 +48,8 @@ * http://www.pcpedia.it/Hacking/algoritmi-di-generazione-wpa-alice-e-fastweb-e-lavidita-del-sapere.html * http://wifiresearchers.wordpress.com/2010/09/09/telsey-fastweb-full-disclosure/ */ -public class TelseyKeygen extends Keygen implements Parcelable{ - - public TelseyKeygen(String ssid, String mac ) { - super(ssid, mac); - } - - //Scramble Function - long[] scrambler(String mac){ - long[]vector = new long [64]; - byte [] macValue = new byte[6]; - for (int i = 0; i < 12; i += 2) - macValue[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) - + Character.digit(mac.charAt(i + 1), 16)); - - vector[0] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[1] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[2] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[3] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[4] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[5] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[5] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[6] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[7] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[8] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[9] =0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[10]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[11]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[12]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[13]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[14]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[15]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[16]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[17]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[18]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[5] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[19]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[20]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[21]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[22]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[23]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[24]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[25]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[26]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[27]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[28]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[29]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[30]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[31]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[32]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[33]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[34]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[35]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[5] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[36]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[37]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[38]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[39]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[40]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[41]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[5] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[42]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[43]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[44]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[45]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[46]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[47]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[48]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[1] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[49]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[50]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[51]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[52]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[53]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[5] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[54]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[55]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[0] ) << 8 )|( 0xFF & macValue[4] ) )); - vector[56]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[5] ) )); - vector[57]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[4] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[58]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[4] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[0] ) )); - vector[59]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[2] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[5] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[60]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[3] ) << 24 )|( ( 0xFF & macValue[1] ) << 16 ) | - ( ( 0xFF & macValue[2] ) << 8 )|( 0xFF & macValue[3] ) )); - vector[61]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[0] ) << 16 ) | - ( ( 0xFF & macValue[1] ) << 8 )|( 0xFF & macValue[2] ) )); - vector[62]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[5] ) << 24 )|( ( 0xFF & macValue[3] ) << 16 ) | - ( ( 0xFF & macValue[4] ) << 8 )|( 0xFF & macValue[1] ) )); - vector[63]=0xFFFFFFFFL & ((long)( ( ( 0xFF & macValue[0] ) << 24 )|( ( 0xFF & macValue[2] ) << 16 ) | - ( ( 0xFF & macValue[3] ) << 8 )|( 0xFF & macValue[0] ) )); - - return vector; - } - - @Override - public List getKeys() { - JenkinsHash hash = new JenkinsHash(); - if ( getMacAddress().length() < 12 ) - { - setErrorCode(R.string.msg_nomac); - return null; - } - long [] key = scrambler(getMacAddress()); - long seed = 0; - - for (int x = 0; x < 64; x++) { - seed = hash.hashword(key,x, seed); - } - - String S1 = Long.toHexString(seed); - while ( S1.length() < 8 ) - S1 = "0" + S1; - - - for ( int x = 0; x <64; x++) { - if (x <8) - key[x] =( key[x]<< 3 ) & 0xFFFFFFFF; - else if ( x<16) - key[x] >>>= 5; - else if (x < 32 ) - key[x] >>>= 2; - else - key[x] =( key[x]<< 7 ) & 0xFFFFFFFF; - } - - seed = 0; - for (int x = 0; x < 64; x++) { - seed = hash.hashword(key, x, seed); - } - String S2 = Long.toHexString(seed); - while ( S2.length() < 8 ) - S2 = "0" + S2; - addPassword(S1.substring(S1.length() - 5) + S2.substring(0, 5)); - return getResults(); - } - - - - private TelseyKeygen(Parcel in) { - super(in); - } - +public class TelseyKeygen extends Keygen implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public TelseyKeygen createFromParcel(Parcel in) { return new TelseyKeygen(in); @@ -251,5 +59,194 @@ public TelseyKeygen[] newArray(int size) { return new TelseyKeygen[size]; } }; - + + public TelseyKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private TelseyKeygen(Parcel in) { + super(in); + } + + //Scramble Function + long[] scrambler(String mac) { + long[] vector = new long[64]; + byte[] macValue = new byte[6]; + for (int i = 0; i < 12; i += 2) + macValue[i / 2] = (byte) ((Character.digit(mac.charAt(i), 16) << 4) + + Character.digit(mac.charAt(i + 1), 16)); + + vector[0] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[5]))); + vector[1] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[5]))); + vector[2] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[2]))); + vector[3] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[2]))); + vector[4] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[0]))); + vector[5] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[5]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[1]))); + vector[6] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[1]))); + vector[7] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[0]))); + vector[8] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[2]))); + vector[9] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[4]))); + vector[10] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[3]))); + vector[11] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[5]))); + vector[12] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[5]))); + vector[13] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[1]))); + vector[14] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[3]))); + vector[15] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[2]))); + vector[16] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[4]))); + vector[17] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[0]))); + vector[18] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[5]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[5]))); + vector[19] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[5]))); + vector[20] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[4]))); + vector[21] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[4]))); + vector[22] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[3]))); + vector[23] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[3]))); + vector[24] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[0]))); + vector[25] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[1]))); + vector[26] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[5]))); + vector[27] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[3]))); + vector[28] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[4]))); + vector[29] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[2]))); + vector[30] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[5]))); + vector[31] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[4]))); + vector[32] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[2]))); + vector[33] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[0]))); + vector[34] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[1]))); + vector[35] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[5]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[0]))); + vector[36] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[0]))); + vector[37] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[2]))); + vector[38] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[1]))); + vector[39] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[3]))); + vector[40] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[4]))); + vector[41] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[5]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[5]))); + vector[42] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[0]))); + vector[43] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[4]))); + vector[44] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[2]))); + vector[45] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[3]))); + vector[46] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[1]))); + vector[47] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[5]))); + vector[48] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[1]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[0]))); + vector[49] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[1]))); + vector[50] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[2]))); + vector[51] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[3]))); + vector[52] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[5]))); + vector[53] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[5]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[4]))); + vector[54] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[5]))); + vector[55] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[0]) << 8) | (0xFF & macValue[4]))); + vector[56] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[5]))); + vector[57] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[4]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[1]))); + vector[58] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[4]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[0]))); + vector[59] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[2]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[5]) << 8) | (0xFF & macValue[1]))); + vector[60] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[3]) << 24) | ((0xFF & macValue[1]) << 16) | + ((0xFF & macValue[2]) << 8) | (0xFF & macValue[3]))); + vector[61] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[0]) << 16) | + ((0xFF & macValue[1]) << 8) | (0xFF & macValue[2]))); + vector[62] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[5]) << 24) | ((0xFF & macValue[3]) << 16) | + ((0xFF & macValue[4]) << 8) | (0xFF & macValue[1]))); + vector[63] = 0xFFFFFFFFL & ((long) (((0xFF & macValue[0]) << 24) | ((0xFF & macValue[2]) << 16) | + ((0xFF & macValue[3]) << 8) | (0xFF & macValue[0]))); + + return vector; + } + + @Override + public List getKeys() { + JenkinsHash hash = new JenkinsHash(); + if (getMacAddress().length() < 12) { + setErrorCode(R.string.msg_nomac); + return null; + } + long[] key = scrambler(getMacAddress()); + long seed = 0; + + for (int x = 0; x < 64; x++) { + seed = hash.hashword(key, x, seed); + } + + String S1 = Long.toHexString(seed); + while (S1.length() < 8) + S1 = "0" + S1; + + + for (int x = 0; x < 64; x++) { + if (x < 8) + key[x] = (key[x] << 3) & 0xFFFFFFFF; + else if (x < 16) + key[x] >>>= 5; + else if (x < 32) + key[x] >>>= 2; + else + key[x] = (key[x] << 7) & 0xFFFFFFFF; + } + + seed = 0; + for (int x = 0; x < 64; x++) { + seed = hash.hashword(key, x, seed); + } + String S2 = Long.toHexString(seed); + while (S2.length() < 8) + S2 = "0" + S2; + addPassword(S1.substring(S1.length() - 5) + S2.substring(0, 5)); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ThomsonKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ThomsonKeygen.java index de9c9d7..25baf7c 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ThomsonKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ThomsonKeygen.java @@ -18,6 +18,14 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.ui.Preferences; +import org.exobel.routerkeygen.utils.InputStreamUtils; +import org.exobel.routerkeygen.utils.StringUtils; + import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; @@ -33,64 +41,52 @@ import java.util.Locale; import java.util.zip.ZipInputStream; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.ui.Preferences; -import org.exobel.routerkeygen.utils.StringUtils; - -import android.os.Parcel; -import android.os.Parcelable; - public class ThomsonKeygen extends Keygen { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ThomsonKeygen createFromParcel(Parcel in) { + return new ThomsonKeygen(in); + } + + public ThomsonKeygen[] newArray(int size) { + return new ThomsonKeygen[size]; + } + }; + final private static byte[] charectbytes0 = {'3', '3', '3', '3', '3', '3', + '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', + '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', + '5', '5', '5', '5',}; + final private static byte[] charectbytes1 = {'0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', + '7', '8', '9', 'A',}; final private byte[] cp = new byte[12]; - private byte[] entry; final private byte[] table = new byte[1282]; + final private byte[] routerESSID = new byte[3]; + final private String ssidIdentifier; + private byte[] entry; private int a, b, c; private int year; private int week; private int sequenceNumber; - final private byte[] routerESSID = new byte[3]; private boolean internetAlgorithm; - private boolean errorDict; private int len = 0; private String dictionaryPath; - private MessageDigest md; - final private String ssidIdentifier; private InputStream webdic; - private static boolean readFromInput(byte[] buf, int length, - InputStream input) throws IOException { - int check = 0, ret = 0; - while (check != length) { - ret = input.read(buf, check, length - check); - if (ret == -1) { - return false; - } else - check += ret; - } - return true; - } - - private static boolean readFromInput(byte[] buf, int length, - RandomAccessFile input) throws IOException { - int check = 0, ret = 0; - while (check != length) { - ret = input.read(buf, check, length - check); - if (ret == -1) { - return false; - } else - check += ret; - } - return true; - } - public ThomsonKeygen(String ssid, String mac) { super(ssid, mac); this.errorDict = false; this.ssidIdentifier = ssid.substring(ssid.length() - 6); } + private ThomsonKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + errorDict = in.readInt() == 1; + } + @Override public List getKeys() { try { @@ -125,22 +121,18 @@ public List getKeys() { private boolean internetCalc() { try { - DataInputStream onlineFile = null; - int lenght = 0; - URL url; ZipInputStream fis = new ZipInputStream(webdic); fis.getNextEntry(); - if (!readFromInput(table, 1024, fis)) { + if (!InputStreamUtils.readFromInput(table, 1024, fis)) { setErrorCode(R.string.msg_err_webdic_table); errorDict = true; fis.close(); return false; } int totalOffset = 0; - int offset = 0; int lastLength = 0; int i = (0xFF & routerESSID[0]) * 4; - offset = ((0xFF & table[i]) << 24) | ((0xFF & table[i + 1]) << 16) + int offset = ((0xFF & table[i]) << 24) | ((0xFF & table[i + 1]) << 16) | ((0xFF & table[i + 2]) << 8) | (0xFF & table[i + 3]); if (i != 1020) // routerESSID[0] != 0xFF ( 255*4 == 1020 ) lastLength = ((0xFF & table[i + 4]) << 24) @@ -148,11 +140,11 @@ private boolean internetCalc() { | ((0xFF & table[i + 6]) << 8) | (0xFF & table[i + 7]); totalOffset += offset; long checkLong = 0, retLong; - while (checkLong != (i / 4) * 768)/* + /* * ZipInputStream doens't seems to * block. */ - { + while (checkLong != (i / 4) * 768) { retLong = fis.skip((i / 4) * 768 - checkLong); if (retLong == -1) { setErrorCode(R.string.msg_err_webdic_table); @@ -163,7 +155,7 @@ private boolean internetCalc() { checkLong += retLong; } - if (!readFromInput(table, 768, fis)) { + if (!InputStreamUtils.readFromInput(table, 768, fis)) { setErrorCode(R.string.msg_err_webdic_table); errorDict = true; fis.close(); @@ -176,10 +168,10 @@ private boolean internetCalc() { * There's no check here because humans are lazy people and because * it doesn't matter */ - lenght = ((0xFF & table[i + 3]) << 16) + int length = ((0xFF & table[i + 3]) << 16) | ((0xFF & table[i + 4]) << 8) | (0xFF & table[i + 5]); totalOffset += offset; - lenght -= offset; + length -= offset; if ((lastLength != 0) && ((0xFF & routerESSID[1]) == 0xFF)) { /* * Only for SSID starting with XXFF. We use the next item on the @@ -187,7 +179,7 @@ private boolean internetCalc() { * for. */ lastLength -= totalOffset; - lenght = lastLength; + length = lastLength; } if (((0xFF & routerESSID[0]) == 0xFF) && ((0xFF & routerESSID[1]) == 0xFF)) { @@ -195,16 +187,16 @@ private boolean internetCalc() { * Only for SSID starting with FFFF as we don't have a marker of * the end. */ - lenght = 2000; + length = 2000; } - url = new URL(Preferences.PUB_DOWNLOAD); + final URL url = new URL(Preferences.PUB_DOWNLOAD); URLConnection con = url.openConnection(); con.setRequestProperty("Range", "bytes=" + totalOffset + "-" - + (totalOffset + lenght)); - onlineFile = new DataInputStream(con.getInputStream()); - len = lenght; + + (totalOffset + length)); + final DataInputStream onlineFile = new DataInputStream(con.getInputStream()); + len = length; this.entry = new byte[len]; - if (!readFromInput(entry, len, onlineFile)) { + if (!InputStreamUtils.readFromInput(entry, len, onlineFile)) { setErrorCode(R.string.msg_err_webdic_table); onlineFile.close(); errorDict = true; @@ -231,9 +223,9 @@ private boolean localCalc() { errorDict = true; return false; } - int version = 0; + int version; try { - if (!readFromInput(table, 1282, fis)) { + if (!InputStreamUtils.readFromInput(table, 1282, fis)) { setErrorCode(R.string.msg_errordict); errorDict = true; fis.close(); @@ -256,7 +248,7 @@ private boolean localCalc() { } totalOffset += offset; fis.seek(totalOffset); - if (!readFromInput(table, 1024, fis)) { + if (!InputStreamUtils.readFromInput(table, 1024, fis)) { setErrorCode(R.string.msg_errordict); errorDict = true; fis.close(); @@ -293,10 +285,9 @@ private boolean localCalc() { this.entry = new byte[length]; } - int bytesRead = 0; len = 0; while (len < length) { - bytesRead = fis.read(entry, len, length - len); + int bytesRead = fis.read(entry, len, length - len); if (bytesRead == -1) break; len += bytesRead; @@ -345,8 +336,8 @@ private boolean thirdDic() { } if (isStopRequested()) return false; - for (int i = 0; i < results.length; ++i) - addPassword(results[i]); + for (String result : results) + addPassword(result); return true; } @@ -358,8 +349,8 @@ private void forthDic() { if (isStopRequested()) return; sequenceNumber = i - + (((0xFF & entry[offset + 0]) << 16) - | ((0xFF & entry[offset + 1]) << 8) | (0xFF & entry[offset + 2])) + + (((0xFF & entry[offset]) << 16) + | ((0xFF & entry[offset + 1]) << 8) | (0xFF & entry[offset + 2])) * 2; c = sequenceNumber % 36; b = sequenceNumber / 36 % 36; @@ -402,7 +393,7 @@ private void secondDic() { for (int offset = 0; offset < len; offset += 3) { if (isStopRequested()) return; - sequenceNumber = ((0xFF & entry[offset + 0]) << 16) + sequenceNumber = ((0xFF & entry[offset]) << 16) | ((0xFF & entry[offset + 1]) << 8) | (0xFF & entry[offset + 2]); c = sequenceNumber % 36; @@ -499,38 +490,12 @@ public void setInternetAlgorithm(boolean thomson3g) { this.internetAlgorithm = thomson3g; } - final private static byte[] charectbytes0 = { '3', '3', '3', '3', '3', '3', - '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', - '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', - '5', '5', '5', '5', }; - - final private static byte[] charectbytes1 = { '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', - '7', '8', '9', 'A', }; - - private ThomsonKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - errorDict = in.readInt() == 1; - } - public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(ssidIdentifier); dest.writeInt(errorDict ? 1 : 0); } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ThomsonKeygen createFromParcel(Parcel in) { - return new ThomsonKeygen(in); - } - - public ThomsonKeygen[] newArray(int size) { - return new ThomsonKeygen[size]; - } - }; - @Override public int getSupportState() { if (getMacAddress().length() < 12) @@ -549,7 +514,7 @@ private static class ThomsonNative { } private native String[] thirdDicNative(byte[] essid, byte[] entry, - int size); + int size); } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TplinkKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TplinkKeygen.java index 24887ed..c392346 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TplinkKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/TplinkKeygen.java @@ -18,34 +18,16 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; public class TplinkKeygen extends Keygen { - public TplinkKeygen(String ssid, String mac) { - super(ssid, mac); - } - - @Override - public List getKeys() { - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - addPassword(getMacAddress().substring(4).toUpperCase(Locale.getDefault())); - return getResults(); - } - - private TplinkKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public TplinkKeygen createFromParcel(Parcel in) { return new TplinkKeygen(in); @@ -55,6 +37,24 @@ public TplinkKeygen[] newArray(int size) { return new TplinkKeygen[size]; } }; - + + public TplinkKeygen(String ssid, String mac) { + super(ssid, mac); + } + + private TplinkKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + addPassword(getMacAddress().substring(4).toUpperCase(Locale.getDefault())); + return getResults(); + } + } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/VerizonKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/VerizonKeygen.java index fb23e2b..0ddc0c6 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/VerizonKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/VerizonKeygen.java @@ -18,64 +18,17 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; - -import org.exobel.routerkeygen.R; - import android.os.Parcel; import android.os.Parcelable; -public class VerizonKeygen extends Keygen { - +import org.exobel.routerkeygen.R; - public VerizonKeygen(String ssid, String mac ) { - super(ssid, mac); - } +import java.util.List; +import java.util.Locale; - @Override - public List getKeys() { - if ( getSsidName().length() != 5 ) - { - setErrorCode(R.string.msg_shortessid5); - return null; - } - char [] inverse = new char[5]; - inverse[0] = getSsidName().charAt(4); - inverse[1] = getSsidName().charAt(3); - inverse[2] = getSsidName().charAt(2); - inverse[3] = getSsidName().charAt(1); - inverse[4] = getSsidName().charAt(0); - - int result = 0; - try{ - result = Integer.valueOf(String.copyValueOf(inverse), 36); - }catch(NumberFormatException e){ - setErrorCode(R.string.msg_err_verizon_ssid); - return null; - } - - String ssidKey = Integer.toHexString(result).toUpperCase(Locale.getDefault()); - while ( ssidKey.length() < 6 ) - ssidKey = "0" + ssidKey; - if ( !getMacAddress().equals("")) - { - addPassword(getMacAddress().substring(3,5) + getMacAddress().substring(6,8) + - ssidKey); - } - else - { - addPassword("1801" + ssidKey); - addPassword("1F90" + ssidKey); - } - return getResults(); - } +public class VerizonKeygen extends Keygen { - private VerizonKeygen(Parcel in) { - super(in); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public VerizonKeygen createFromParcel(Parcel in) { return new VerizonKeygen(in); @@ -85,4 +38,47 @@ public VerizonKeygen[] newArray(int size) { return new VerizonKeygen[size]; } }; + + public VerizonKeygen(String ssid, String mac) { + super(ssid, mac); + } + + + private VerizonKeygen(Parcel in) { + super(in); + } + + @Override + public List getKeys() { + if (getSsidName().length() != 5) { + setErrorCode(R.string.msg_shortessid5); + return null; + } + char[] inverse = new char[5]; + inverse[0] = getSsidName().charAt(4); + inverse[1] = getSsidName().charAt(3); + inverse[2] = getSsidName().charAt(2); + inverse[3] = getSsidName().charAt(1); + inverse[4] = getSsidName().charAt(0); + + int result = 0; + try { + result = Integer.valueOf(String.copyValueOf(inverse), 36); + } catch (NumberFormatException e) { + setErrorCode(R.string.msg_err_verizon_ssid); + return null; + } + + String ssidKey = Integer.toHexString(result).toUpperCase(Locale.getDefault()); + while (ssidKey.length() < 6) + ssidKey = "0" + ssidKey; + if (!getMacAddress().equals("")) { + addPassword(getMacAddress().substring(3, 5) + getMacAddress().substring(6, 8) + + ssidKey); + } else { + addPassword("1801" + ssidKey); + addPassword("1F90" + ssidKey); + } + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WiFiNetwork.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WiFiNetwork.java index 9620716..1d2d55e 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WiFiNetwork.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WiFiNetwork.java @@ -1,35 +1,51 @@ package org.exobel.routerkeygen.algorithms; -import java.util.ArrayList; -import java.util.Locale; -import java.util.zip.ZipInputStream; - -import org.exobel.routerkeygen.WirelessMatcher; - import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; +import org.exobel.routerkeygen.WirelessMatcher; + +import java.util.ArrayList; +import java.util.Locale; +import java.util.zip.ZipInputStream; + public class WiFiNetwork implements Comparable, Parcelable { - private ScanResult scanResult; + // Constants used for different security types + public static final String PSK = "PSK"; + public static final String WEP = "WEP"; + public static final String EAP = "EAP"; + public static final String OPEN = "Open"; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + + public WiFiNetwork[] newArray(int size) { + return new WiFiNetwork[size]; + } + + @Override + public WiFiNetwork createFromParcel(Parcel source) { + return new WiFiNetwork(source); + } + }; final private String ssidName; final private String macAddress; final private int level; final private String encryption; + private ScanResult scanResult; private ArrayList keygens; public WiFiNetwork(ScanResult scanResult, ZipInputStream magicInfo) { - this(scanResult.SSID,scanResult.BSSID, - WifiManager.calculateSignalLevel(scanResult.level, 4), + this(scanResult.SSID, scanResult.BSSID, + WifiManager.calculateSignalLevel(scanResult.level, 4), scanResult.capabilities, magicInfo); this.scanResult = scanResult; } public WiFiNetwork(final String ssid, final String mac, int level, - String enc, ZipInputStream magicInfo) { + String enc, ZipInputStream magicInfo) { this.ssidName = ssid; this.macAddress = mac.toUpperCase(Locale.getDefault()); this.level = level; @@ -39,6 +55,40 @@ public WiFiNetwork(final String ssid, final String mac, int level, magicInfo); } + protected WiFiNetwork(Parcel in) { + ssidName = in.readString(); + if (in.readInt() == 1) + macAddress = in.readString(); + else + macAddress = ""; + if (in.readInt() == 1) + encryption = in.readString(); + else + encryption = OPEN; + level = in.readInt(); + keygens = new ArrayList<>(); + in.readList(keygens, Keygen.class.getClassLoader()); + if (in.readInt() == 1) + scanResult = in.readParcelable(ScanResult.class.getClassLoader()); + else + scanResult = null; + } + + /** + * @return The security of a given {@link ScanResult}. + */ + public static String getScanResultSecurity(WiFiNetwork scanResult) { + final String cap = scanResult.encryption; + final String[] securityModes = {WEP, PSK, EAP}; + for (int i = securityModes.length - 1; i >= 0; i--) { + if (cap.contains(securityModes[i])) { + return securityModes[i]; + } + } + + return OPEN; + } + public String getSsidName() { return ssidName; } @@ -97,71 +147,20 @@ public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(scanResult, flags); } - protected WiFiNetwork(Parcel in) { - ssidName = in.readString(); - if (in.readInt() == 1) - macAddress = in.readString(); - else - macAddress = ""; - if (in.readInt() == 1) - encryption = in.readString(); - else - encryption = OPEN; - level = in.readInt(); - keygens = new ArrayList<>(); - in.readList(keygens, Keygen.class.getClassLoader()); - if (in.readInt() == 1) - scanResult = in.readParcelable(ScanResult.class.getClassLoader()); - else - scanResult = null; - } - public boolean isLocked() { return !OPEN.equals(getScanResultSecurity(this)); } - /** - * @return The security of a given {@link ScanResult}. - */ - public static String getScanResultSecurity(WiFiNetwork scanResult) { - final String cap = scanResult.encryption; - final String[] securityModes = { WEP, PSK, EAP }; - for (int i = securityModes.length - 1; i >= 0; i--) { - if (cap.contains(securityModes[i])) { - return securityModes[i]; - } - } - - return OPEN; - } - public ScanResult getScanResult() { return scanResult; } - public void setKeygens(ZipInputStream magicInfo) { - this.keygens = WirelessMatcher.getKeygen(ssidName, macAddress, - magicInfo); - } public ArrayList getKeygens() { return keygens; } - // Constants used for different security types - public static final String PSK = "PSK"; - public static final String WEP = "WEP"; - public static final String EAP = "EAP"; - public static final String OPEN = "Open"; - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - public WiFiNetwork[] newArray(int size) { - return new WiFiNetwork[size]; - } - - @Override - public WiFiNetwork createFromParcel(Parcel source) { - return new WiFiNetwork(source); - } - }; + public void setKeygens(ZipInputStream magicInfo) { + this.keygens = WirelessMatcher.getKeygen(ssidName, macAddress, + magicInfo); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WifimediaRKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WifimediaRKeygen.java index c503b11..3abf25c 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WifimediaRKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/WifimediaRKeygen.java @@ -18,54 +18,53 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; +import java.util.Locale; /** * Simple algorithm for "wifimedia_R-XXXX" seen here: * "http://foro.seguridadwireless.net/aplicaciones/(r-wlanxdecrypter-0-9)-generador-de-diccionarios-para-claves-por-defecto-de-r/msg264486/#msg264486" - * + * * @author Rui Araujo - * */ public class WifimediaRKeygen extends Keygen { - public WifimediaRKeygen(String ssid, String mac) { - super(ssid, mac); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public WifimediaRKeygen createFromParcel(Parcel in) { + return new WifimediaRKeygen(in); + } - @Override - public List getKeys() { - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - final String possibleKey = mac.substring(0, 11).toLowerCase( - Locale.getDefault()) - + "0"; - addPassword(possibleKey); - addPassword(possibleKey.toUpperCase(Locale.getDefault())); - return getResults(); - } + public WifimediaRKeygen[] newArray(int size) { + return new WifimediaRKeygen[size]; + } + }; - private WifimediaRKeygen(Parcel in) { - super(in); - } + public WifimediaRKeygen(String ssid, String mac) { + super(ssid, mac); + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public WifimediaRKeygen createFromParcel(Parcel in) { - return new WifimediaRKeygen(in); - } + private WifimediaRKeygen(Parcel in) { + super(in); + } - public WifimediaRKeygen[] newArray(int size) { - return new WifimediaRKeygen[size]; - } - }; + @Override + public List getKeys() { + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + final String possibleKey = mac.substring(0, 11).toLowerCase( + Locale.getDefault()) + + "0"; + addPassword(possibleKey); + addPassword(possibleKey.toUpperCase(Locale.getDefault())); + return getResults(); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan2Keygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan2Keygen.java index 2b866fb..7f9f725 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan2Keygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan2Keygen.java @@ -18,92 +18,23 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; +import android.os.Parcel; +import android.os.Parcelable; import org.exobel.routerkeygen.R; -import android.os.Parcel; -import android.os.Parcelable; +import java.util.List; /** * This only calculates the keys for some WLAN_xx - *
- * + *
+ *

* Many WLAN_XX don't use this algorithm. * Code by Kampanita */ public class Wlan2Keygen extends Keygen { - final private String ssidIdentifier; - public Wlan2Keygen(String ssid, String mac ) { - super(ssid, mac); - ssidIdentifier = ssid.substring(ssid.length()-2); - } - - @Override - public List getKeys() { - char[] key = new char[26]; - if (getMacAddress().length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - key[0] = getMacAddress().charAt(10); - key[1] = getMacAddress().charAt(11); - key[2] = getMacAddress().charAt(0); - key[3] = getMacAddress().charAt(1); - key[4] = getMacAddress().charAt(8); - key[5] = getMacAddress().charAt(9); - key[6] = getMacAddress().charAt(2); - key[7] = getMacAddress().charAt(3); - key[8] = getMacAddress().charAt(4); - key[9] = getMacAddress().charAt(5); - key[10] = getMacAddress().charAt(6); - key[11] = getMacAddress().charAt(7); - key[12] = getMacAddress().charAt(10); - key[13] = getMacAddress().charAt(11); - key[14] = getMacAddress().charAt(8); - key[15] = getMacAddress().charAt(9); - key[16] = getMacAddress().charAt(2); - key[17] = getMacAddress().charAt(3); - key[18] = getMacAddress().charAt(4); - key[19] = getMacAddress().charAt(5); - key[20] = getMacAddress().charAt(6); - key[21] = getMacAddress().charAt(7); - key[22] = getMacAddress().charAt(0); - key[23] = getMacAddress().charAt(1); - key[24] = getMacAddress().charAt(4); - key[25] = getMacAddress().charAt(5); - - int max = 9; - String begin = ssidIdentifier.substring(0,1); - int primer_n = Integer.parseInt(begin, 16); - if (primer_n > max) { - String cadena = String.valueOf(key, 0, 2); - int value = Integer.parseInt(cadena,16); - value=value-1; - String cadena2 = Integer.toHexString(value); - if ( cadena2.length() < 2 ) - cadena2 = "0" + cadena2; - key[0]=cadena2.charAt(0); - key[1]=cadena2.charAt(1); - } - - addPassword(String.valueOf(key, 0, 26)); - return getResults(); - } - - - private Wlan2Keygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } - - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Wlan2Keygen createFromParcel(Parcel in) { return new Wlan2Keygen(in); @@ -113,5 +44,74 @@ public Wlan2Keygen[] newArray(int size) { return new Wlan2Keygen[size]; } }; + final private String ssidIdentifier; + + public Wlan2Keygen(String ssid, String mac) { + super(ssid, mac); + ssidIdentifier = ssid.substring(ssid.length() - 2); + } + + + private Wlan2Keygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } + + @Override + public List getKeys() { + char[] key = new char[26]; + if (getMacAddress().length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + key[0] = getMacAddress().charAt(10); + key[1] = getMacAddress().charAt(11); + key[2] = getMacAddress().charAt(0); + key[3] = getMacAddress().charAt(1); + key[4] = getMacAddress().charAt(8); + key[5] = getMacAddress().charAt(9); + key[6] = getMacAddress().charAt(2); + key[7] = getMacAddress().charAt(3); + key[8] = getMacAddress().charAt(4); + key[9] = getMacAddress().charAt(5); + key[10] = getMacAddress().charAt(6); + key[11] = getMacAddress().charAt(7); + key[12] = getMacAddress().charAt(10); + key[13] = getMacAddress().charAt(11); + key[14] = getMacAddress().charAt(8); + key[15] = getMacAddress().charAt(9); + key[16] = getMacAddress().charAt(2); + key[17] = getMacAddress().charAt(3); + key[18] = getMacAddress().charAt(4); + key[19] = getMacAddress().charAt(5); + key[20] = getMacAddress().charAt(6); + key[21] = getMacAddress().charAt(7); + key[22] = getMacAddress().charAt(0); + key[23] = getMacAddress().charAt(1); + key[24] = getMacAddress().charAt(4); + key[25] = getMacAddress().charAt(5); + + int max = 9; + String begin = ssidIdentifier.substring(0, 1); + int primer_n = Integer.parseInt(begin, 16); + if (primer_n > max) { + String cadena = String.valueOf(key, 0, 2); + int value = Integer.parseInt(cadena, 16); + value = value - 1; + String cadena2 = Integer.toHexString(value); + if (cadena2.length() < 2) + cadena2 = "0" + cadena2; + key[0] = cadena2.charAt(0); + key[1] = cadena2.charAt(1); + } + + addPassword(String.valueOf(key, 0, 26)); + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan6Keygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan6Keygen.java index 029254f..cb0dd67 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan6Keygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/Wlan6Keygen.java @@ -18,96 +18,16 @@ */ package org.exobel.routerkeygen.algorithms; -import java.util.List; -import java.util.Locale; - -import org.exobel.routerkeygen.R; - import android.os.Parcel; import android.os.Parcelable; -public class Wlan6Keygen extends Keygen { - - final private String ssidIdentifier; - public Wlan6Keygen(String ssid, String mac ) { - super(ssid, mac); - ssidIdentifier = ssid.substring(ssid.length()-6); - } - - @Override - public List getKeys() { - String macStr = getMacAddress(); - if ( macStr.length() != 12 ) - { - setErrorCode(R.string.msg_errpirelli); - return null; - } - char [] ssidSubPart = {'1', '2','3', '4', '5','6' };/*These values are not revelant.*/ - char [] bssidLastByte = { '6', '6' }; - ssidSubPart[0] = ssidIdentifier.charAt(0); - ssidSubPart[1] = ssidIdentifier.charAt(1); - ssidSubPart[2] = ssidIdentifier.charAt(2); - ssidSubPart[3] = ssidIdentifier.charAt(3); - ssidSubPart[4] = ssidIdentifier.charAt(4); - ssidSubPart[5] = ssidIdentifier.charAt(5); - bssidLastByte[0] = macStr.charAt(10); - bssidLastByte[1] = macStr.charAt(11); - for ( int k = 0; k < 6 ; ++k ) - if( ssidSubPart[k] >= 'A') - ssidSubPart[k] = (char)(ssidSubPart[k] - 55); +import org.exobel.routerkeygen.R; - if(bssidLastByte[0] >= 'A' ) - bssidLastByte[0] = (char)(bssidLastByte[0] - 55); - if(bssidLastByte[1] >= 'A' ) - bssidLastByte[1] = (char)(bssidLastByte[1] - 55); - - for ( int i = 0; i < 10 ; ++i ) - { - /*Do not change the order of this instructions*/ - int aux = i + ( ssidSubPart[3] & 0xf ) + ( bssidLastByte[0] & 0xf ) + ( bssidLastByte[1] & 0xf ); - int aux1 = ( ssidSubPart[1] & 0xf ) + ( ssidSubPart[2] & 0xf ) + ( ssidSubPart[4] & 0xf ) + ( ssidSubPart[5] & 0xf ); - int second = aux ^ ( ssidSubPart[5] & 0xf ); - int sixth = aux ^ ( ssidSubPart[4] & 0xf ); - int tenth = aux ^ ( ssidSubPart[3] & 0xf ); - int third = aux1 ^ ( ssidSubPart[2] & 0xf ); - int seventh = aux1 ^ ( bssidLastByte[0] & 0xf ); - int eleventh = aux1 ^ ( bssidLastByte[1] & 0xf ); - int fourth = ( bssidLastByte[0] & 0xf ) ^ ( ssidSubPart[5] & 0xf ); - int eighth = ( bssidLastByte[1] & 0xf ) ^ ( ssidSubPart[4] & 0xf ); - int twelfth = aux ^ aux1; - int fifth = second ^ eighth; - int ninth = seventh ^ eleventh; - int thirteenth = third ^ tenth; - int first = twelfth ^ sixth; - String key = Integer.toHexString(first & 0xf) + Integer.toHexString(second & 0xf)+ - Integer.toHexString(third & 0xf) + Integer.toHexString(fourth & 0xf) + - Integer.toHexString(fifth & 0xf) + Integer.toHexString(sixth & 0xf) + - Integer.toHexString(seventh & 0xf) + Integer.toHexString(eighth & 0xf) + - Integer.toHexString(ninth & 0xf) + Integer.toHexString(tenth & 0xf) + - Integer.toHexString(eleventh & 0xf) + Integer.toHexString(twelfth & 0xf) + - Integer.toHexString(thirteenth & 0xf); - - addPassword(key.toUpperCase(Locale.getDefault())); - } - if ( ( ( ssidSubPart[0] != macStr.charAt(7) ) || ( ssidSubPart[1] != macStr.charAt(8) ) ||( ssidSubPart[2] != macStr.charAt(9) ) ) - && !getSsidName().startsWith("WiFi")) - { - setErrorCode(R.string.msg_err_essid_no_match); - } - return getResults(); - } - +import java.util.List; +import java.util.Locale; - private Wlan6Keygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } +public class Wlan6Keygen extends Keygen { - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Wlan6Keygen createFromParcel(Parcel in) { return new Wlan6Keygen(in); @@ -117,5 +37,82 @@ public Wlan6Keygen[] newArray(int size) { return new Wlan6Keygen[size]; } }; + final private String ssidIdentifier; + + public Wlan6Keygen(String ssid, String mac) { + super(ssid, mac); + ssidIdentifier = ssid.substring(ssid.length() - 6); + } + + + private Wlan6Keygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } + + @Override + public List getKeys() { + String macStr = getMacAddress(); + if (macStr.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + char[] ssidSubPart = {'1', '2', '3', '4', '5', '6'};/*These values are not revelant.*/ + char[] bssidLastByte = {'6', '6'}; + ssidSubPart[0] = ssidIdentifier.charAt(0); + ssidSubPart[1] = ssidIdentifier.charAt(1); + ssidSubPart[2] = ssidIdentifier.charAt(2); + ssidSubPart[3] = ssidIdentifier.charAt(3); + ssidSubPart[4] = ssidIdentifier.charAt(4); + ssidSubPart[5] = ssidIdentifier.charAt(5); + bssidLastByte[0] = macStr.charAt(10); + bssidLastByte[1] = macStr.charAt(11); + for (int k = 0; k < 6; ++k) + if (ssidSubPart[k] >= 'A') + ssidSubPart[k] = (char) (ssidSubPart[k] - 55); + + if (bssidLastByte[0] >= 'A') + bssidLastByte[0] = (char) (bssidLastByte[0] - 55); + if (bssidLastByte[1] >= 'A') + bssidLastByte[1] = (char) (bssidLastByte[1] - 55); + + for (int i = 0; i < 10; ++i) { + /*Do not change the order of this instructions*/ + int aux = i + (ssidSubPart[3] & 0xf) + (bssidLastByte[0] & 0xf) + (bssidLastByte[1] & 0xf); + int aux1 = (ssidSubPart[1] & 0xf) + (ssidSubPart[2] & 0xf) + (ssidSubPart[4] & 0xf) + (ssidSubPart[5] & 0xf); + int second = aux ^ (ssidSubPart[5] & 0xf); + int sixth = aux ^ (ssidSubPart[4] & 0xf); + int tenth = aux ^ (ssidSubPart[3] & 0xf); + int third = aux1 ^ (ssidSubPart[2] & 0xf); + int seventh = aux1 ^ (bssidLastByte[0] & 0xf); + int eleventh = aux1 ^ (bssidLastByte[1] & 0xf); + int fourth = (bssidLastByte[0] & 0xf) ^ (ssidSubPart[5] & 0xf); + int eighth = (bssidLastByte[1] & 0xf) ^ (ssidSubPart[4] & 0xf); + int twelfth = aux ^ aux1; + int fifth = second ^ eighth; + int ninth = seventh ^ eleventh; + int thirteenth = third ^ tenth; + int first = twelfth ^ sixth; + String key = Integer.toHexString(first & 0xf) + Integer.toHexString(second & 0xf) + + Integer.toHexString(third & 0xf) + Integer.toHexString(fourth & 0xf) + + Integer.toHexString(fifth & 0xf) + Integer.toHexString(sixth & 0xf) + + Integer.toHexString(seventh & 0xf) + Integer.toHexString(eighth & 0xf) + + Integer.toHexString(ninth & 0xf) + Integer.toHexString(tenth & 0xf) + + Integer.toHexString(eleventh & 0xf) + Integer.toHexString(twelfth & 0xf) + + Integer.toHexString(thirteenth & 0xf); + + addPassword(key.toUpperCase(Locale.getDefault())); + } + if (((ssidSubPart[0] != macStr.charAt(7)) || (ssidSubPart[1] != macStr.charAt(8)) || (ssidSubPart[2] != macStr.charAt(9))) + && !getSsidName().startsWith("WiFi")) { + setErrorCode(R.string.msg_err_essid_no_match); + } + return getResults(); + } + + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ZyxelKeygen.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ZyxelKeygen.java index 8da95cc..b379a6f 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ZyxelKeygen.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/algorithms/ZyxelKeygen.java @@ -18,74 +18,73 @@ */ package org.exobel.routerkeygen.algorithms; +import android.os.Parcel; +import android.os.Parcelable; + +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.utils.StringUtils; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Locale; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.utils.StringUtils; - -import android.os.Parcel; -import android.os.Parcelable; - public class ZyxelKeygen extends Keygen { - final private String ssidIdentifier; - private MessageDigest md; - - public ZyxelKeygen(String ssid, String mac) { - super(ssid, mac); - ssidIdentifier = ssid.substring(ssid.length() - 4); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ZyxelKeygen createFromParcel(Parcel in) { + return new ZyxelKeygen(in); + } - @Override - public List getKeys() { - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e1) { - setErrorCode(R.string.msg_nomd5); - return null; - } - final String mac = getMacAddress(); - if (mac.length() != 12) { - setErrorCode(R.string.msg_errpirelli); - return null; - } - try { + public ZyxelKeygen[] newArray(int size) { + return new ZyxelKeygen[size]; + } + }; + final private String ssidIdentifier; + private MessageDigest md; - final String macMod = mac.substring(0, 8) + ssidIdentifier; - md.reset(); - md.update(macMod.toLowerCase(Locale.getDefault()).getBytes("ASCII")); + public ZyxelKeygen(String ssid, String mac) { + super(ssid, mac); + ssidIdentifier = ssid.substring(ssid.length() - 4); + } - byte[] hash = md.digest(); - addPassword(StringUtils.getHexString(hash).substring(0, 20) - .toUpperCase(Locale.getDefault())); - return getResults(); - } catch (UnsupportedEncodingException e) { - } - return null; - } + private ZyxelKeygen(Parcel in) { + super(in); + ssidIdentifier = in.readString(); + } - private ZyxelKeygen(Parcel in) { - super(in); - ssidIdentifier = in.readString(); - } + @Override + public List getKeys() { + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e1) { + setErrorCode(R.string.msg_nomd5); + return null; + } + final String mac = getMacAddress(); + if (mac.length() != 12) { + setErrorCode(R.string.msg_errpirelli); + return null; + } + try { - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(ssidIdentifier); - } + final String macMod = mac.substring(0, 8) + ssidIdentifier; + md.reset(); + md.update(macMod.toLowerCase(Locale.getDefault()).getBytes("ASCII")); - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public ZyxelKeygen createFromParcel(Parcel in) { - return new ZyxelKeygen(in); - } + byte[] hash = md.digest(); + addPassword(StringUtils.getHexString(hash).substring(0, 20) + .toUpperCase(Locale.getDefault())); + return getResults(); + } catch (UnsupportedEncodingException e) { + } + return null; + } - public ZyxelKeygen[] newArray(int size) { - return new ZyxelKeygen[size]; - } - }; + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(ssidIdentifier); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceConfigParser.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceConfigParser.java index d4791b8..410734b 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceConfigParser.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceConfigParser.java @@ -27,31 +27,31 @@ public class AliceConfigParser { - public static Map> parse(InputStream in) { - Map> supportedAlices = new HashMap>(); - final BufferedReader bufferedInput = new BufferedReader( - new InputStreamReader(in)); - try { - String line; - while ((line = bufferedInput.readLine()) != null) { - final String[] infos = line.split(","); - final String name = infos[0]; - ArrayList supported = supportedAlices.get(name); - if (supported == null) { - supported = new ArrayList(5); - supportedAlices.put(name, supported); - } - final String serial = infos[1]; - int[] magic = new int[2]; - magic[0] = Integer.parseInt(infos[2]); // k - magic[1] = Integer.parseInt(infos[3]); // q - final String mac = infos[4]; - supported.add(new AliceMagicInfo(name, magic, serial, mac)); - } - } catch (Exception e) { - e.printStackTrace(); - } - return supportedAlices; - } + public static Map> parse(InputStream in) { + Map> supportedAlices = new HashMap>(); + final BufferedReader bufferedInput = new BufferedReader( + new InputStreamReader(in)); + try { + String line; + while ((line = bufferedInput.readLine()) != null) { + final String[] infos = line.split(","); + final String name = infos[0]; + ArrayList supported = supportedAlices.get(name); + if (supported == null) { + supported = new ArrayList(5); + supportedAlices.put(name, supported); + } + final String serial = infos[1]; + int[] magic = new int[2]; + magic[0] = Integer.parseInt(infos[2]); // k + magic[1] = Integer.parseInt(infos[3]); // q + final String mac = infos[4]; + supported.add(new AliceMagicInfo(name, magic, serial, mac)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return supportedAlices; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceMagicInfo.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceMagicInfo.java index 3113c00..98ecbb3 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceMagicInfo.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/AliceMagicInfo.java @@ -21,46 +21,7 @@ import android.os.Parcel; import android.os.Parcelable; -public class AliceMagicInfo implements Parcelable{ - final private String alice; - final private int [] magic; - final private String serial; - final private String mac; - public AliceMagicInfo(String alice, int[] magic, String serial, String mac) { - this.alice = alice; - this.magic = magic; - this.serial = serial; - this.mac = mac; - } - public String getAlice() { - return alice; - } - public int[] getMagic() { - return magic; - } - public String getSerial() { - return serial; - } - public String getMac() { - return mac; - } - public int describeContents() { - return 0; - } - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(alice); - dest.writeString(serial); - dest.writeString(mac); - dest.writeIntArray(magic); - } - - private AliceMagicInfo(Parcel in){ - this.alice = in.readString(); - this.serial = in.readString(); - this.mac = in.readString(); - this.magic = in.createIntArray(); - } - +public class AliceMagicInfo implements Parcelable { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public AliceMagicInfo createFromParcel(Parcel in) { return new AliceMagicInfo(in); @@ -70,5 +31,50 @@ public AliceMagicInfo[] newArray(int size) { return new AliceMagicInfo[size]; } }; + final private String alice; + final private int[] magic; + final private String serial; + final private String mac; + + public AliceMagicInfo(String alice, int[] magic, String serial, String mac) { + this.alice = alice; + this.magic = magic; + this.serial = serial; + this.mac = mac; + } + + private AliceMagicInfo(Parcel in) { + this.alice = in.readString(); + this.serial = in.readString(); + this.mac = in.readString(); + this.magic = in.createIntArray(); + } + + public String getAlice() { + return alice; + } + + public int[] getMagic() { + return magic; + } + + public String getSerial() { + return serial; + } + + public String getMac() { + return mac; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(alice); + dest.writeString(serial); + dest.writeString(mac); + dest.writeIntArray(magic); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/OTEHuaweiConfigParser.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/OTEHuaweiConfigParser.java index 24a5343..ff12842 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/OTEHuaweiConfigParser.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/OTEHuaweiConfigParser.java @@ -24,21 +24,21 @@ public class OTEHuaweiConfigParser { - public static String[] parse(InputStream in) { - final String[] supportedOTE = new String[61440]; - final BufferedReader bufferedInput = new BufferedReader( - new InputStreamReader(in)); - int j = 0; - try { - String line; - while ((line = bufferedInput.readLine()) != null) - supportedOTE[j++] = line; - } catch (Exception e) { - e.printStackTrace(); - } - if (j != supportedOTE.length) - throw new RuntimeException(); - return supportedOTE; - } + public static String[] parse(InputStream in) { + final String[] supportedOTE = new String[61440]; + final BufferedReader bufferedInput = new BufferedReader( + new InputStreamReader(in)); + int j = 0; + try { + String line; + while ((line = bufferedInput.readLine()) != null) + supportedOTE[j++] = line; + } catch (Exception e) { + e.printStackTrace(); + } + if (j != supportedOTE.length) + throw new RuntimeException(); + return supportedOTE; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuConfigParser.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuConfigParser.java index e1a7ed7..487b232 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuConfigParser.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuConfigParser.java @@ -27,34 +27,34 @@ public class TeleTuConfigParser { - public static Map> parse(InputStream in) { - Map> supportedTeleTu = new HashMap>(); - final BufferedReader bufferedInput = new BufferedReader( - new InputStreamReader(in)); - try { - String line; - while ((line = bufferedInput.readLine()) != null) { - final String[] infos = line.split(" "); - final String name = infos[0]; - ArrayList supported = supportedTeleTu - .get(name); - if (supported == null) { - supported = new ArrayList(5); - supportedTeleTu.put(name, supported); - } - int[] range = new int[2]; - range[0] = Integer.parseInt(infos[1], 16); // from - range[1] = Integer.parseInt(infos[2], 16); // to - final String serial = infos[3]; - final int base = Integer.parseInt(infos[4], 16); - final int divider = Integer.parseInt(infos[5]); - supported - .add(new TeleTuMagicInfo(range, serial, base, divider)); - } - } catch (Exception e) { - e.printStackTrace(); - } - return supportedTeleTu; - } + public static Map> parse(InputStream in) { + Map> supportedTeleTu = new HashMap>(); + final BufferedReader bufferedInput = new BufferedReader( + new InputStreamReader(in)); + try { + String line; + while ((line = bufferedInput.readLine()) != null) { + final String[] infos = line.split(" "); + final String name = infos[0]; + ArrayList supported = supportedTeleTu + .get(name); + if (supported == null) { + supported = new ArrayList(5); + supportedTeleTu.put(name, supported); + } + int[] range = new int[2]; + range[0] = Integer.parseInt(infos[1], 16); // from + range[1] = Integer.parseInt(infos[2], 16); // to + final String serial = infos[3]; + final int base = Integer.parseInt(infos[4], 16); + final int divider = Integer.parseInt(infos[5]); + supported + .add(new TeleTuMagicInfo(range, serial, base, divider)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return supportedTeleTu; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuMagicInfo.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuMagicInfo.java index 0d8ac10..bbaf13d 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuMagicInfo.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/config/TeleTuMagicInfo.java @@ -22,60 +22,59 @@ import android.os.Parcelable; public class TeleTuMagicInfo implements Parcelable { - private final int[] range; - private final int base; - private final String serial; - private final int divider; + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public TeleTuMagicInfo createFromParcel(Parcel in) { + return new TeleTuMagicInfo(in); + } - public TeleTuMagicInfo(int[] range, String serial, int base, int divider) { - this.serial = serial; - this.range = range; - this.base = base; - this.divider = divider; - } + public TeleTuMagicInfo[] newArray(int size) { + return new TeleTuMagicInfo[size]; + } + }; + private final int[] range; + private final int base; + private final String serial; + private final int divider; - public int[] getRange() { - return range; - } + public TeleTuMagicInfo(int[] range, String serial, int base, int divider) { + this.serial = serial; + this.range = range; + this.base = base; + this.divider = divider; + } - public int getBase() { - return base; - } + private TeleTuMagicInfo(Parcel in) { + this.base = in.readInt(); + this.divider = in.readInt(); + this.range = in.createIntArray(); + this.serial = in.readString(); + } - public int getDivider() { - return divider; - } + public int[] getRange() { + return range; + } - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(base); - dest.writeInt(divider); - dest.writeIntArray(range); - dest.writeString(serial); - } + public int getBase() { + return base; + } - private TeleTuMagicInfo(Parcel in) { - this.base = in.readInt(); - this.divider = in.readInt(); - this.range = in.createIntArray(); - this.serial = in.readString(); - } + public int getDivider() { + return divider; + } - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public TeleTuMagicInfo createFromParcel(Parcel in) { - return new TeleTuMagicInfo(in); - } + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(base); + dest.writeInt(divider); + dest.writeIntArray(range); + dest.writeString(serial); + } - public TeleTuMagicInfo[] newArray(int size) { - return new TeleTuMagicInfo[size]; - } - }; + public int describeContents() { + return 0; + } - public int describeContents() { - return 0; - } - - public String getSerial() { - return serial; - } + public String getSerial() { + return serial; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputActivity.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputActivity.java index 98b34bd..153d5a9 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputActivity.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputActivity.java @@ -19,11 +19,6 @@ package org.exobel.routerkeygen.ui; -import org.exobel.routerkeygen.AdsUtils; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.algorithms.Keygen; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NavUtils; @@ -34,74 +29,79 @@ import com.actionbarsherlock.view.MenuItem; import com.google.android.gms.analytics.GoogleAnalytics; +import org.exobel.routerkeygen.AdsUtils; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.algorithms.Keygen; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; + public class ManualInputActivity extends SherlockFragmentActivity implements - NetworksListFragment.OnItemSelectionListener { + NetworksListFragment.OnItemSelectionListener { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_single_fragment); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_single_fragment); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); - AdsUtils.loadAdIfNeeded(this); - if (savedInstanceState == null) { - getSupportFragmentManager() - .beginTransaction() - .add(R.id.keygen_fragment, - ManualInputFragment - .newInstance(getIntent() - .getStringExtra( - ManualInputFragment.MAC_ADDRESS_ARG))) - .commit(); - } - } + AdsUtils.loadAdIfNeeded(this); + if (savedInstanceState == null) { + getSupportFragmentManager() + .beginTransaction() + .add(R.id.keygen_fragment, + ManualInputFragment + .newInstance(getIntent() + .getStringExtra( + ManualInputFragment.MAC_ADDRESS_ARG))) + .commit(); + } + } - @Override - public void onStart() { - super.onStart(); - //Get an Analytics tracker to report app starts and uncaught exceptions etc. - GoogleAnalytics.getInstance(this).reportActivityStart(this); + @Override + public void onStart() { + super.onStart(); + //Get an Analytics tracker to report app starts and uncaught exceptions etc. + GoogleAnalytics.getInstance(this).reportActivityStart(this); - } + } - @Override - public void onStop() { - super.onStop(); - //Stop the analytics tracking + @Override + public void onStop() { + super.onStop(); + //Stop the analytics tracking GoogleAnalytics.getInstance(this).reportActivityStop(this); - } + } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - NavUtils.navigateUpTo(this, new Intent(this, - NetworksListActivity.class)); - return true; - case R.id.pref: - startActivity(new Intent(this, Preferences.class)); - return true; - } - return super.onOptionsItemSelected(item); - } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + NavUtils.navigateUpTo(this, new Intent(this, + NetworksListActivity.class)); + return true; + case R.id.pref: + startActivity(new Intent(this, Preferences.class)); + return true; + } + return super.onOptionsItemSelected(item); + } - public boolean onCreateOptionsMenu(Menu menu) { - getSupportMenuInflater().inflate(R.menu.preferences, menu); - return true; - } + public boolean onCreateOptionsMenu(Menu menu) { + getSupportMenuInflater().inflate(R.menu.preferences, menu); + return true; + } - public void onItemSelected(WiFiNetwork wiFiNetwork) { - if (wiFiNetwork.getSupportState() == Keygen.UNSUPPORTED) { - Toast.makeText(this, R.string.msg_unspported, - Toast.LENGTH_SHORT).show(); - return; - } - Intent detailIntent = new Intent(this, NetworkActivity.class); - detailIntent.putExtra(NetworkFragment.NETWORK_ID, wiFiNetwork); - startActivity(detailIntent); - } + public void onItemSelected(WiFiNetwork wiFiNetwork) { + if (wiFiNetwork.getSupportState() == Keygen.UNSUPPORTED) { + Toast.makeText(this, R.string.msg_unspported, + Toast.LENGTH_SHORT).show(); + return; + } + Intent detailIntent = new Intent(this, NetworkActivity.class); + detailIntent.putExtra(NetworkFragment.NETWORK_ID, wiFiNetwork); + startActivity(detailIntent); + } - public void onItemSelected(String mac) { - } + public void onItemSelected(String mac) { + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputFragment.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputFragment.java index 4fdff21..7d5a6dc 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputFragment.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/ManualInputFragment.java @@ -1,14 +1,5 @@ package org.exobel.routerkeygen.ui; -import java.io.IOException; -import java.util.Locale; -import java.util.zip.ZipInputStream; - -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.algorithms.Keygen; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; -import org.exobel.routerkeygen.ui.NetworksListFragment.OnItemSelectionListener; - import android.annotation.TargetApi; import android.app.Activity; import android.os.AsyncTask; @@ -30,233 +21,240 @@ import com.actionbarsherlock.app.SherlockFragment; -public class ManualInputFragment extends SherlockFragment { - public final static String MAC_ADDRESS_ARG = "mac_address"; - private View loading; - private View mainView; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.algorithms.Keygen; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; +import org.exobel.routerkeygen.ui.NetworksListFragment.OnItemSelectionListener; - public static ManualInputFragment newInstance() { - ManualInputFragment frag = new ManualInputFragment(); - frag.setArguments(Bundle.EMPTY); - return frag; - } +import java.io.IOException; +import java.util.Locale; +import java.util.zip.ZipInputStream; - public static ManualInputFragment newInstance(String mac) { - Bundle args = new Bundle(); - if (mac != null) - args.putString(MAC_ADDRESS_ARG, mac.replace(":", "")); - ManualInputFragment frag = new ManualInputFragment(); - frag.setArguments(args); - return frag; - } +public class ManualInputFragment extends SherlockFragment { + public final static String MAC_ADDRESS_ARG = "mac_address"; + private static OnItemSelectionListener sDummyCallbacks = new OnItemSelectionListener() { + public void onItemSelected(WiFiNetwork id) { + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - final String macAddress; - if (getArguments().containsKey(MAC_ADDRESS_ARG)) - macAddress = getArguments().getString(MAC_ADDRESS_ARG); - else - macAddress = null; - final View root = inflater - .inflate(R.layout.fragment_manual_input, null); - mainView = root.findViewById(R.id.manual_root); - loading = root.findViewById(R.id.loading_spinner); - final String[] routers = getResources().getStringArray( - R.array.supported_routers); - ArrayAdapter adapter = new ArrayAdapter(getActivity(), - android.R.layout.simple_dropdown_item_1line, routers); - final AutoCompleteTextView edit = (AutoCompleteTextView) root - .findViewById(R.id.manual_autotext); - edit.setAdapter(adapter); - edit.setThreshold(1); - final InputFilter filterSSID = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, - Spanned dest, int dstart, int dend) { - for (int i = start; i < end; i++) { - if (!Character.isLetterOrDigit(source.charAt(i)) - && source.charAt(i) != '-' - && source.charAt(i) != '_' - && source.charAt(i) != ' ') { - return ""; - } - } - return null; - } - }; - edit.setFilters(new InputFilter[] { filterSSID }); - final EditText macs[] = new EditText[6]; - root.findViewById(R.id.manual_mac_root).setVisibility(View.VISIBLE); - edit.setImeOptions(EditorInfo.IME_ACTION_NEXT); - macs[0] = (EditText) root.findViewById(R.id.input_mac_pair1); - macs[1] = (EditText) root.findViewById(R.id.input_mac_pair2); - macs[2] = (EditText) root.findViewById(R.id.input_mac_pair3); - macs[3] = (EditText) root.findViewById(R.id.input_mac_pair4); - macs[4] = (EditText) root.findViewById(R.id.input_mac_pair5); - macs[5] = (EditText) root.findViewById(R.id.input_mac_pair6); - if (macAddress != null) { - macs[0].setText(macAddress.substring(0, 2)); - macs[1].setText(macAddress.substring(2, 4)); - macs[2].setText(macAddress.substring(4, 6)); - macs[3].setText(macAddress.substring(6, 8)); - macs[4].setText(macAddress.substring(8, 10)); - macs[5].setText(macAddress.substring(10, 12)); - } - final InputFilter filterMac = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, - Spanned dest, int dstart, int dend) { - if (dstart >= 2) - return ""; - if (source.length() > 2) - return "";// max 2 chars - for (int i = start; i < end; i++) { - if (Character.digit(source.charAt(i), 16) == -1) { - return ""; - } - } - if (source.length() + dstart > 2) - return source.subSequence(0, 2 - dstart); - return null; - } - }; - for (final EditText mac : macs) { - mac.setFilters(new InputFilter[] { filterMac }); - mac.addTextChangedListener(new TextWatcher() { - public void onTextChanged(CharSequence s, int start, - int before, int count) { - } + public void onItemSelected(String mac) { + } + }; + private View loading; + private View mainView; + private OnItemSelectionListener mCallbacks = sDummyCallbacks; - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } + public static ManualInputFragment newInstance() { + ManualInputFragment frag = new ManualInputFragment(); + frag.setArguments(Bundle.EMPTY); + return frag; + } - public void afterTextChanged(Editable e) { - if (e.length() != 2) - return; + public static ManualInputFragment newInstance(String mac) { + Bundle args = new Bundle(); + if (mac != null) + args.putString(MAC_ADDRESS_ARG, mac.replace(":", "")); + ManualInputFragment frag = new ManualInputFragment(); + frag.setArguments(args); + return frag; + } - for (int i = 0; i < 6; ++i) { - if (macs[i].getText().length() >= 2) - continue; + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + final String macAddress; + if (getArguments().containsKey(MAC_ADDRESS_ARG)) + macAddress = getArguments().getString(MAC_ADDRESS_ARG); + else + macAddress = null; + final View root = inflater + .inflate(R.layout.fragment_manual_input, null); + mainView = root.findViewById(R.id.manual_root); + loading = root.findViewById(R.id.loading_spinner); + final String[] routers = getResources().getStringArray( + R.array.supported_routers); + ArrayAdapter adapter = new ArrayAdapter(getActivity(), + android.R.layout.simple_dropdown_item_1line, routers); + final AutoCompleteTextView edit = (AutoCompleteTextView) root + .findViewById(R.id.manual_autotext); + edit.setAdapter(adapter); + edit.setThreshold(1); + final InputFilter filterSSID = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, + Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + if (!Character.isLetterOrDigit(source.charAt(i)) + && source.charAt(i) != '-' + && source.charAt(i) != '_' + && source.charAt(i) != ' ') { + return ""; + } + } + return null; + } + }; + edit.setFilters(new InputFilter[]{filterSSID}); + final EditText macs[] = new EditText[6]; + root.findViewById(R.id.manual_mac_root).setVisibility(View.VISIBLE); + edit.setImeOptions(EditorInfo.IME_ACTION_NEXT); + macs[0] = (EditText) root.findViewById(R.id.input_mac_pair1); + macs[1] = (EditText) root.findViewById(R.id.input_mac_pair2); + macs[2] = (EditText) root.findViewById(R.id.input_mac_pair3); + macs[3] = (EditText) root.findViewById(R.id.input_mac_pair4); + macs[4] = (EditText) root.findViewById(R.id.input_mac_pair5); + macs[5] = (EditText) root.findViewById(R.id.input_mac_pair6); + if (macAddress != null) { + macs[0].setText(macAddress.substring(0, 2)); + macs[1].setText(macAddress.substring(2, 4)); + macs[2].setText(macAddress.substring(4, 6)); + macs[3].setText(macAddress.substring(6, 8)); + macs[4].setText(macAddress.substring(8, 10)); + macs[5].setText(macAddress.substring(10, 12)); + } + final InputFilter filterMac = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, + Spanned dest, int dstart, int dend) { + if (dstart >= 2) + return ""; + if (source.length() > 2) + return "";// max 2 chars + for (int i = start; i < end; i++) { + if (Character.digit(source.charAt(i), 16) == -1) { + return ""; + } + } + if (source.length() + dstart > 2) + return source.subSequence(0, 2 - dstart); + return null; + } + }; + for (final EditText mac : macs) { + mac.setFilters(new InputFilter[]{filterMac}); + mac.addTextChangedListener(new TextWatcher() { + public void onTextChanged(CharSequence s, int start, + int before, int count) { + } - macs[i].requestFocus(); - return; - } - } - }); - } - Button calc = (Button) root.findViewById(R.id.bt_calc); - calc.setOnClickListener(new View.OnClickListener() { + public void beforeTextChanged(CharSequence s, int start, + int count, int after) { + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public void onClick(View v) { - String ssid = edit.getText().toString().trim(); - StringBuilder mac = new StringBuilder(); - boolean warnUnused = false; - for (EditText m : macs) { - final String mText = m.getText().toString(); - if (mText.length() > 0) - warnUnused = true; - mac.append(mText); - if (!m.equals(macs[5])) - mac.append(":"); // do not add this for the - // last one - } - if (mac.length() < 17) { - mac.setLength(0); - if (warnUnused) - Toast.makeText(getActivity(), R.string.msg_invalid_mac, - Toast.LENGTH_SHORT).show(); - } + public void afterTextChanged(Editable e) { + if (e.length() != 2) + return; - if (ssid.equals("")) - return; - KeygenMatcherTask matcher = new KeygenMatcherTask(ssid, mac - .toString().toUpperCase(Locale.getDefault())); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { - matcher.execute(); - } else { - matcher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + for (int i = 0; i < 6; ++i) { + if (macs[i].getText().length() >= 2) + continue; - } - }); - Button cancel = (Button) root.findViewById(R.id.bt_cancel); - cancel.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - getActivity().onBackPressed(); - } - }); - return root; - } + macs[i].requestFocus(); + return; + } + } + }); + } + Button calc = (Button) root.findViewById(R.id.bt_calc); + calc.setOnClickListener(new View.OnClickListener() { - private static OnItemSelectionListener sDummyCallbacks = new OnItemSelectionListener() { - public void onItemSelected(WiFiNetwork id) { - } + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public void onClick(View v) { + String ssid = edit.getText().toString().trim(); + StringBuilder mac = new StringBuilder(); + boolean warnUnused = false; + for (EditText m : macs) { + final String mText = m.getText().toString(); + if (mText.length() > 0) + warnUnused = true; + mac.append(mText); + if (!m.equals(macs[5])) + mac.append(":"); // do not add this for the + // last one + } + if (mac.length() < 17) { + mac.setLength(0); + if (warnUnused) + Toast.makeText(getActivity(), R.string.msg_invalid_mac, + Toast.LENGTH_SHORT).show(); + } - public void onItemSelected(String mac) { - } - }; + if (ssid.equals("")) + return; + KeygenMatcherTask matcher = new KeygenMatcherTask(ssid, mac + .toString().toUpperCase(Locale.getDefault())); + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { + matcher.execute(); + } else { + matcher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } - private OnItemSelectionListener mCallbacks = sDummyCallbacks; + } + }); + Button cancel = (Button) root.findViewById(R.id.bt_cancel); + cancel.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + getActivity().onBackPressed(); + } + }); + return root; + } - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - if (!(activity instanceof OnItemSelectionListener)) { - throw new IllegalStateException( - "Activity must implement fragment's callbacks."); - } + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + if (!(activity instanceof OnItemSelectionListener)) { + throw new IllegalStateException( + "Activity must implement fragment's callbacks."); + } - mCallbacks = (OnItemSelectionListener) activity; - } + mCallbacks = (OnItemSelectionListener) activity; + } - @Override - public void onDetach() { - super.onDetach(); - mCallbacks = sDummyCallbacks; - } + @Override + public void onDetach() { + super.onDetach(); + mCallbacks = sDummyCallbacks; + } - private class KeygenMatcherTask extends AsyncTask { - private final String ssid; - private final String mac; + private class KeygenMatcherTask extends AsyncTask { + private final String ssid; + private final String mac; - public KeygenMatcherTask(String ssid, String mac) { - this.ssid = ssid; - this.mac = mac; - } + public KeygenMatcherTask(String ssid, String mac) { + this.ssid = ssid; + this.mac = mac; + } - @Override - protected void onPreExecute() { - mainView.setVisibility(View.GONE); - loading.setVisibility(View.VISIBLE); - } + @Override + protected void onPreExecute() { + mainView.setVisibility(View.GONE); + loading.setVisibility(View.VISIBLE); + } - @Override - protected void onPostExecute(WiFiNetwork wifiNetwork) { - loading.setVisibility(View.GONE); - mainView.setVisibility(View.VISIBLE); - if (wifiNetwork.getSupportState() == Keygen.UNSUPPORTED) { - if (getActivity() != null ) { - Toast.makeText(getActivity(), R.string.msg_unspported_network, - Toast.LENGTH_SHORT).show(); - } - return; - } - mCallbacks.onItemSelected(wifiNetwork); - } + @Override + protected void onPostExecute(WiFiNetwork wifiNetwork) { + loading.setVisibility(View.GONE); + mainView.setVisibility(View.VISIBLE); + if (wifiNetwork.getSupportState() == Keygen.UNSUPPORTED) { + if (getActivity() != null) { + Toast.makeText(getActivity(), R.string.msg_unspported_network, + Toast.LENGTH_SHORT).show(); + } + return; + } + mCallbacks.onItemSelected(wifiNetwork); + } - @Override - protected WiFiNetwork doInBackground(Void... params) { - final ZipInputStream magicInfo = new ZipInputStream(getActivity() - .getResources().openRawResource(R.raw.magic_info)); - final WiFiNetwork wifi = new WiFiNetwork(ssid, mac, 0, "", - magicInfo); - try { - magicInfo.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return wifi; - } - } + @Override + protected WiFiNetwork doInBackground(Void... params) { + final ZipInputStream magicInfo = new ZipInputStream(getActivity() + .getResources().openRawResource(R.raw.magic_info)); + final WiFiNetwork wifi = new WiFiNetwork(ssid, mac, 0, "", + magicInfo); + try { + magicInfo.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return wifi; + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/MessagePublisher.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/MessagePublisher.java index 12da1a4..d5ac365 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/MessagePublisher.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/MessagePublisher.java @@ -1,5 +1,5 @@ package org.exobel.routerkeygen.ui; public interface MessagePublisher { - public void setMessage(int message); + void setMessage(int message); } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkActivity.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkActivity.java index 1a5910c..c4fdea6 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkActivity.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkActivity.java @@ -19,11 +19,6 @@ package org.exobel.routerkeygen.ui; -import org.exobel.routerkeygen.AdsUtils; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.RefreshHandler; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NavUtils; @@ -34,79 +29,84 @@ import com.google.android.gms.analytics.GoogleAnalytics; import com.millennialmedia.android.MMAdView; +import org.exobel.routerkeygen.AdsUtils; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.RefreshHandler; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; + public class NetworkActivity extends SherlockFragmentActivity { - private RefreshHandler adRefreshHandler; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_single_fragment); - - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - MMAdView ad = AdsUtils.loadAdIfNeeded(this); - if (ad != null) { - adRefreshHandler = new RefreshHandler(ad); - } - if (savedInstanceState == null) { - final Bundle arguments = new Bundle(); - final WiFiNetwork wiFiNetwork = getIntent().getParcelableExtra(NetworkFragment.NETWORK_ID); - arguments.putParcelable(NetworkFragment.NETWORK_ID, wiFiNetwork); - setTitle(wiFiNetwork.getSsidName()); - NetworkFragment fragment = new NetworkFragment(); - fragment.setArguments(arguments); - getSupportFragmentManager().beginTransaction() - .add(R.id.keygen_fragment, fragment).commit(); - } - } - - - @Override - public void onStart() { - super.onStart(); - //Get an Analytics tracker to report app starts and uncaught exceptions etc. - GoogleAnalytics.getInstance(this).reportActivityStart(this); - - } - - @Override - public void onStop() { - super.onStop(); - //Stop the analytics tracking - GoogleAnalytics.getInstance(this).reportActivityStop(this); - } - - @Override - protected void onResume() { - super.onResume(); - if (adRefreshHandler != null) - adRefreshHandler.onResume(); - } - - @Override - protected void onPause() { - super.onPause(); - if (adRefreshHandler != null) - adRefreshHandler.onPause(); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - NavUtils.navigateUpTo(this, new Intent(this, - NetworksListActivity.class)); - return true; - case R.id.pref: - startActivity(new Intent(this, Preferences.class)); - return true; - } - return super.onOptionsItemSelected(item); - } - - public boolean onCreateOptionsMenu(Menu menu) { - getSupportMenuInflater().inflate(R.menu.preferences, menu); - return true; - } + private RefreshHandler adRefreshHandler; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_single_fragment); + + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + MMAdView ad = AdsUtils.loadAdIfNeeded(this); + if (ad != null) { + adRefreshHandler = new RefreshHandler(ad); + } + if (savedInstanceState == null) { + final Bundle arguments = new Bundle(); + final WiFiNetwork wiFiNetwork = getIntent().getParcelableExtra(NetworkFragment.NETWORK_ID); + arguments.putParcelable(NetworkFragment.NETWORK_ID, wiFiNetwork); + setTitle(wiFiNetwork.getSsidName()); + NetworkFragment fragment = new NetworkFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction() + .add(R.id.keygen_fragment, fragment).commit(); + } + } + + + @Override + public void onStart() { + super.onStart(); + //Get an Analytics tracker to report app starts and uncaught exceptions etc. + GoogleAnalytics.getInstance(this).reportActivityStart(this); + + } + + @Override + public void onStop() { + super.onStop(); + //Stop the analytics tracking + GoogleAnalytics.getInstance(this).reportActivityStop(this); + } + + @Override + protected void onResume() { + super.onResume(); + if (adRefreshHandler != null) + adRefreshHandler.onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + if (adRefreshHandler != null) + adRefreshHandler.onPause(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + NavUtils.navigateUpTo(this, new Intent(this, + NetworksListActivity.class)); + return true; + case R.id.pref: + startActivity(new Intent(this, Preferences.class)); + return true; + } + return super.onOptionsItemSelected(item); + } + + public boolean onCreateOptionsMenu(Menu menu) { + getSupportMenuInflater().inflate(R.menu.preferences, menu); + return true; + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkFragment.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkFragment.java index f1f4332..0f6c98c 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkFragment.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworkFragment.java @@ -19,25 +19,6 @@ package org.exobel.routerkeygen.ui; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.zip.ZipInputStream; - -import org.acra.ACRA; -import org.exobel.routerkeygen.AdsUtils; -import org.exobel.routerkeygen.AutoConnectService; -import org.exobel.routerkeygen.BuildConfig; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.algorithms.Keygen; -import org.exobel.routerkeygen.algorithms.NativeThomson; -import org.exobel.routerkeygen.algorithms.ThomsonKeygen; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.annotation.TargetApi; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; @@ -70,16 +51,39 @@ import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; +import org.acra.ACRA; +import org.exobel.routerkeygen.AdsUtils; +import org.exobel.routerkeygen.AutoConnectService; +import org.exobel.routerkeygen.BuildConfig; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.algorithms.Keygen; +import org.exobel.routerkeygen.algorithms.NativeThomson; +import org.exobel.routerkeygen.algorithms.ThomsonKeygen; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.zip.ZipInputStream; + @SuppressWarnings("deprecation") public class NetworkFragment extends SherlockFragment { public static final String NETWORK_ID = "vulnerable_network"; public static final String TAG = "NetworkFragment"; + private static final String PASSWORD_LIST = "password_list"; private WiFiNetwork wifiNetwork; private KeygenThread thread; private ViewSwitcher root; private TextView messages; private List passwordList; + private boolean thomson3g; + private boolean nativeCalc; + private String dicFile; public NetworkFragment() { } @@ -105,7 +109,7 @@ public void onCreate(Bundle savedInstanceState) { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + Bundle savedInstanceState) { root = (ViewSwitcher) inflater.inflate(R.layout.fragment_network, container, false); messages = (TextView) root.findViewById(R.id.loading_text); @@ -160,8 +164,6 @@ private boolean isAutoConnectServiceRunning() { return false; } - private static final String PASSWORD_LIST = "password_list"; - @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); @@ -189,7 +191,7 @@ public void onActivityCreated(Bundle savedInstanceState) { @Override public void onDetach() { super.onDetach(); - if (thread != null){ + if (thread != null) { //This thread can be null if there was a previosly calculated //password list thread.cancel(); @@ -200,7 +202,7 @@ public void onDetach() { * Some devices seem to have bugs with the parcelable implementation * So we try to restore missing objects here. */ - private void restoreMissingKeygens(){ + private void restoreMissingKeygens() { boolean foundMissingKeygen = false; for (Keygen keygen : wifiNetwork.getKeygens()) { if (keygen == null) { @@ -208,7 +210,7 @@ private void restoreMissingKeygens(){ break; } } - if (foundMissingKeygen){ + if (foundMissingKeygen) { //If any is missing, simply replace them all. ZipInputStream zipInputStream = new ZipInputStream( getActivity().getResources().openRawResource(R.raw.magic_info)); @@ -231,70 +233,70 @@ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_share: - try { + case R.id.menu_share: + try { + if (passwordList == null) + return true; + Intent i = new Intent(Intent.ACTION_SEND); + i.setType("text/plain"); + i.putExtra(Intent.EXTRA_SUBJECT, wifiNetwork.getSsidName() + + getString(R.string.share_msg_begin)); + final StringBuilder message = new StringBuilder( + wifiNetwork.getSsidName()); + message.append("\n"); + message.append(getString(R.string.share_msg_begin)); + message.append(":\n"); + for (String password : passwordList) { + message.append(password); + message.append('\n'); + } + i.putExtra(Intent.EXTRA_TEXT, message.toString()); + startActivity(Intent.createChooser(i, + getString(R.string.share_title))); + } catch (Exception e) { + Toast.makeText(getActivity(), R.string.msg_err_sendto, + Toast.LENGTH_SHORT).show(); + } + return true; + case R.id.menu_save_sd: + if (!Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED)) { + Toast.makeText(getActivity(), R.string.msg_nosdcard, + Toast.LENGTH_SHORT).show(); + return true; + } if (passwordList == null) return true; - Intent i = new Intent(Intent.ACTION_SEND); - i.setType("text/plain"); - i.putExtra(Intent.EXTRA_SUBJECT, wifiNetwork.getSsidName() - + getString(R.string.share_msg_begin)); final StringBuilder message = new StringBuilder( wifiNetwork.getSsidName()); - message.append("\n"); - message.append(getString(R.string.share_msg_begin)); - message.append(":\n"); + message.append(" KEYS\n"); for (String password : passwordList) { message.append(password); message.append('\n'); } - i.putExtra(Intent.EXTRA_TEXT, message.toString()); - startActivity(Intent.createChooser(i, - getString(R.string.share_title))); - } catch (Exception e) { - Toast.makeText(getActivity(), R.string.msg_err_sendto, - Toast.LENGTH_SHORT).show(); - } - return true; - case R.id.menu_save_sd: - if (!Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { - Toast.makeText(getActivity(), R.string.msg_nosdcard, - Toast.LENGTH_SHORT).show(); - return true; - } - if (passwordList == null) - return true; - final StringBuilder message = new StringBuilder( - wifiNetwork.getSsidName()); - message.append(" KEYS\n"); - for (String password : passwordList) { - message.append(password); - message.append('\n'); - } - try { - getPrefs(); - final String path = new File(dicFile).getParent(); - final BufferedWriter out = new BufferedWriter(new FileWriter( - (path != null ? path - : Environment.getExternalStorageDirectory()) - + File.separator - + wifiNetwork.getSsidName() - + ".txt")); - out.write(message.toString()); - out.close(); - } catch (IOException e) { - Toast.makeText(getActivity(), - getString(R.string.msg_err_saving_key_file), + try { + getPrefs(); + final String path = new File(dicFile).getParent(); + final BufferedWriter out = new BufferedWriter(new FileWriter( + (path != null ? path + : Environment.getExternalStorageDirectory()) + + File.separator + + wifiNetwork.getSsidName() + + ".txt")); + out.write(message.toString()); + out.close(); + } catch (IOException e) { + Toast.makeText(getActivity(), + getString(R.string.msg_err_saving_key_file), + Toast.LENGTH_SHORT).show(); + return true; + } + Toast.makeText( + getActivity(), + wifiNetwork.getSsidName() + ".txt " + + getString(R.string.msg_saved_key_file), Toast.LENGTH_SHORT).show(); return true; - } - Toast.makeText( - getActivity(), - wifiNetwork.getSsidName() + ".txt " - + getString(R.string.msg_saved_key_file), - Toast.LENGTH_SHORT).show(); - return true; } return super.onOptionsItemSelected(item); } @@ -307,7 +309,7 @@ private void displayResults() { final ListView list = (ListView) root.findViewById(R.id.list_keys); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View view, - int position, long id) { + int position, long id) { final String key = ((TextView) view).getText().toString(); Toast.makeText(getActivity(), getString(R.string.msg_copied, key), @@ -325,7 +327,20 @@ public void onItemClick(AdapterView parent, View view, } } + private void getPrefs() { + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(getActivity()); + thomson3g = prefs.getBoolean(Preferences.thomson3gPref, false); + nativeCalc = prefs.getBoolean(Preferences.nativeCalcPref, true); + dicFile = prefs.getString(Preferences.dicLocalPref, Environment + .getExternalStorageDirectory().getAbsolutePath() + + "RouterKeygen.dic"); + } + private class KeygenThread extends AsyncTask> { + private final static int SHOW_TOAST = 0; + private final static int SHOW_MESSAGE_WITH_SPINNER = 1; + private final static int SHOW_MESSAGE_NO_SPINNER = 2; private WiFiNetwork wifiNetwork; private KeygenThread(WiFiNetwork wifiNetwork) { @@ -358,22 +373,22 @@ protected void onProgressUpdate(Integer... values) { return; for (int i = 0; i < values.length; i += 2) { switch (values[i]) { - case SHOW_TOAST: - Toast.makeText(getActivity(), values[i + 1], - Toast.LENGTH_SHORT).show(); + case SHOW_TOAST: + Toast.makeText(getActivity(), values[i + 1], + Toast.LENGTH_SHORT).show(); - break; - case SHOW_MESSAGE_NO_SPINNER: - messages.setText(values[i + 1]); - root.findViewById(R.id.loading_spinner).setVisibility( - View.GONE); - break; + break; + case SHOW_MESSAGE_NO_SPINNER: + messages.setText(values[i + 1]); + root.findViewById(R.id.loading_spinner).setVisibility( + View.GONE); + break; - case SHOW_MESSAGE_WITH_SPINNER: - messages.setText(values[i + 1]); - root.findViewById(R.id.loading_spinner).setVisibility( - View.VISIBLE); - break; + case SHOW_MESSAGE_WITH_SPINNER: + messages.setText(values[i + 1]); + root.findViewById(R.id.loading_spinner).setVisibility( + View.VISIBLE); + break; } } @@ -385,10 +400,6 @@ public void cancel() { cancel(true); } - private final static int SHOW_TOAST = 0; - private final static int SHOW_MESSAGE_WITH_SPINNER = 1; - private final static int SHOW_MESSAGE_NO_SPINNER = 2; - @Override protected List doInBackground(Void... params) { final List result = new ArrayList<>(); @@ -412,7 +423,7 @@ protected List doInBackground(Void... params) { ACRA.getErrorReporter().handleException(e); if (keygen instanceof ThomsonKeygen) { ((ThomsonKeygen) keygen).setErrorDict(true);// native - // should + // should // never crash } } @@ -464,18 +475,4 @@ private List calcKeys(Keygen keygen) { } - private boolean thomson3g; - private boolean nativeCalc; - private String dicFile; - - private void getPrefs() { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getActivity()); - thomson3g = prefs.getBoolean(Preferences.thomson3gPref, false); - nativeCalc = prefs.getBoolean(Preferences.nativeCalcPref, true); - dicFile = prefs.getString(Preferences.dicLocalPref, Environment - .getExternalStorageDirectory().getAbsolutePath() - + "RouterKeygen.dic"); - } - } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListActivity.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListActivity.java index 92da36c..6e3c81f 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListActivity.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListActivity.java @@ -19,16 +19,6 @@ package org.exobel.routerkeygen.ui; -import org.exobel.routerkeygen.AdsUtils; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.RefreshHandler; -import org.exobel.routerkeygen.UpdateCheckerService; -import org.exobel.routerkeygen.WifiScanReceiver; -import org.exobel.routerkeygen.WifiScanReceiver.OnScanListener; -import org.exobel.routerkeygen.WifiStateReceiver; -import org.exobel.routerkeygen.algorithms.Keygen; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.BroadcastReceiver; @@ -54,317 +44,324 @@ import com.google.android.gms.analytics.GoogleAnalytics; import com.millennialmedia.android.MMAdView; -public class NetworksListActivity extends SherlockFragmentActivity implements - NetworksListFragment.OnItemSelectionListener, OnScanListener { - private final static String LAST_DIALOG_TIME = "last_time"; - private boolean mTwoPane; - private NetworksListFragment networkListFragment; - private WifiManager wifi; - private BroadcastReceiver scanFinished; - private BroadcastReceiver stateChanged; - private boolean welcomeScreenShown; - private RefreshHandler adRefreshHandler; - - private Handler mHandler = new Handler(); - - @TargetApi(Build.VERSION_CODES.GINGERBREAD) - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_networks_list); - - networkListFragment = ((NetworksListFragment) getSupportFragmentManager() - .findFragmentById(R.id.frag_networks_list)); - if (findViewById(R.id.keygen_fragment) != null) { - mTwoPane = true; - networkListFragment.setActivateOnItemClick(true); - } - wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); - - wifiState = wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED - || wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING; - scanFinished = new WifiScanReceiver(wifi, networkListFragment, this); - stateChanged = new WifiStateReceiver(wifi, networkListFragment); - - final MMAdView ad = AdsUtils.loadAdIfNeeded(this); - if (ad != null) { - adRefreshHandler = new RefreshHandler(ad); - } - final SharedPreferences mPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - welcomeScreenShown = mPrefs.getBoolean(Preferences.VERSION, false); - - final long timePassed = System.currentTimeMillis() - - mPrefs.getLong(LAST_DIALOG_TIME, 0); - if (!welcomeScreenShown || (timePassed > DateUtils.WEEK_IN_MILLIS)) { - final SharedPreferences.Editor editor = mPrefs.edit(); - editor.putBoolean(Preferences.VERSION, true); - editor.putLong(LAST_DIALOG_TIME, System.currentTimeMillis()); - editor.apply(); - - // Checking for updates every week - startService(new Intent(getApplicationContext(), - UpdateCheckerService.class)); - if (!AdsUtils.checkDonation(this)) { - final String whatsNewTitle = getString(R.string.msg_welcome_title); - final String whatsNewText = getString(R.string.msg_welcome_text); - new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_dialog_alert) - .setTitle(whatsNewTitle) - .setMessage(whatsNewText) - .setNegativeButton(R.string.bt_dont_donate, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - dialog.dismiss(); - } - }) - .setNeutralButton(R.string.bt_paypal, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - final String donateLink = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V3FFBTRTTV5DN"; - Uri uri = Uri.parse(donateLink); - startActivity(new Intent( - Intent.ACTION_VIEW, uri)); - dialog.dismiss(); - } - }) - .setPositiveButton(R.string.bt_google_play, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - try { - startActivity(new Intent( - Intent.ACTION_VIEW, - Uri.parse("market://details?id=" - + Preferences.GOOGLE_PLAY_DOWNLOADER))); - } catch (android.content.ActivityNotFoundException anfe) { - startActivity(new Intent( - Intent.ACTION_VIEW, - Uri.parse("http://play.google.com/store/apps/details?id=" - + Preferences.GOOGLE_PLAY_DOWNLOADER))); - } - Toast.makeText(getApplicationContext(), - R.string.msg_donation, - Toast.LENGTH_LONG).show(); - dialog.dismiss(); - } - }).show(); - } - } - if (welcomeScreenShown){ - AdsUtils.displayStartupInterstitial(this); - } - - } - - @Override - public void onItemSelected(WiFiNetwork keygen) { - if (mTwoPane) { - final Bundle arguments = new Bundle(); - arguments.putParcelable(NetworkFragment.NETWORK_ID, keygen); - final NetworkFragment fragment = new NetworkFragment(); - fragment.setArguments(arguments); - getSupportFragmentManager().beginTransaction() - .replace(R.id.keygen_fragment, fragment).commit(); - - } else { - if (keygen.getSupportState() == Keygen.UNSUPPORTED) { - Toast.makeText(this, R.string.msg_unspported, - Toast.LENGTH_SHORT).show(); - return; - } - Intent detailIntent = new Intent(this, NetworkActivity.class); - detailIntent.putExtra(NetworkFragment.NETWORK_ID, keygen); - startActivity(detailIntent); - } - } - - public boolean onCreateOptionsMenu(Menu menu) { - mOptionsMenu = menu; - getSupportMenuInflater().inflate(R.menu.networks_list, menu); - getSupportMenuInflater().inflate(R.menu.preferences, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.manual_input: - if (mTwoPane) { - getSupportFragmentManager() - .beginTransaction() - .replace(R.id.keygen_fragment, - ManualInputFragment.newInstance()).commit(); - } else { - startActivity(new Intent(this, ManualInputActivity.class)); - } - return true; - case R.id.wifi_scan: - scan(); - return true; - case R.id.pref: - startActivity(new Intent(this, Preferences.class)); - return true; - default: - return super.onOptionsItemSelected(item); - } - } - - @Override - public void onStart() { - super.onStart(); - //Get an Analytics tracker to report app starts and uncaught exceptions etc. - GoogleAnalytics.getInstance(this).reportActivityStart(this); - getPrefs(); - if (wifiOn) { - try { - if (!wifi.setWifiEnabled(true)) - networkListFragment.setMessage(R.string.msg_wifibroken); - else - wifiState = true; - } catch (SecurityException e) { - // Workaround for - // http://code.google.com/p/android/issues/detail?id=22036 - networkListFragment.setMessage(R.string.msg_wifibroken); - } - } - } - - @Override - public void onResume() { - super.onResume(); - getPrefs(); - GoogleAnalytics.getInstance(this).setAppOptOut(!analyticsOptIn); - if (autoScan) { - mHandler.removeCallbacks(mAutoScanTask); - mHandler.postDelayed(mAutoScanTask, autoScanInterval * 1000L); - } else - mHandler.removeCallbacks(mAutoScanTask); - scan(); - if (adRefreshHandler != null) - adRefreshHandler.onResume(); - } - - @Override - public void onPause() { - super.onPause(); - try { - mHandler.removeCallbacks(mAutoScanTask); - } catch (Exception e) { - } - if (adRefreshHandler != null) - adRefreshHandler.onPause(); - } - - @Override - public void onStop() { - super.onStop(); - try { - //Stop the analytics tracking - GoogleAnalytics.getInstance(this).reportActivityStop(this); - unregisterReceiver(scanFinished); - unregisterReceiver(stateChanged); - } catch (Exception e) { - } - } - - private Menu mOptionsMenu; - private View mRefreshIndeterminateProgressView = null; - - public void setRefreshActionItemState(boolean refreshing) { - // On Honeycomb, we can set the state of the refresh button by giving it - // a custom - // action view. - if (mOptionsMenu == null) { - return; - } - - final MenuItem refreshItem = mOptionsMenu.findItem(R.id.wifi_scan); - if (refreshItem != null) { - if (refreshing) { - if (mRefreshIndeterminateProgressView == null) { - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - mRefreshIndeterminateProgressView = inflater.inflate( - R.layout.actionbar_indeterminate_progress, null); - } - - refreshItem.setActionView(mRefreshIndeterminateProgressView); - } else { - refreshItem.setActionView(null); - } - } - } - - public void scan() { - if (!wifiState && !wifiOn) { - networkListFragment.setMessage(R.string.msg_nowifi); - return; - } - registerReceiver(scanFinished, new IntentFilter( - WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); - if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { - registerReceiver(stateChanged, new IntentFilter( - WifiManager.WIFI_STATE_CHANGED_ACTION)); - Toast.makeText(this, R.string.msg_wifienabling, Toast.LENGTH_SHORT) - .show(); - } else { - if (wifi.startScan()) { - setRefreshActionItemState(true); - } else - networkListFragment.setMessage(R.string.msg_scanfailed); - } - } - - private Runnable mAutoScanTask = new Runnable() { - @Override - public void run() { - scan(); - mHandler.postDelayed(mAutoScanTask, autoScanInterval * 1000L); - } - }; - - private boolean wifiState; - private boolean wifiOn; - private boolean autoScan; - private boolean analyticsOptIn; - private long autoScanInterval; - - private void getPrefs() { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); - wifiOn = prefs.getBoolean(Preferences.wifiOnPref, getResources() - .getBoolean(R.bool.wifiOnDefault)); - autoScan = prefs.getBoolean(Preferences.autoScanPref, getResources() - .getBoolean(R.bool.autoScanDefault)); - autoScanInterval = prefs.getInt(Preferences.autoScanIntervalPref, - getResources().getInteger(R.integer.autoScanIntervalDefault)); - analyticsOptIn = prefs.getBoolean(Preferences.analyticsPref, - getResources().getBoolean(R.bool.analyticsDefault)); - } - - @Override - public void onScanFinished(WiFiNetwork[] networks) { - setRefreshActionItemState(false); - if (!welcomeScreenShown) { - Toast.makeText(this, R.string.msg_welcome_tip, Toast.LENGTH_LONG) - .show(); - welcomeScreenShown = true; - } - } +import org.exobel.routerkeygen.AdsUtils; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.RefreshHandler; +import org.exobel.routerkeygen.UpdateCheckerService; +import org.exobel.routerkeygen.WifiScanReceiver; +import org.exobel.routerkeygen.WifiScanReceiver.OnScanListener; +import org.exobel.routerkeygen.WifiStateReceiver; +import org.exobel.routerkeygen.algorithms.Keygen; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; - @Override - public void onItemSelected(String mac) { - if (mTwoPane) { - getSupportFragmentManager() - .beginTransaction() - .replace(R.id.keygen_fragment, - ManualInputFragment.newInstance(mac)).commit(); - } else { - startActivity(new Intent(this, ManualInputActivity.class).putExtra( - ManualInputFragment.MAC_ADDRESS_ARG, mac)); - } - } +public class NetworksListActivity extends SherlockFragmentActivity implements + NetworksListFragment.OnItemSelectionListener, OnScanListener { + private final static String LAST_DIALOG_TIME = "last_time"; + private boolean mTwoPane; + private NetworksListFragment networkListFragment; + private WifiManager wifi; + private BroadcastReceiver scanFinished; + private BroadcastReceiver stateChanged; + private boolean welcomeScreenShown; + private RefreshHandler adRefreshHandler; + + private Handler mHandler = new Handler(); + private Menu mOptionsMenu; + private View mRefreshIndeterminateProgressView = null; + private boolean wifiState; + private boolean wifiOn; + private boolean autoScan; + private boolean analyticsOptIn; + private long autoScanInterval; + private Runnable mAutoScanTask = new Runnable() { + @Override + public void run() { + scan(); + mHandler.postDelayed(mAutoScanTask, autoScanInterval * 1000L); + } + }; + + @TargetApi(Build.VERSION_CODES.GINGERBREAD) + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_networks_list); + + networkListFragment = ((NetworksListFragment) getSupportFragmentManager() + .findFragmentById(R.id.frag_networks_list)); + if (findViewById(R.id.keygen_fragment) != null) { + mTwoPane = true; + networkListFragment.setActivateOnItemClick(true); + } + wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); + + wifiState = wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED + || wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING; + scanFinished = new WifiScanReceiver(wifi, networkListFragment, this); + stateChanged = new WifiStateReceiver(wifi, networkListFragment); + + final MMAdView ad = AdsUtils.loadAdIfNeeded(this); + if (ad != null) { + adRefreshHandler = new RefreshHandler(ad); + } + final SharedPreferences mPrefs = PreferenceManager + .getDefaultSharedPreferences(this); + welcomeScreenShown = mPrefs.getBoolean(Preferences.VERSION, false); + + final long timePassed = System.currentTimeMillis() + - mPrefs.getLong(LAST_DIALOG_TIME, 0); + if (!welcomeScreenShown || (timePassed > DateUtils.WEEK_IN_MILLIS)) { + final SharedPreferences.Editor editor = mPrefs.edit(); + editor.putBoolean(Preferences.VERSION, true); + editor.putLong(LAST_DIALOG_TIME, System.currentTimeMillis()); + editor.apply(); + + // Checking for updates every week + startService(new Intent(getApplicationContext(), + UpdateCheckerService.class)); + if (!AdsUtils.checkDonation(this)) { + final String whatsNewTitle = getString(R.string.msg_welcome_title); + final String whatsNewText = getString(R.string.msg_welcome_text); + new AlertDialog.Builder(this) + .setIcon(android.R.drawable.ic_dialog_alert) + .setTitle(whatsNewTitle) + .setMessage(whatsNewText) + .setNegativeButton(R.string.bt_dont_donate, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + dialog.dismiss(); + } + }) + .setNeutralButton(R.string.bt_paypal, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + final String donateLink = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V3FFBTRTTV5DN"; + Uri uri = Uri.parse(donateLink); + startActivity(new Intent( + Intent.ACTION_VIEW, uri)); + dialog.dismiss(); + } + }) + .setPositiveButton(R.string.bt_google_play, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + try { + startActivity(new Intent( + Intent.ACTION_VIEW, + Uri.parse("market://details?id=" + + Preferences.GOOGLE_PLAY_DOWNLOADER))); + } catch (android.content.ActivityNotFoundException anfe) { + startActivity(new Intent( + Intent.ACTION_VIEW, + Uri.parse("http://play.google.com/store/apps/details?id=" + + Preferences.GOOGLE_PLAY_DOWNLOADER))); + } + Toast.makeText(getApplicationContext(), + R.string.msg_donation, + Toast.LENGTH_LONG).show(); + dialog.dismiss(); + } + }).show(); + } + } + if (welcomeScreenShown) { + AdsUtils.displayStartupInterstitial(this); + } + + } + + @Override + public void onItemSelected(WiFiNetwork keygen) { + if (mTwoPane) { + final Bundle arguments = new Bundle(); + arguments.putParcelable(NetworkFragment.NETWORK_ID, keygen); + final NetworkFragment fragment = new NetworkFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction() + .replace(R.id.keygen_fragment, fragment).commit(); + + } else { + if (keygen.getSupportState() == Keygen.UNSUPPORTED) { + Toast.makeText(this, R.string.msg_unspported, + Toast.LENGTH_SHORT).show(); + return; + } + Intent detailIntent = new Intent(this, NetworkActivity.class); + detailIntent.putExtra(NetworkFragment.NETWORK_ID, keygen); + startActivity(detailIntent); + } + } + + public boolean onCreateOptionsMenu(Menu menu) { + mOptionsMenu = menu; + getSupportMenuInflater().inflate(R.menu.networks_list, menu); + getSupportMenuInflater().inflate(R.menu.preferences, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.manual_input: + if (mTwoPane) { + getSupportFragmentManager() + .beginTransaction() + .replace(R.id.keygen_fragment, + ManualInputFragment.newInstance()).commit(); + } else { + startActivity(new Intent(this, ManualInputActivity.class)); + } + return true; + case R.id.wifi_scan: + scan(); + return true; + case R.id.pref: + startActivity(new Intent(this, Preferences.class)); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + @Override + public void onStart() { + super.onStart(); + //Get an Analytics tracker to report app starts and uncaught exceptions etc. + GoogleAnalytics.getInstance(this).reportActivityStart(this); + getPrefs(); + if (wifiOn) { + try { + if (!wifi.setWifiEnabled(true)) + networkListFragment.setMessage(R.string.msg_wifibroken); + else + wifiState = true; + } catch (SecurityException e) { + // Workaround for + // http://code.google.com/p/android/issues/detail?id=22036 + networkListFragment.setMessage(R.string.msg_wifibroken); + } + } + } + + @Override + public void onResume() { + super.onResume(); + getPrefs(); + GoogleAnalytics.getInstance(this).setAppOptOut(!analyticsOptIn); + if (autoScan) { + mHandler.removeCallbacks(mAutoScanTask); + mHandler.postDelayed(mAutoScanTask, autoScanInterval * 1000L); + } else + mHandler.removeCallbacks(mAutoScanTask); + scan(); + if (adRefreshHandler != null) + adRefreshHandler.onResume(); + } + + @Override + public void onPause() { + super.onPause(); + try { + mHandler.removeCallbacks(mAutoScanTask); + } catch (Exception e) { + } + if (adRefreshHandler != null) + adRefreshHandler.onPause(); + } + + @Override + public void onStop() { + super.onStop(); + try { + //Stop the analytics tracking + GoogleAnalytics.getInstance(this).reportActivityStop(this); + unregisterReceiver(scanFinished); + unregisterReceiver(stateChanged); + } catch (Exception e) { + } + } + + public void setRefreshActionItemState(boolean refreshing) { + // On Honeycomb, we can set the state of the refresh button by giving it + // a custom + // action view. + if (mOptionsMenu == null) { + return; + } + + final MenuItem refreshItem = mOptionsMenu.findItem(R.id.wifi_scan); + if (refreshItem != null) { + if (refreshing) { + if (mRefreshIndeterminateProgressView == null) { + LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mRefreshIndeterminateProgressView = inflater.inflate( + R.layout.actionbar_indeterminate_progress, null); + } + + refreshItem.setActionView(mRefreshIndeterminateProgressView); + } else { + refreshItem.setActionView(null); + } + } + } + + public void scan() { + if (!wifiState && !wifiOn) { + networkListFragment.setMessage(R.string.msg_nowifi); + return; + } + registerReceiver(scanFinished, new IntentFilter( + WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); + if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { + registerReceiver(stateChanged, new IntentFilter( + WifiManager.WIFI_STATE_CHANGED_ACTION)); + Toast.makeText(this, R.string.msg_wifienabling, Toast.LENGTH_SHORT) + .show(); + } else { + if (wifi.startScan()) { + setRefreshActionItemState(true); + } else + networkListFragment.setMessage(R.string.msg_scanfailed); + } + } + + private void getPrefs() { + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(getBaseContext()); + wifiOn = prefs.getBoolean(Preferences.wifiOnPref, getResources() + .getBoolean(R.bool.wifiOnDefault)); + autoScan = prefs.getBoolean(Preferences.autoScanPref, getResources() + .getBoolean(R.bool.autoScanDefault)); + autoScanInterval = prefs.getInt(Preferences.autoScanIntervalPref, + getResources().getInteger(R.integer.autoScanIntervalDefault)); + analyticsOptIn = prefs.getBoolean(Preferences.analyticsPref, + getResources().getBoolean(R.bool.analyticsDefault)); + } + + @Override + public void onScanFinished(WiFiNetwork[] networks) { + setRefreshActionItemState(false); + if (!welcomeScreenShown) { + Toast.makeText(this, R.string.msg_welcome_tip, Toast.LENGTH_LONG) + .show(); + welcomeScreenShown = true; + } + } + + @Override + public void onItemSelected(String mac) { + if (mTwoPane) { + getSupportFragmentManager() + .beginTransaction() + .replace(R.id.keygen_fragment, + ManualInputFragment.newInstance(mac)).commit(); + } else { + startActivity(new Intent(this, ManualInputActivity.class).putExtra( + ManualInputFragment.MAC_ADDRESS_ARG, mac)); + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListFragment.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListFragment.java index 12ae373..99b9916 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListFragment.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/NetworksListFragment.java @@ -19,10 +19,6 @@ package org.exobel.routerkeygen.ui; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.WifiScanReceiver.OnScanListener; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -45,203 +41,203 @@ import com.actionbarsherlock.app.SherlockFragment; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.WifiScanReceiver.OnScanListener; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; + @SuppressWarnings("deprecation") public class NetworksListFragment extends SherlockFragment implements - OnScanListener, OnItemClickListener, MessagePublisher { - - private static final String STATE_ACTIVATED_POSITION = "activated_position"; - private static final String NETWORKS_FOUND = "network_found"; - - private OnItemSelectionListener mCallbacks = sDummyCallbacks; - private int mActivatedPosition = ListView.INVALID_POSITION; - private ListView listview; - private WifiListAdapter wifiListAdapter; - private View noNetworksMessage; - - private WiFiNetwork[] networksFound; - - public interface OnItemSelectionListener { - - public void onItemSelected(WiFiNetwork id); - - public void onItemSelected(String mac); - } - - private static OnItemSelectionListener sDummyCallbacks = new OnItemSelectionListener() { - public void onItemSelected(WiFiNetwork id) { - } - - public void onItemSelected(String mac) { - } - }; - - public NetworksListFragment() { - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - super.onCreateView(inflater, container, savedInstanceState); - RelativeLayout root = (RelativeLayout) inflater.inflate( - R.layout.fragment_networks_list, container, false); - listview = (ListView) root.findViewById(R.id.networks_list); - wifiListAdapter = new WifiListAdapter(getActivity()); - listview.setAdapter(wifiListAdapter); - noNetworksMessage = root.findViewById(R.id.message_group); - if (savedInstanceState != null) { - if (savedInstanceState.containsKey(NETWORKS_FOUND)) { - Parcelable[] storedNetworksFound = savedInstanceState - .getParcelableArray(NETWORKS_FOUND); - networksFound = new WiFiNetwork[storedNetworksFound.length]; - for (int i = 0; i < storedNetworksFound.length; ++i) - networksFound[i] = (WiFiNetwork) storedNetworksFound[i]; - onScanFinished(networksFound); - } - if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { - setActivatedPosition(savedInstanceState - .getInt(STATE_ACTIVATED_POSITION)); - } - } - registerForContextMenu(listview); - listview.setOnItemClickListener(this); - return root; - } - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - if (!(activity instanceof OnItemSelectionListener)) { - throw new IllegalStateException( - "Activity must implement fragment's callbacks."); - } - - mCallbacks = (OnItemSelectionListener) activity; - } - - @Override - public void onDetach() { - super.onDetach(); - mCallbacks = sDummyCallbacks; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if (networksFound != null) - outState.putParcelableArray(NETWORKS_FOUND, networksFound); - if (mActivatedPosition != ListView.INVALID_POSITION) { - outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); - } - } - - public void setActivateOnItemClick(boolean activateOnItemClick) { - listview.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE - : ListView.CHOICE_MODE_NONE); - } - - public void setActivatedPosition(int position) { - if (position == ListView.INVALID_POSITION) { - listview.setItemChecked(mActivatedPosition, false); - } else { - listview.setItemChecked(position, true); - } - - mActivatedPosition = position; - } - - private static final String MENU_VALUE = "menu_value"; - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenu.ContextMenuInfo menuInfo) { - super.onCreateContextMenu(menu, v, menuInfo); - final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; - if (networksFound == null || wifiListAdapter.getCount() <= info.position) - return; - final WiFiNetwork wiFiNetwork = wifiListAdapter.getItem(info.position).wifiNetwork; - if (wiFiNetwork == null) // the list is unstable and it can happen - return; - - MenuInflater inflater = getActivity().getMenuInflater(); - inflater.inflate(R.menu.networks_context_menu, menu); - // We are copying the values right away as the networks list is - // unstable. - ((MenuItem) menu.findItem(R.id.copy_ssid)).setIntent(new Intent() - .putExtra(MENU_VALUE, wiFiNetwork.getSsidName())); - ((MenuItem) menu.findItem(R.id.copy_mac)).setIntent(new Intent() - .putExtra(MENU_VALUE, wiFiNetwork.getMacAddress())); - ((MenuItem) menu.findItem(R.id.use_mac)).setIntent(new Intent() - .putExtra(MENU_VALUE, wiFiNetwork.getMacAddress())); - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - String value = item.getIntent().getStringExtra(MENU_VALUE); - switch (item.getItemId()) { - case R.id.copy_ssid: { - ClipboardManager clipboard = (ClipboardManager) getActivity() - .getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText(value); - Toast.makeText(getActivity(), - getString(R.string.msg_copied, value), Toast.LENGTH_SHORT) - .show(); - return true; - } - case R.id.copy_mac: { - ClipboardManager clipboard = (ClipboardManager) getActivity() - .getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText(value); - Toast.makeText(getActivity(), - getString(R.string.msg_copied, value), Toast.LENGTH_SHORT) - .show(); - return true; - } - case R.id.use_mac: - mCallbacks.onItemSelected(value); - return true; - } - return super.onContextItemSelected(item); - } - - public void setMessage(int message) { - noNetworksMessage.findViewById(R.id.loading_spinner).setVisibility( - View.GONE); - listview.setVisibility(View.GONE); - TextView messageView = (TextView) noNetworksMessage - .findViewById(R.id.message); - messageView.setVisibility(View.VISIBLE); - messageView.setText(message); - noNetworksMessage.setVisibility(View.VISIBLE); - } - - public void onScanFinished(WiFiNetwork[] networks) { - networksFound = networks; - if (getActivity() == null) - return; - if (networks.length > 0) { - noNetworksMessage.setVisibility(View.GONE); - wifiListAdapter.updateNetworks(networks); - listview.setVisibility(View.VISIBLE); - } else { - noNetworksMessage.findViewById(R.id.loading_spinner).setVisibility( - View.GONE); - listview.setVisibility(View.GONE); - listview.setVisibility(View.GONE); - TextView messageView = (TextView) noNetworksMessage - .findViewById(R.id.message); - messageView.setVisibility(View.VISIBLE); - messageView.setText(R.string.msg_nowifidetected); - noNetworksMessage.setVisibility(View.VISIBLE); - } - } - - public void onItemClick(AdapterView list, View view, int position, - long id) { - if (networksFound != null && wifiListAdapter.getCount() > position) { - final WiFiNetwork wifiNetwork = wifiListAdapter.getItem(position).wifiNetwork; - if (wifiNetwork != null) // the list is unstable and it can happen - mCallbacks.onItemSelected(wifiNetwork); - } - } + OnScanListener, OnItemClickListener, MessagePublisher { + + private static final String STATE_ACTIVATED_POSITION = "activated_position"; + private static final String NETWORKS_FOUND = "network_found"; + private static final String MENU_VALUE = "menu_value"; + private static OnItemSelectionListener sDummyCallbacks = new OnItemSelectionListener() { + public void onItemSelected(WiFiNetwork id) { + } + + public void onItemSelected(String mac) { + } + }; + private OnItemSelectionListener mCallbacks = sDummyCallbacks; + private int mActivatedPosition = ListView.INVALID_POSITION; + private ListView listview; + private WifiListAdapter wifiListAdapter; + private View noNetworksMessage; + private WiFiNetwork[] networksFound; + + public NetworksListFragment() { + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + RelativeLayout root = (RelativeLayout) inflater.inflate( + R.layout.fragment_networks_list, container, false); + listview = (ListView) root.findViewById(R.id.networks_list); + wifiListAdapter = new WifiListAdapter(getActivity()); + listview.setAdapter(wifiListAdapter); + noNetworksMessage = root.findViewById(R.id.message_group); + if (savedInstanceState != null) { + if (savedInstanceState.containsKey(NETWORKS_FOUND)) { + Parcelable[] storedNetworksFound = savedInstanceState + .getParcelableArray(NETWORKS_FOUND); + networksFound = new WiFiNetwork[storedNetworksFound.length]; + for (int i = 0; i < storedNetworksFound.length; ++i) + networksFound[i] = (WiFiNetwork) storedNetworksFound[i]; + onScanFinished(networksFound); + } + if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { + setActivatedPosition(savedInstanceState + .getInt(STATE_ACTIVATED_POSITION)); + } + } + registerForContextMenu(listview); + listview.setOnItemClickListener(this); + return root; + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + if (!(activity instanceof OnItemSelectionListener)) { + throw new IllegalStateException( + "Activity must implement fragment's callbacks."); + } + + mCallbacks = (OnItemSelectionListener) activity; + } + + @Override + public void onDetach() { + super.onDetach(); + mCallbacks = sDummyCallbacks; + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + if (networksFound != null) + outState.putParcelableArray(NETWORKS_FOUND, networksFound); + if (mActivatedPosition != ListView.INVALID_POSITION) { + outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); + } + } + + public void setActivateOnItemClick(boolean activateOnItemClick) { + listview.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE + : ListView.CHOICE_MODE_NONE); + } + + public void setActivatedPosition(int position) { + if (position == ListView.INVALID_POSITION) { + listview.setItemChecked(mActivatedPosition, false); + } else { + listview.setItemChecked(position, true); + } + + mActivatedPosition = position; + } + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, + ContextMenu.ContextMenuInfo menuInfo) { + super.onCreateContextMenu(menu, v, menuInfo); + final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; + if (networksFound == null || wifiListAdapter.getCount() <= info.position) + return; + final WiFiNetwork wiFiNetwork = wifiListAdapter.getItem(info.position).wifiNetwork; + if (wiFiNetwork == null) // the list is unstable and it can happen + return; + + MenuInflater inflater = getActivity().getMenuInflater(); + inflater.inflate(R.menu.networks_context_menu, menu); + // We are copying the values right away as the networks list is + // unstable. + menu.findItem(R.id.copy_ssid).setIntent(new Intent() + .putExtra(MENU_VALUE, wiFiNetwork.getSsidName())); + menu.findItem(R.id.copy_mac).setIntent(new Intent() + .putExtra(MENU_VALUE, wiFiNetwork.getMacAddress())); + menu.findItem(R.id.use_mac).setIntent(new Intent() + .putExtra(MENU_VALUE, wiFiNetwork.getMacAddress())); + } + + @Override + public boolean onContextItemSelected(MenuItem item) { + String value = item.getIntent().getStringExtra(MENU_VALUE); + switch (item.getItemId()) { + case R.id.copy_ssid: { + ClipboardManager clipboard = (ClipboardManager) getActivity() + .getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText(value); + Toast.makeText(getActivity(), + getString(R.string.msg_copied, value), Toast.LENGTH_SHORT) + .show(); + return true; + } + case R.id.copy_mac: { + ClipboardManager clipboard = (ClipboardManager) getActivity() + .getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText(value); + Toast.makeText(getActivity(), + getString(R.string.msg_copied, value), Toast.LENGTH_SHORT) + .show(); + return true; + } + case R.id.use_mac: + mCallbacks.onItemSelected(value); + return true; + } + return super.onContextItemSelected(item); + } + + public void setMessage(int message) { + noNetworksMessage.findViewById(R.id.loading_spinner).setVisibility( + View.GONE); + listview.setVisibility(View.GONE); + TextView messageView = (TextView) noNetworksMessage + .findViewById(R.id.message); + messageView.setVisibility(View.VISIBLE); + messageView.setText(message); + noNetworksMessage.setVisibility(View.VISIBLE); + } + + public void onScanFinished(WiFiNetwork[] networks) { + networksFound = networks; + if (getActivity() == null) + return; + if (networks.length > 0) { + noNetworksMessage.setVisibility(View.GONE); + wifiListAdapter.updateNetworks(networks); + listview.setVisibility(View.VISIBLE); + } else { + noNetworksMessage.findViewById(R.id.loading_spinner).setVisibility( + View.GONE); + listview.setVisibility(View.GONE); + listview.setVisibility(View.GONE); + TextView messageView = (TextView) noNetworksMessage + .findViewById(R.id.message); + messageView.setVisibility(View.VISIBLE); + messageView.setText(R.string.msg_nowifidetected); + noNetworksMessage.setVisibility(View.VISIBLE); + } + } + + public void onItemClick(AdapterView list, View view, int position, + long id) { + if (networksFound != null && wifiListAdapter.getCount() > position) { + final WiFiNetwork wifiNetwork = wifiListAdapter.getItem(position).wifiNetwork; + if (wifiNetwork != null) // the list is unstable and it can happen + mCallbacks.onItemSelected(wifiNetwork); + } + } + + public interface OnItemSelectionListener { + + void onItemSelected(WiFiNetwork id); + + void onItemSelected(String mac); + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/Preferences.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/Preferences.java index 0bc3a4a..fced3d4 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/Preferences.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/Preferences.java @@ -19,24 +19,6 @@ package org.exobel.routerkeygen.ui; -import it.gmariotti.changelibs.library.view.ChangeLogListView; - -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.UnknownHostException; - -import org.exobel.routerkeygen.AdsUtils; -import org.exobel.routerkeygen.DictionaryDownloadService; -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.UpdateCheckerService; -import org.exobel.routerkeygen.UpdateCheckerService.LastVersion; -import org.exobel.routerkeygen.utils.HashUtils; - import android.annotation.TargetApi; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; @@ -77,10 +59,31 @@ import com.ipaulpro.afilechooser.FileChooserActivity; import com.ipaulpro.afilechooser.utils.FileUtils; +import org.exobel.routerkeygen.AdsUtils; +import org.exobel.routerkeygen.DictionaryDownloadService; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.UpdateCheckerService; +import org.exobel.routerkeygen.UpdateCheckerService.LastVersion; +import org.exobel.routerkeygen.utils.HashUtils; +import org.exobel.routerkeygen.utils.InputStreamUtils; + +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.UnknownHostException; + +import it.gmariotti.changelibs.library.view.ChangeLogListView; + @SuppressWarnings("deprecation") public class Preferences extends SherlockPreferenceActivity { - /** The maximum supported dictionary version */ + /** + * The maximum supported dictionary version + */ public static final int MAX_DIC_VERSION = 4; public static final String dicLocalPref = "dictionaryPath"; @@ -94,11 +97,16 @@ public class Preferences extends SherlockPreferenceActivity { public final static String GOOGLE_PLAY_DOWNLOADER = "org.doublecheck.wifiscanner"; public static final String PUB_DOWNLOAD = "https://github.com/routerkeygen/thomsonDicGenerator/releases/download/v3/RouterKeygen_v3.dic"; + public static final String VERSION = "3.14.2"; private static final String PUB_DIC_CFV = "https://github.com/routerkeygen/thomsonDicGenerator/releases/download/v3/RKDictionary.cfv"; - - public static final String VERSION = "3.14.1"; - private static final String LAUNCH_DATE = "16/05/2015"; - + private static final String LAUNCH_DATE = "01/06/2015"; + private static final int DIALOG_ABOUT = 1001; + private static final int DIALOG_ASK_DOWNLOAD = 1002; + private static final int DIALOG_WAIT = 1003; + private static final int DIALOG_ERROR_TOO_ADVANCED = 1004; + private static final int DIALOG_ERROR = 1005; + private static final int DIALOG_UPDATE_NEEDED = 1006; + private static final int DIALOG_CHANGELOG = 1007; private LastVersion lastVersion; @TargetApi(Build.VERSION_CODES.HONEYCOMB) @@ -272,26 +280,26 @@ public boolean onPreferenceClick(Preference preference) { @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { - case 0: - if (resultCode == RESULT_OK) { - // The URI of the selected file - final Uri uri = data.getData(); - // Create a File from this Uri - File file = FileUtils.getFile(this, uri); - final SharedPreferences customSharedPreference = PreferenceManager - .getDefaultSharedPreferences(getApplicationContext()); - final SharedPreferences.Editor editor = customSharedPreference - .edit(); - editor.putString(dicLocalPref, file.getAbsolutePath()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) - editor.apply(); - else - new Thread(new Runnable() { - public void run() { - editor.commit(); - } - }).start(); - } + case 0: + if (resultCode == RESULT_OK) { + // The URI of the selected file + final Uri uri = data.getData(); + // Create a File from this Uri + File file = FileUtils.getFile(this, uri); + final SharedPreferences customSharedPreference = PreferenceManager + .getDefaultSharedPreferences(getApplicationContext()); + final SharedPreferences.Editor editor = customSharedPreference + .edit(); + editor.putString(dicLocalPref, file.getAbsolutePath()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) + editor.apply(); + else + new Thread(new Runnable() { + public void run() { + editor.commit(); + } + }).start(); + } } } @@ -310,10 +318,10 @@ private boolean isDictionaryServiceRunning() { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case android.R.id.home: - NavUtils.navigateUpTo(this, new Intent(this, - NetworksListActivity.class)); - return true; + case android.R.id.home: + NavUtils.navigateUpTo(this, new Intent(this, + NetworksListActivity.class)); + return true; } return super.onOptionsItemSelected(item); } @@ -333,132 +341,124 @@ public void onStop() { GoogleAnalytics.getInstance(this).reportActivityStop(this); } - private static final int DIALOG_ABOUT = 1001; - private static final int DIALOG_ASK_DOWNLOAD = 1002; - private static final int DIALOG_WAIT = 1003; - private static final int DIALOG_ERROR_TOO_ADVANCED = 1004; - private static final int DIALOG_ERROR = 1005; - private static final int DIALOG_UPDATE_NEEDED = 1006; - private static final int DIALOG_CHANGELOG = 1007; - protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder = new Builder(this); switch (id) { - case DIALOG_ABOUT: { - LayoutInflater inflater = (LayoutInflater) this - .getSystemService(LAYOUT_INFLATER_SERVICE); - View layout = inflater.inflate(R.layout.about_dialog, - (ViewGroup) findViewById(R.id.tabhost)); - TabHost tabs = (TabHost) layout.findViewById(R.id.tabhost); - tabs.setup(); - TabSpec tspec1 = tabs.newTabSpec("about"); - tspec1.setIndicator(getString(R.string.pref_about)); - - tspec1.setContent(R.id.text_about_scroll); - TextView text = ((TextView) layout.findViewById(R.id.text_about)); - text.setMovementMethod(LinkMovementMethod.getInstance()); - text.append(VERSION + "\n" + LAUNCH_DATE); - tabs.addTab(tspec1); - TabSpec tspec2 = tabs.newTabSpec("credits"); - tspec2.setIndicator(getString(R.string.dialog_about_credits)); - tspec2.setContent(R.id.about_credits_scroll); - ((TextView) layout.findViewById(R.id.about_credits)) - .setMovementMethod(LinkMovementMethod.getInstance()); - tabs.addTab(tspec2); - TabSpec tspec3 = tabs.newTabSpec("license"); - tspec3.setIndicator(getString(R.string.dialog_about_license)); - tspec3.setContent(R.id.about_license_scroll); - ((TextView) layout.findViewById(R.id.about_license)) - .setMovementMethod(LinkMovementMethod.getInstance()); - tabs.addTab(tspec3); - builder.setNeutralButton(R.string.bt_close, new OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - removeDialog(DIALOG_ABOUT); + case DIALOG_ABOUT: { + LayoutInflater inflater = (LayoutInflater) this + .getSystemService(LAYOUT_INFLATER_SERVICE); + View layout = inflater.inflate(R.layout.about_dialog, + (ViewGroup) findViewById(R.id.tabhost)); + TabHost tabs = (TabHost) layout.findViewById(R.id.tabhost); + tabs.setup(); + TabSpec tspec1 = tabs.newTabSpec("about"); + tspec1.setIndicator(getString(R.string.pref_about)); + + tspec1.setContent(R.id.text_about_scroll); + TextView text = ((TextView) layout.findViewById(R.id.text_about)); + text.setMovementMethod(LinkMovementMethod.getInstance()); + text.append(VERSION + "\n" + LAUNCH_DATE); + tabs.addTab(tspec1); + TabSpec tspec2 = tabs.newTabSpec("credits"); + tspec2.setIndicator(getString(R.string.dialog_about_credits)); + tspec2.setContent(R.id.about_credits_scroll); + ((TextView) layout.findViewById(R.id.about_credits)) + .setMovementMethod(LinkMovementMethod.getInstance()); + tabs.addTab(tspec2); + TabSpec tspec3 = tabs.newTabSpec("license"); + tspec3.setIndicator(getString(R.string.dialog_about_license)); + tspec3.setContent(R.id.about_license_scroll); + ((TextView) layout.findViewById(R.id.about_license)) + .setMovementMethod(LinkMovementMethod.getInstance()); + tabs.addTab(tspec3); + builder.setNeutralButton(R.string.bt_close, new OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + removeDialog(DIALOG_ABOUT); - } - }); - builder.setView(layout); - break; - } - case DIALOG_ASK_DOWNLOAD: { - DialogInterface.OnClickListener diOnClickListener = new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - // Check if we have the latest dictionary version. - try { - checkCurrentDictionary(); - } catch (Exception e) { - e.printStackTrace(); } - } - }; - - builder.setTitle(R.string.pref_download); - builder.setMessage(R.string.msg_dicislarge); - builder.setCancelable(false); - builder.setPositiveButton(android.R.string.yes, diOnClickListener); - builder.setNegativeButton(android.R.string.no, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - removeDialog(DIALOG_ASK_DOWNLOAD); + }); + builder.setView(layout); + break; + } + case DIALOG_ASK_DOWNLOAD: { + DialogInterface.OnClickListener diOnClickListener = new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + // Check if we have the latest dictionary version. + try { + checkCurrentDictionary(); + } catch (Exception e) { + e.printStackTrace(); } - }); - break; - } - case DIALOG_UPDATE_NEEDED: { - builder.setTitle(R.string.update_title) - .setMessage( - getString(R.string.update_message, - lastVersion.version)) - .setNegativeButton(R.string.bt_close, - new OnClickListener() { - - public void onClick(DialogInterface dialog, - int which) { - removeDialog(DIALOG_UPDATE_NEEDED); - } - }) - .setPositiveButton(R.string.bt_website, - new OnClickListener() { - - public void onClick(DialogInterface dialog, - int which) { - startActivity(new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse(lastVersion.url))); - } - }); - break; - } - case DIALOG_WAIT: { - ProgressDialog pbarDialog = new ProgressDialog(Preferences.this); - pbarDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); - pbarDialog.setMessage(getString(R.string.msg_wait)); - return pbarDialog; - } - case DIALOG_ERROR_TOO_ADVANCED: { - builder.setTitle(R.string.msg_error).setMessage( - R.string.msg_err_online_too_adv); - break; - } - case DIALOG_ERROR: { - builder.setTitle(R.string.msg_error).setMessage( - R.string.msg_err_unkown); - break; - } - case DIALOG_CHANGELOG: { - LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - ChangeLogListView chgList = (ChangeLogListView) layoutInflater - .inflate(R.layout.dialog_changelog, null); - builder.setTitle(R.string.pref_changelog) - .setView(chgList) - .setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - } - }); - break; - } + } + }; + + builder.setTitle(R.string.pref_download); + builder.setMessage(R.string.msg_dicislarge); + builder.setCancelable(false); + builder.setPositiveButton(android.R.string.yes, diOnClickListener); + builder.setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + removeDialog(DIALOG_ASK_DOWNLOAD); + } + }); + break; + } + case DIALOG_UPDATE_NEEDED: { + builder.setTitle(R.string.update_title) + .setMessage( + getString(R.string.update_message, + lastVersion.version)) + .setNegativeButton(R.string.bt_close, + new OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + removeDialog(DIALOG_UPDATE_NEEDED); + } + }) + .setPositiveButton(R.string.bt_website, + new OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + startActivity(new Intent(Intent.ACTION_VIEW) + .setData(Uri.parse(lastVersion.url))); + } + }); + break; + } + case DIALOG_WAIT: { + ProgressDialog pbarDialog = new ProgressDialog(Preferences.this); + pbarDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); + pbarDialog.setMessage(getString(R.string.msg_wait)); + return pbarDialog; + } + case DIALOG_ERROR_TOO_ADVANCED: { + builder.setTitle(R.string.msg_error).setMessage( + R.string.msg_err_online_too_adv); + break; + } + case DIALOG_ERROR: { + builder.setTitle(R.string.msg_error).setMessage( + R.string.msg_err_unkown); + break; + } + case DIALOG_CHANGELOG: { + LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); + ChangeLogListView chgList = (ChangeLogListView) layoutInflater + .inflate(R.layout.dialog_changelog, null); + builder.setTitle(R.string.pref_changelog) + .setView(chgList) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + }); + break; + } } return builder.create(); } @@ -474,17 +474,17 @@ private void checkCurrentDictionary() throws FileNotFoundException { DictionaryDownloadService.URL_DOWNLOAD, PUB_DOWNLOAD)); } else { AsyncTask task = new AsyncTask() { - protected void onPreExecute() { - removeDialog(DIALOG_ASK_DOWNLOAD); - showDialog(DIALOG_WAIT); - } - private final static int TOO_ADVANCED = 1; private final static int OK = 0; private final static int DOWNLOAD_NEEDED = -1; private final static int ERROR_NETWORK = -2; private final static int ERROR = -3; + protected void onPreExecute() { + removeDialog(DIALOG_ASK_DOWNLOAD); + showDialog(DIALOG_WAIT); + } + protected Integer doInBackground(Void... params) { // Comparing this version with the online @@ -496,15 +496,23 @@ protected Integer doInBackground(Void... params) { con.getInputStream()); byte[] cfvTable = new byte[18]; - dis.read(cfvTable); + boolean readCorrectly = InputStreamUtils.readFromInput( + cfvTable, cfvTable.length, dis); dis.close(); con.disconnect(); + if (!readCorrectly) { + return ERROR; + } InputStream is = new FileInputStream(myDicFile); byte[] dicVersion = new byte[2]; // Check our version - is.read(dicVersion); + readCorrectly = InputStreamUtils.readFromInput( + dicVersion, dicVersion.length, is); is.close(); + if (!readCorrectly) { + return ERROR; + } int thisVersion, onlineVersion; thisVersion = dicVersion[0] << 8 | dicVersion[1]; onlineVersion = cfvTable[0] << 8 | cfvTable[1]; @@ -513,8 +521,7 @@ protected Integer doInBackground(Void... params) { // It is the latest version, but is // it not corrupt? byte[] dicHash = new byte[16]; - for (int i = 2; i < 18; ++i) - dicHash[i - 2] = cfvTable[i]; + System.arraycopy(cfvTable, 2, dicHash, 0, dicHash.length); if (HashUtils.checkDicMD5( new File(myDicFile).getPath(), dicHash)) { // All is well @@ -523,7 +530,7 @@ protected Integer doInBackground(Void... params) { } if (onlineVersion > thisVersion && onlineVersion > MAX_DIC_VERSION) { - // Online version is too advancedv + // Online version is too advanced return TOO_ADVANCED; } return DOWNLOAD_NEEDED; @@ -545,30 +552,30 @@ protected void onPostExecute(Integer result) { return; } switch (result) { - case ERROR: - showDialog(DIALOG_ERROR); - break; - case ERROR_NETWORK: - Toast.makeText(Preferences.this, - R.string.msg_errthomson3g, Toast.LENGTH_SHORT) - .show(); - break; - case DOWNLOAD_NEEDED: - startService(new Intent(getApplicationContext(), - DictionaryDownloadService.class).putExtra( - DictionaryDownloadService.URL_DOWNLOAD, - PUB_DOWNLOAD)); - break; - case OK: - Toast.makeText( - getBaseContext(), - getResources().getString( - R.string.msg_dic_updated), - Toast.LENGTH_SHORT).show(); - break; - case TOO_ADVANCED: - showDialog(DIALOG_ERROR_TOO_ADVANCED); - break; + case ERROR: + showDialog(DIALOG_ERROR); + break; + case ERROR_NETWORK: + Toast.makeText(Preferences.this, + R.string.msg_errthomson3g, Toast.LENGTH_SHORT) + .show(); + break; + case DOWNLOAD_NEEDED: + startService(new Intent(getApplicationContext(), + DictionaryDownloadService.class).putExtra( + DictionaryDownloadService.URL_DOWNLOAD, + PUB_DOWNLOAD)); + break; + case OK: + Toast.makeText( + getBaseContext(), + getResources().getString( + R.string.msg_dic_updated), + Toast.LENGTH_SHORT).show(); + break; + case TOO_ADVANCED: + showDialog(DIALOG_ERROR_TOO_ADVANCED); + break; } } @@ -581,4 +588,4 @@ protected void onPostExecute(Integer result) { } } -}; +} diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/WifiListAdapter.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/WifiListAdapter.java index c1e1bae..f9a9592 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/WifiListAdapter.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/ui/WifiListAdapter.java @@ -18,12 +18,6 @@ */ package org.exobel.routerkeygen.ui; -import java.util.ArrayList; - -import org.exobel.routerkeygen.R; -import org.exobel.routerkeygen.algorithms.Keygen; -import org.exobel.routerkeygen.algorithms.WiFiNetwork; - import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; @@ -39,232 +33,237 @@ import com.hb.views.PinnedSectionListView; -public class WifiListAdapter extends BaseAdapter implements - PinnedSectionListView.PinnedSectionListAdapter { - private ArrayList listNetworks; +import org.exobel.routerkeygen.R; +import org.exobel.routerkeygen.algorithms.Keygen; +import org.exobel.routerkeygen.algorithms.WiFiNetwork; - final private LayoutInflater inflater; - private final Drawable[] wifiSignal; - private final Drawable[] wifiSignalLocked; - private Typeface typeface = null; +import java.util.ArrayList; + +public class WifiListAdapter extends BaseAdapter implements + PinnedSectionListView.PinnedSectionListAdapter { + final private LayoutInflater inflater; + private final Drawable[] wifiSignal; + private final Drawable[] wifiSignalLocked; + private ArrayList listNetworks; + private Typeface typeface = null; - @SuppressWarnings("deprecation") - public WifiListAdapter(Context context) { - this.listNetworks = new ArrayList(); - try { - typeface = Typeface.createFromAsset(context.getAssets(), - "fonts/Roboto-Light.ttf"); - } catch (Exception e) { - // Rarely some devices have a problem creating this typeface - } + @SuppressWarnings("deprecation") + public WifiListAdapter(Context context) { + this.listNetworks = new ArrayList(); + try { + typeface = Typeface.createFromAsset(context.getAssets(), + "fonts/Roboto-Light.ttf"); + } catch (Exception e) { + // Rarely some devices have a problem creating this typeface + } - final Resources resources = context.getResources(); - inflater = LayoutInflater.from(context); - wifiSignal = new Drawable[4]; - wifiSignalLocked = new Drawable[4]; - for (int i = 0; i < 4; ++i) { - switch (i) { - case 0: - wifiSignal[i] = resources - .getDrawable(R.drawable.ic_wifi_signal_1); - wifiSignalLocked[i] = resources - .getDrawable(R.drawable.ic_wifi_lock_signal_1); - break; - case 1: - wifiSignal[i] = resources - .getDrawable(R.drawable.ic_wifi_signal_2); - wifiSignalLocked[i] = resources - .getDrawable(R.drawable.ic_wifi_lock_signal_2); - break; - case 2: - wifiSignal[i] = resources - .getDrawable(R.drawable.ic_wifi_signal_3); - wifiSignalLocked[i] = resources - .getDrawable(R.drawable.ic_wifi_lock_signal_3); - break; - case 3: - wifiSignal[i] = resources - .getDrawable(R.drawable.ic_wifi_signal_4); - wifiSignalLocked[i] = resources - .getDrawable(R.drawable.ic_wifi_lock_signal_4); - break; - } - } - } + final Resources resources = context.getResources(); + inflater = LayoutInflater.from(context); + wifiSignal = new Drawable[4]; + wifiSignalLocked = new Drawable[4]; + for (int i = 0; i < 4; ++i) { + switch (i) { + case 0: + wifiSignal[i] = resources + .getDrawable(R.drawable.ic_wifi_signal_1); + wifiSignalLocked[i] = resources + .getDrawable(R.drawable.ic_wifi_lock_signal_1); + break; + case 1: + wifiSignal[i] = resources + .getDrawable(R.drawable.ic_wifi_signal_2); + wifiSignalLocked[i] = resources + .getDrawable(R.drawable.ic_wifi_lock_signal_2); + break; + case 2: + wifiSignal[i] = resources + .getDrawable(R.drawable.ic_wifi_signal_3); + wifiSignalLocked[i] = resources + .getDrawable(R.drawable.ic_wifi_lock_signal_3); + break; + case 3: + wifiSignal[i] = resources + .getDrawable(R.drawable.ic_wifi_signal_4); + wifiSignalLocked[i] = resources + .getDrawable(R.drawable.ic_wifi_lock_signal_4); + break; + } + } + } - public int getCount() { - return listNetworks.size(); - } + public int getCount() { + return listNetworks.size(); + } - public Item getItem(int position) { - return listNetworks.get(position); - } + public Item getItem(int position) { + return listNetworks.get(position); + } - @Override - public int getItemViewType(int position) { - if (position >= getCount()) - return -1; - return getItem(position).type; - } + @Override + public int getItemViewType(int position) { + if (position >= getCount()) + return -1; + return getItem(position).type; + } - @Override - public int getViewTypeCount() { - return 2; - } + @Override + public int getViewTypeCount() { + return 2; + } - @Override - public boolean areAllItemsEnabled() { - return false; - } + @Override + public boolean areAllItemsEnabled() { + return false; + } - @Override - public boolean isEnabled(int position) { - if (position >= getCount()) - return false; - return getItem(position).type == Item.ITEM; - } + @Override + public boolean isEnabled(int position) { + if (position >= getCount()) + return false; + return getItem(position).type == Item.ITEM; + } - public long getItemId(int position) { - return position; - } + public long getItemId(int position) { + return position; + } - private View getSectionView(ViewGroup parent) { - final TextView view = (TextView) inflater.inflate( - android.R.layout.simple_list_item_1, parent, false); - if (typeface != null) - view.setTypeface(typeface); - view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 23); - view.setTextColor(0xFFFFFFFF); - return view; - } + private View getSectionView(ViewGroup parent) { + final TextView view = (TextView) inflater.inflate( + android.R.layout.simple_list_item_1, parent, false); + if (typeface != null) + view.setTypeface(typeface); + view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 23); + view.setTextColor(0xFFFFFFFF); + return view; + } - private View getItemView(ViewGroup parent) { - final View convertView = inflater.inflate(R.layout.item_list_wifi, - parent, false); - final ViewHolder holder = new ViewHolder( - (TextView) convertView.findViewById(R.id.wifiName), - (TextView) convertView.findViewById(R.id.wifiMAC), - (ImageView) convertView.findViewById(R.id.strenght)); - if (typeface != null) - holder.ssid.setTypeface(typeface); - holder.ssid.setSelected(true); - holder.ssid.setEllipsize(TruncateAt.MARQUEE); - if (typeface != null) - holder.mac.setTypeface(typeface); - holder.mac.setSelected(true); - holder.mac.setEllipsize(TruncateAt.MARQUEE); - convertView.setTag(holder); - return convertView; - } + private View getItemView(ViewGroup parent) { + final View convertView = inflater.inflate(R.layout.item_list_wifi, + parent, false); + final ViewHolder holder = new ViewHolder( + (TextView) convertView.findViewById(R.id.wifiName), + (TextView) convertView.findViewById(R.id.wifiMAC), + (ImageView) convertView.findViewById(R.id.strenght)); + if (typeface != null) + holder.ssid.setTypeface(typeface); + holder.ssid.setSelected(true); + holder.ssid.setEllipsize(TruncateAt.MARQUEE); + if (typeface != null) + holder.mac.setTypeface(typeface); + holder.mac.setSelected(true); + holder.mac.setEllipsize(TruncateAt.MARQUEE); + convertView.setTag(holder); + return convertView; + } - public View getView(int position, View convertView, ViewGroup parent) { - final Item wifi = getItem(position); - if (convertView == null) { - if (wifi.type == Item.ITEM) { - convertView = getItemView(parent); - } else { - convertView = getSectionView(parent); - } - } else { - switch (wifi.type) { - case Item.ITEM: - if (convertView.getTag() == null) { - convertView = getItemView(parent); - } - break; - case Item.SECTION: - if (convertView.getTag() != null) { - convertView = getSectionView(parent); - } - break; - } - } + public View getView(int position, View convertView, ViewGroup parent) { + final Item wifi = getItem(position); + if (convertView == null) { + if (wifi.type == Item.ITEM) { + convertView = getItemView(parent); + } else { + convertView = getSectionView(parent); + } + } else { + switch (wifi.type) { + case Item.ITEM: + if (convertView.getTag() == null) { + convertView = getItemView(parent); + } + break; + case Item.SECTION: + if (convertView.getTag() != null) { + convertView = getSectionView(parent); + } + break; + } + } - if (wifi.type == Item.ITEM) { - final ViewHolder holder = (ViewHolder) convertView.getTag(); - holder.ssid.setText(wifi.wifiNetwork.getSsidName()); - holder.mac.setText(wifi.wifiNetwork.getMacAddress()); - final int strenght = wifi.wifiNetwork.getLevel(); - if (wifi.wifiNetwork.isLocked()) { - holder.networkStrenght - .setImageDrawable(wifiSignalLocked[strenght]); - } else { - holder.networkStrenght.setImageDrawable(wifiSignal[strenght]); - } - } else { - TextView view = (TextView) convertView; - view.setText(wifi.text); - view.setBackgroundColor(parent.getResources().getColor(wifi.color)); - } - return convertView; - } + if (wifi.type == Item.ITEM) { + final ViewHolder holder = (ViewHolder) convertView.getTag(); + holder.ssid.setText(wifi.wifiNetwork.getSsidName()); + holder.mac.setText(wifi.wifiNetwork.getMacAddress()); + final int strenght = wifi.wifiNetwork.getLevel(); + if (wifi.wifiNetwork.isLocked()) { + holder.networkStrenght + .setImageDrawable(wifiSignalLocked[strenght]); + } else { + holder.networkStrenght.setImageDrawable(wifiSignal[strenght]); + } + } else { + TextView view = (TextView) convertView; + view.setText(wifi.text); + view.setBackgroundColor(parent.getResources().getColor(wifi.color)); + } + return convertView; + } - private static class ViewHolder { - final private TextView ssid; - final private TextView mac; - final private ImageView networkStrenght; + @Override + public boolean hasStableIds() { + return true; + } - public ViewHolder(TextView ssid, TextView mac, ImageView networkStrenght) { - this.ssid = ssid; - this.mac = mac; - this.networkStrenght = networkStrenght; - } - } + public boolean isItemViewTypePinned(int viewType) { + return viewType == Item.SECTION; + } - @Override - public boolean hasStableIds() { - return true; - } + public void updateNetworks(WiFiNetwork[] list) { + if (list != null) { + listNetworks.clear(); + int currentSupportState = -1; + for (WiFiNetwork wifi : list) { + if (wifi.getSupportState() != currentSupportState) { + currentSupportState = wifi.getSupportState(); + switch (currentSupportState) { + case Keygen.SUPPORTED: + listNetworks.add(new Item(Item.SECTION, + R.string.networklist_supported, null, + R.color.holo_green_dark)); + break; + case Keygen.UNLIKELY_SUPPORTED: + listNetworks.add(new Item(Item.SECTION, + R.string.networklist_unlikely_supported, null, + R.color.holo_orange_dark)); + break; + case Keygen.UNSUPPORTED: + listNetworks.add(new Item(Item.SECTION, + R.string.networklist_unsupported, null, + R.color.holo_red_dark)); + break; + } + } + listNetworks.add(new Item(Item.ITEM, 0, wifi, 0)); + } + notifyDataSetChanged(); + } + } - public boolean isItemViewTypePinned(int viewType) { - return viewType == Item.SECTION; - } + private static class ViewHolder { + final private TextView ssid; + final private TextView mac; + final private ImageView networkStrenght; - public static class Item { - public static final int ITEM = 0; - public static final int SECTION = 1; + public ViewHolder(TextView ssid, TextView mac, ImageView networkStrenght) { + this.ssid = ssid; + this.mac = mac; + this.networkStrenght = networkStrenght; + } + } - public final int type; - public final int text; - public final WiFiNetwork wifiNetwork; - public final int color; + public static class Item { + public static final int ITEM = 0; + public static final int SECTION = 1; - public Item(int type, int text, WiFiNetwork wifiNetwork, int color) { - this.type = type; - this.text = text; - this.wifiNetwork = wifiNetwork; - this.color = color; - } - } + public final int type; + public final int text; + public final WiFiNetwork wifiNetwork; + public final int color; - public void updateNetworks(WiFiNetwork[] list) { - if (list != null) { - listNetworks.clear(); - int currentSupportState = -1; - for (WiFiNetwork wifi : list) { - if (wifi.getSupportState() != currentSupportState) { - currentSupportState = wifi.getSupportState(); - switch (currentSupportState) { - case Keygen.SUPPORTED: - listNetworks.add(new Item(Item.SECTION, - R.string.networklist_supported, null, - R.color.holo_green_dark)); - break; - case Keygen.UNLIKELY_SUPPORTED: - listNetworks.add(new Item(Item.SECTION, - R.string.networklist_unlikely_supported, null, - R.color.holo_orange_dark)); - break; - case Keygen.UNSUPPORTED: - listNetworks.add(new Item(Item.SECTION, - R.string.networklist_unsupported, null, - R.color.holo_red_dark)); - break; - } - } - listNetworks.add(new Item(Item.ITEM, 0, wifi, 0)); - } - notifyDataSetChanged(); - } - } + public Item(int type, int text, WiFiNetwork wifiNetwork, int color) { + this.type = type; + this.text = text; + this.wifiNetwork = wifiNetwork; + this.color = color; + } + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/HashUtils.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/HashUtils.java index 32981c0..d0caebe 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/HashUtils.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/HashUtils.java @@ -7,25 +7,27 @@ import java.util.Arrays; public class HashUtils { - private HashUtils(){} - // Check RouterKeygen.dic file through md5 - public static boolean checkDicMD5(String dicFile, final byte[] expected) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - InputStream is = new FileInputStream(dicFile); - try { - is = new DigestInputStream(is, md); - byte[] buffer = new byte[16384]; - while (is.read(buffer) != -1) - ; - } finally { - is.close(); - } - final byte[] hash = md.digest(); - return Arrays.equals(hash, expected); - } catch (Exception e) { - return false; - } + private HashUtils() { + } - } + // Check RouterKeygen.dic file through md5 + public static boolean checkDicMD5(String dicFile, final byte[] expected) { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + InputStream is = new FileInputStream(dicFile); + try { + is = new DigestInputStream(is, md); + byte[] buffer = new byte[16384]; + while (is.read(buffer) != -1) + ; + } finally { + is.close(); + } + final byte[] hash = md.digest(); + return Arrays.equals(hash, expected); + } catch (Exception e) { + return false; + } + + } } diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/InputStreamUtils.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/InputStreamUtils.java new file mode 100644 index 0000000..7eeee5b --- /dev/null +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/InputStreamUtils.java @@ -0,0 +1,36 @@ +package org.exobel.routerkeygen.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; + + +public class InputStreamUtils { + + public static boolean readFromInput(byte[] buf, int length, + InputStream input) throws IOException { + int check = 0; + while (check != length) { + int ret = input.read(buf, check, length - check); + if (ret == -1) { + return false; + } else + check += ret; + } + return true; + } + + + public static boolean readFromInput(byte[] buf, int length, + RandomAccessFile input) throws IOException { + int check = 0; + while (check != length) { + int ret = input.read(buf, check, length - check); + if (ret == -1) { + return false; + } else + check += ret; + } + return true; + } +} diff --git a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/StringUtils.java b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/StringUtils.java index 4599708..55e1dcc 100644 --- a/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/StringUtils.java +++ b/android/routerKeygen/src/main/java/org/exobel/routerkeygen/utils/StringUtils.java @@ -17,82 +17,93 @@ * along with Router Keygen. If not, see . */ package org.exobel.routerkeygen.utils; + import java.io.UnsupportedEncodingException; public class StringUtils { - - static public String dectoString( int mac){ - String ret = ""; - while ( mac > 0 ){ - switch (mac %10){ - case 0: ret = "Zero" + ret; - break; - case 1: ret = "One" + ret; - break; - case 2: ret = "Two" + ret; - break; - case 3: ret = "Three" + ret; - break; - case 4: ret = "Four" + ret; - break; - case 5: ret = "Five" + ret ; - break; - case 6: ret = "Six" + ret; - break; - case 7: ret = "Seven" + ret; - break; - case 8: ret = "Eight" + ret; - break; - case 9: ret = "Nine" + ret; - break; - } - mac /=10; - } - return ret; - } - - static final byte[] HEX_CHAR_TABLE = { - (byte)'0', (byte)'1', (byte)'2', (byte)'3', - (byte)'4', (byte)'5', (byte)'6', (byte)'7', - (byte)'8', (byte)'9', (byte)'a', (byte)'b', - (byte)'c', (byte)'d', (byte)'e', (byte)'f' - }; + static final byte[] HEX_CHAR_TABLE = { + (byte) '0', (byte) '1', (byte) '2', (byte) '3', + (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', + (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' + }; + + static public String dectoString(int mac) { + String ret = ""; + while (mac > 0) { + switch (mac % 10) { + case 0: + ret = "Zero" + ret; + break; + case 1: + ret = "One" + ret; + break; + case 2: + ret = "Two" + ret; + break; + case 3: + ret = "Three" + ret; + break; + case 4: + ret = "Four" + ret; + break; + case 5: + ret = "Five" + ret; + break; + case 6: + ret = "Six" + ret; + break; + case 7: + ret = "Seven" + ret; + break; + case 8: + ret = "Eight" + ret; + break; + case 9: + ret = "Nine" + ret; + break; + } + mac /= 10; + } + return ret; + } + + public static String getHexString(byte[] raw) + throws UnsupportedEncodingException { + byte[] hex = new byte[2 * raw.length]; + int index = 0; + + for (byte b : raw) { + int v = b & 0xFF; + hex[index++] = HEX_CHAR_TABLE[v >>> 4]; + hex[index++] = HEX_CHAR_TABLE[v & 0xF]; + } + return new String(hex, "ASCII"); + } + + public static String getHexString(short[] raw) + throws UnsupportedEncodingException { + byte[] hex = new byte[2 * raw.length]; + int index = 0; - public static String getHexString(byte[] raw) - throws UnsupportedEncodingException - { - byte[] hex = new byte[2 * raw.length]; - int index = 0; + for (short b : raw) { + int v = b & 0xFF; + hex[index++] = HEX_CHAR_TABLE[v >>> 4]; + hex[index++] = HEX_CHAR_TABLE[v & 0xF]; + } + return new String(hex, "ASCII"); + } - for (byte b : raw) { - int v = b & 0xFF; - hex[index++] = HEX_CHAR_TABLE[v >>> 4]; - hex[index++] = HEX_CHAR_TABLE[v & 0xF]; - } - return new String(hex, "ASCII"); - } - public static String getHexString(short[] raw) - throws UnsupportedEncodingException - { - byte[] hex = new byte[2 * raw.length]; - int index = 0; - - for (short b : raw) { - int v = b & 0xFF; - hex[index++] = HEX_CHAR_TABLE[v >>> 4]; - hex[index++] = HEX_CHAR_TABLE[v & 0xF]; - } - return new String(hex, "ASCII"); - } - public static String getHexString(short raw) { - byte[] hex = new byte[2]; - int v = raw & 0xFF; - hex[0] = HEX_CHAR_TABLE[v >>> 4]; - hex[1] = HEX_CHAR_TABLE[v & 0xF]; - try { - return new String(hex, "ASCII"); - } catch (UnsupportedEncodingException e) {} - return ""; - } + public static String getHexString(short raw) { + byte[] hex = new byte[2]; + int v = raw & 0xFF; + hex[0] = HEX_CHAR_TABLE[v >>> 4]; + hex[1] = HEX_CHAR_TABLE[v & 0xF]; + try { + return new String(hex, "ASCII"); + } catch (UnsupportedEncodingException e) { + } + return ""; + } } \ No newline at end of file diff --git a/android/routerKeygen/src/main/res/layout-v11/actionbar_indeterminate_progress.xml b/android/routerKeygen/src/main/res/layout-v11/actionbar_indeterminate_progress.xml index 7d11f18..359a9fa 100644 --- a/android/routerKeygen/src/main/res/layout-v11/actionbar_indeterminate_progress.xml +++ b/android/routerKeygen/src/main/res/layout-v11/actionbar_indeterminate_progress.xml @@ -17,7 +17,7 @@ + android:gravity="center"> + tools:context=".NetworksListActivity"> + android:showDividers="middle"> - + - diff --git a/android/routerKeygen/src/main/res/layout-v14/fragment_manual_input.xml b/android/routerKeygen/src/main/res/layout-v14/fragment_manual_input.xml index 4465cec..3fca759 100644 --- a/android/routerKeygen/src/main/res/layout-v14/fragment_manual_input.xml +++ b/android/routerKeygen/src/main/res/layout-v14/fragment_manual_input.xml @@ -1,5 +1,4 @@ - - + android:layout_height="match_parent"> + android:layout_height="match_parent"> + android:orientation="horizontal"> + android:orientation="horizontal">