- Как я потерял пароль от Android keystore, но потом смог восстановить с помощью Jetbrains Idea
- How to recover data of your Android KeyStore?
- 1. Check your log files
- 3. Do hack
- How to use the Android Keystore to store passwords and other sensitive information
- Preparation
- How to Recover Lost Keystore Password for Android Studio Projects?
- 1.a. Recover Keystore Password through Android Studio Logs
- 1.b. Recover Keystore Password through Gradle’s ‘taskArtifacts.bin’ File
- 2. Recover Keystore Password through a Password Generator Tool
- Steps to Recover Keystore Password using the smart wordlist attack
- Steps to Recover Keystore Password using the dictionary attack
- Steps to Recover Keystore Password using the brute force attack
- Using AdroidKeyStore for Secure User Password Storage
- Introduction
- The Problem
- Implementation
- interface PasswordStorageInterface
- Details of PasswordStorageHelper_SDK18_init() implementation
- PasswordStorageHelper_SDK18 — setData()
- PasswordStorageHelper_SDK18 — getData()
Как я потерял пароль от Android keystore, но потом смог восстановить с помощью Jetbrains Idea
Жило-было в Google Play Android приложение с несколькими тысячами пользователей. Через год понадобилось его обновить. Ок, запускаем Idea, выбираем «Build» — «Generate Signed APK». Вспоминаю что за это время успел пересесть в Linux, ничего страшного, выбираю файл с ключами, ввожу ранее заботливо записанный пароль… Не подходит. Хмм… Ввожу еще раз, еще… Перебор вариантов, переспрос коллег… Всё плохо.
В итоге потенциально три приложения зависли в Google play, ни один из вариантов не подходит. Вспоминаю, что Windows остался на dual-boot, перезагружаюсь туда, к счастью в этом экземпляре Idea остался сохраненный пароль.
Приложение успешно обновлено, но проблема с паролем осталась. Запрос в Jetbrains к сожалению не помог, поддержка ответила быстро, но ответ был в том духе что пароль восстановить не является возможным, дали ссылку на исходники и предложили сделать свой хак. Что в общем то логично.
Ну что же, надо думать. Так как Idea это обычное java-приложение, то возникла мысль подключить свой код к тому месту, где из хранилища считываются пароли. После прочтения топика про javaagent быстро набросал свой java agent который просто записывал в файл имена всех загружаемых классов. Все что нужно чтобы Idea запускалась с java agent, это прописать в файл idea.exe.vmoptions (или idea64.exe.vmoptions) строку вида
После запуска с агентом текстовый файл быстро наполнился строками вида
Затем жму на «Generate Signed APK» и смотрю на вывод в файле:
Кажется, все нужное нам лежит в exportSignedPackage
Небольшое гугление, и находим исходники 2012 г.
Здесь нас привлекает кусочек кода:
Здесь видно, что пароли вытаскивается из защищенного хранилища и сохраняются в JPasswordField (стандартный контрол Swing для ввода паролей).
Осталось всего ничего — вытащить данные из текстовых полей. В этом нам поможет Javassist — библиотека для манипулирования байт-кодом «на лету». Пишем в нашем java-agent следующий кусочек кода:
Что он делает? Перехватываем момент загрузки класса JPasswordField, находим в нем метод getPassword() и добавляем в конец метода наш фрагмент кода, который печатает в консоль искомый пароль ($_ это служебная переменная javassist, где лежит значение возвращаемое методом).
Таким нехитрым способом пароли были восстановлены и спасены.
P. S. А пароль оказался тем же самым, что и был записан, но вводился в русской раскладке. Всё было просто на самом деле…
Источник
How to recover data of your Android KeyStore?
These methods can save you by recovering Key Alias and Key Password and KeyStore Password.
You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases.
But it’s even worse when you have KeyStore file and you forget any credentials shown in above box.
But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways.
1. Check your log files
→ For windows users,
Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version)\system\log\idea.log.1 ( or any old log number)
Open your log file in Notepad++ or Any text editor, and search for:
and if you are lucky enough then you will start seeing these.
- Pandroid.injected.signing.store.file = This is file path where the keystore file was stored
2. Pandroid.injected.signing.store.password = This is K ey store password
3. Pandroid.injected.signing.key.alias = This is Key alias name
4. Pandroid.injected.signing.key.password = This is Key password
Launch the Console utility and scrolled down to
/Library/Logs -> AndroidStudioBeta(Version of your studio) ->idea.log.1 (or any old log number)
Search for android.injected.signing and you can get them.
2. In case you remember KeyStore password but not the Alias name
→ Launch command prompt(i.e CMD)
→ keytool -list -keystore [will show all available options]
→ Directly run keytool -list -v -keystore
path example —> «C:\\users\admin\docs\main.keystore»
It will ask for KeyStore password and then shows name of alias,
3. Do hack
→ Any time you upload any app to PlayStore, save your keystore file and credentials at any safe place
→ The remember password checkbox shown in image top of the page, will not gonna save it for life time, if you upgrade your studio, there are chances you will loose them.
→ At least, save your KeyStore Password, as in certain tricks it’s the most vital.
Источник
How to use the Android Keystore to store passwords and other sensitive information
Preparation
Before we begin coding, it is helpful to understand a bit about the Android Keystore, and it’s capabilities. The Keystore is not used directly for storing application secrets such as password, however, it provides a secure container, which can be used by apps to store their private keys, in a way that’s pretty difficult for malicious (unauthorised) users and apps to retrieve.
As its name suggests, an app can store multiple keys in the Keystore, but an app can only view, and query, its own keys. Ideally, with the keystore, an app would generate/or receive a private/public key pair, which would be stored in the keystore. The public key can then be used to encrypt application secrets, before being stored in the app specific folders, with the private key used to decrypt the same information when needed.
Although the Android Keystore provider was introduced in API level 18 (Android 4.3), the Keystore itself has been available since API 1, restricted to use by VPN and WiFi systems.
The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.
Источник
How to Recover Lost Keystore Password for Android Studio Projects?
Many times while creating a release build of an Android application, I have created a keystore and an alias only to realize two months later that I have forgotten the password. Fortunately, there are ways to recover lost keystore passwords for Android Studio projects (and potentially Eclipse projects too). These techniques fall into two categories:
- You have access to the machine (and the old logs) on which you created the keystore or used it at least once.
- You are trying to recover the keystore password on another machine.
1.a. Recover Keystore Password through Android Studio Logs
You can find the keystore password by accessing the idea.log files generated by Android Studio (yes, this is true – so much for security). On OSX, you can find the idea log files in
/Library/Logs/AndroidStudio2.0. You can also locate these by opening Android Studio-> Help->Show Log in Finder.
Open the idea.log file. Note: There may be multiple files named idea.log.1, idea.log.2 etc. Look through each of them till you find the password.
Search for “Pandroid.injected.signing.key.password” and you can see the key password.
The area of the logs where you can see your password is below:
You will be able to locate your password in place of the keyword in red above.
1.b. Recover Keystore Password through Gradle’s ‘taskArtifacts.bin’ File
NOTE: This method is less reliable and may only work with older versions of Gradle.
In your code (project folder), search for this file .gradle\2.4\taskArtifacts\taskArtifacts.bin
Note: replace 2.4 with the version of gradle that you are using.
Then look for storePassword OR signingConfig.storePassword OR password—signingConfig.keyAlias
2. Recover Keystore Password through a Password Generator Tool
You can also Brute Force your lost Android Keystore Password using this excellent tool – Android-keystore-password-recover. This gives you 3 options – a plain brute-force option, a dictionary-based attack and a smart wordlist attack. If you can even faintly remember the first few letters of the password, the smart wordlist attack is very effective and can get you your password in a couple of seconds. I recommend that you try the smart wordlist attack first then the dictionary based attack finally followed by the brute force attack. The difference between the dictionary attack and the smart wordlist attack is that the tool tries the password strings in the dictionary as they are, while in the smart wordlist the words are combined into combinations.
Steps to Recover Keystore Password using the smart wordlist attack
- Download the tool from here.
- Create a list of potential password match hints and save it in a file called hints.txt
- Run the tool using the following command line
Steps to Recover Keystore Password using the dictionary attack
-
- Download the tool from here.
- Create a list of exact password matches (i.e. your dictionary) and save it in a file called dictionary.txt
- Run the tool using the following command line
Steps to Recover Keystore Password using the brute force attack
-
- Download the tool from here.
- Run the tool using the following command line
That summarizes all the possible techniques to recover your lost Android keystore passwords. In case you know of any other ways that we might have missed, please let us know in the comments section below.
In case this article helped you recover your lost keystore password, a quick ‘Thank you’ in the comments section would be appreciated. Also, please help spread the word by sharing it using the buttons below or linking to us.
As an Android developer, you might also want to check out our free GCM Notifications Test Tool ; read Secret Android codes or then even check out good web hosting companies.
Источник
Using AdroidKeyStore for Secure User Password Storage
Protection of the sensitive date stored on the mobile devices is a hot topic. There are a huge number of apps that provide access to the corporate (confidential) data, banking and payment tools, social networks and many other web-services, where user authorization is required. That it why it is very important for mobile app developers to care about data protection and build solutions with access security and credential protection in mind. For these purposes, Keystone API 18 brought native support for cryptographic operations to Android. It added AndroidKeyStore provider, which allows to:
- Generate new private cryptographic key or a pair of keys
- Work with Keystore entries – receive the list of saved keys
- Sign/verify data
- Transfer responsibility for safety of Keystore access to operating system.
In this article, we will show how to use this technology in practice to build secure Android apps with user password encryption and also support earlier Android versions providing password protection by means of other technologies.
Introduction
For Keystore API 1 you need to manually create Keystore file and make sure that access to it is secure. Usually, for 90% of software, private directory is a safe enough place to store data. However, this is not the case for rooted devices, where said data can be easily accessed.
Additionally, Keystore can be protected with a password. However, while this solution does increase security, it is very inconvenient for the user, as it forces them to enter password each time they want to access Keystore. In any case, there is always the possibility that the password will be cracked and perpetrator will get your Keystore file.
As mentioned above, AndroidKeyStore provider was added in Keystore API 18. As a result, all the hard work on providing security now lies on the system itself. We no longer need to manually protect our storage with a password, the system will do it automatically based on the user’s LockScreen settings (whether it’s a PIN, graphical password, or a fingerprint). If device supports hardware key storage, than it will be used instead of a software one, eliminating the possibility that perpetrators will be able to obtain private keys. When using AndroidKeystore, each application only has access to the keys, used in the context of this application.
The Problem
We have a minSdkVersion 16 application that we need an authorization in order to run. We need to save credentials to automatically log in the next time an app has been launched. In order to do this in a secure way, we will encrypt the password with AndroidKeyStore before saving it in Shared Preferences.
However, since AndroidKeyStore provider was only added since API18, we need to make a separate implementation for password storage for different versions of Android OS.
In this example we will use asymmetric cryptographic algorithm called RSA, where we need to generate and use a pair of keys (a public and a private one). These keys work together: an open key to encrypt data and a private key to decrypt it.
RSA is well suited to encrypt small blocks of data, such as passwords and AES keys. However, when it comes to encrypting large amounts of data, this algorithm is a poor choice because of its performance, while something like AES, for example, is way faster.
Implementation
First, we create a PassowrdStorageHelper class that will provide High level API for working with specific data. Let’s define a specific interface that will implement this class.
interface PasswordStorageInterface
Init() – generates a pair of keys if they don’t exist yet. Keys will be available for further use in KeyStore via an alias specified during generation.
setData() – allows to encrypt data and save the results in SharedPreferences by using the public key from the KeyStore.
getData() – allows to get encrypted password from SharedPreferences by using the private key to decrypt data
remove() – removes decrypted password, saved in SharedPreferences.
In order for PasswordStorageHelper to distinguish between devices that support AndroidKeyStore and those that done, we need to create two classes that implement PasswordStorageInterface.
In the PasswordStorageHelper constructor, we need to create specific class object that implements algorithms for working with protected data depending on your current Android version:
Caution: on certain API 18+ devices an exception can occur when initializing PasswordStorageHelper_SDK18().
In this case, we will use the second implementation of the helper:
Thus, by using the Facade pattern we painlessly split different implementations for working with encrypted data using different versions of Android OS. At the same time, we don’t need to worry about how to correctly initialize helper object – everything happens automatically.
Details of PasswordStorageHelper_SDK18_init() implementation
First, we need to check whether private/public keys are already exist in order to avoid generating them a second time.
We should prepare AlgorithmParameterSpec, this is necessary for further KeyPairGenerator initiation.
Now we can start to actually generate keys:
Along with the software implementation, some devices are also support the hardware key storages. In order to confirm whether a device supports such a storage, we can use the KeyChain.isBoundKeyAlgorithm(Algorithm);
However, Android 6.0 saw a much more extended API for Keystore, which is why this method for checking whether there is a hardware key storage doesn’t work anymore. Now, in order to conduct a check, we need keys to already be in the storage. As a result, we use the following method:
PasswordStorageHelper_SDK18 — setData()
In this method, we need to encrypt passwords with the public key that is already located in the KeyStore, after which we need to save encrypted password in the SharedPreferences.
Encrypting data with a public key.
Saving the result
PasswordStorageHelper_SDK18 — getData()
We do everything similarly to setData(), only in a reverse order – get the encrypted password from SharedPreferences and decrypt it with a private key.
Decrypting data with a private key
In this example of the PasswordStorageHelper_SDK16 class implementation, initial password is simply encrypted with the Base64 and saved in SharedPreferences. This approach poses certain risks. Any app with root access will be able to access your saved password and use it for its own purposes. This is why, when confidentiality of credentials is extremely important, you need to find other ways to implement PasswordStorageHelper for Android versions that doesn’t support AndroidKeyStore provider.
You can also take a look at the source code, as well as test this application on your own device.
Источник