- Android Keystore: что это, для чего нужен, как создать ключ
- Кратко о Keystore
- Как пользоваться KeyStore
- Принципы создания сертификата
- Принципы создания ключа
- Android Keystore System
- In this document
- Blog articles
- Unifying Key Store Access in ICS
- Security Features
- Extraction Prevention
- Key Use Authorizations
- Choosing Between a Keychain or the Android Keystore Provider
- Using Android Keystore Provider
- Generating a New Private Key
- Generating a New Secret Key
- Working with Keystore Entries
- Listing Entries
- Signing and Verifying Data
- Requiring User Authentication For Key Use
- How to use the Android Keystore to store passwords and other sensitive information
- Preparation
- Securing Secret Key In Android Using Keystore
- ENCRYPTING DATA
- DECRYPTING DATA
- In HomeScreen.java
- CONCLUSION:
- Creating Keystores and Signing Android Apps
- Considerations
- Creating keystores
- Signing your APK
Android Keystore: что это, для чего нужен, как создать ключ
Конфиденциальность в приложении – пункт №1, которому разработчик должен уделить особое внимание. Самый распространенный способ защиты информации – шифрование данных. К нему относятся криптографические символы, симметрия и асимметрия шифра, сертификаты. Keystore – основной ресурс, где можно создать ключ безопасности. Об этом и поговорим ниже.
Кратко о Keystore
Keystore – это хранилище секретной информации, которое применяется Java-прогами с целью зашифровать данные, аутентифицировать и установить HTTPS соединение. Например, для аутентификации пользователя и сервера, между которыми установлен SSL, требуется ключ приватности и сертификат.
Для односторонней аутентификации кейстор применяется только на серверной части. При двусторонней происходит сертификатный обмен (т.е. у обоих сторон есть ключ приватности). Иными словами, кейстор необходим для того, чтобы быстро идентифицировать обладателя ключа.
Java «распознает» такие способы хранения данных в кейстор:
- Jks. Это тип хранения по умолчанию, применяется чаще всего;
- Jceks. Альтернатива предыдущему типу, на основе которой внедряется усложненное шифрование данных (на базе Triple DES). Если изначально применялся jks, хранилище можно обновить на jceks с помощью кейтула;
- Pkcs12. Это тип хранения, используемый при необходимости транспортировки закрытых ключей.
Записи в кейсторе именуются уникальными подписями. В стандартной версии Keystore ключи защищены паролем. Более того, целое хранилище можно защищать паролем. Доверенные сертификаты для ПО Android распределяются в директории Jre-Lib-Security-Cacerts (запароленные под «changeit»).
Как пользоваться KeyStore
Данные в хранилище делятся на 2 группы: ключевые записи (private и public) и доверенные сертификаты. Ключевые записи используются для криптографического шифрования, содержат идентифицированную информацию о клиенте. Доверенные сертификаты не используются тогда, когда требуется key закрытого типа.
Для отделения ключевых записей от сертификатов используются разные хранилища: для персональных ключей и доверенных (включая СЦА). Таким образом, обеспечивается повышенная защита данных.
Принципы создания сертификата
Используйте команду «-genkey» и укажите период действия сертификата («-validity»). Далее создается пара RSA-ключей, действие которых будет длиться 12 месяцев с момента реализации. Закрытые ключи защищаются в хранилище паролем, а открытые «конвертируются» в самодподписывающийся» сертификат.
Если вы не обнаружили искомый ключ в хранилище, его можно создать с помощью кейтула. При использовании данного инструмента система запросит ввести пароль от хранилища и закрытого ключа. Формат создаваемого сертификата – Х.509. Параметры указывайте в виде командной опции. Задавайте информацию о компании, способе размещения в хранилище, сроке действия сертификата.
Принципы создания ключа
Чтобы создать ключ, используйте команду «-genkeypair». Она автоматически клонирует ключ под названием «keypair» и перемещает элементы в хранилище. Открытые ключи «охватываются» форматом Х.509 – т.е. самоподписным сертификатом. Чтобы увидеть список ключей и сертификатов, хранимых в кейсторе, введите команду «-list», после чего укажите путь к информации.
Источник
Android Keystore System
In this document
Blog articles
Unifying Key Store Access in ICS
The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Once keys are in the keystore, they can be used for cryptographic operations with the key material remaining non-exportable. Moreover, it offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes. See Security Features section for more information.
The Keystore system is used by the KeyChain API as well as the Android Keystore provider feature that was introduced in Android 4.3 (API level 18). This document goes over when and how to use the Android Keystore provider.
Security Features
Extraction Prevention
Key Use Authorizations
Supported key use authorizations fall into the following categories:
- cryptography: authorized key algorithm, operations or purposes (encrypt, decrypt, sign, verify), padding schemes, block modes, digests with which the key can be used;
- temporal validity interval: interval of time during which the key is authorized for use;
- user authentication: the key can only be used if the user has been authenticated recently enough. See Requiring User Authentication For Key Use.
As an additional security measure, for keys whose key material is inside secure hardware (see KeyInfo.isInsideSecurityHardware() ) some key use authorizations may be enforced by secure hardware, depending on the Android device. Cryptographic and user authentication authorizations are likely to be enforced by secure hardware. Temporal validity interval authorizations are unlikely to be enforced by the secure hardware because it normally does not have an independent secure real-time clock.
Whether a key’s user authentication authorization is enforced by the secure hardware can be queried using KeyInfo.isUserAuthenticationRequirementEnforcedBySecureHardware() .
Choosing Between a Keychain or the Android Keystore Provider
Use the KeyChain API when you want system-wide credentials. When an app requests the use of any credential through the KeyChain API, users get to choose, through a system-provided UI, which of the installed credentials an app can access. This allows several apps to use the same set of credentials with user consent.
Use the Android Keystore provider to let an individual app store its own credentials that only the app itself can access. This provides a way for apps to manage credentials that are usable only by itself while providing the same security benefits that the KeyChain API provides for system-wide credentials. This method requires no user interaction to select the credentials.
Using Android Keystore Provider
To use this feature, you use the standard KeyStore and KeyPairGenerator or KeyGenerator classes along with the AndroidKeyStore provider introduced in Android 4.3 (API level 18).
AndroidKeyStore is registered as a KeyStore type for use with the KeyStore.getInstance(type) method and as a provider for use with the KeyPairGenerator.getInstance(algorithm, provider) and KeyGenerator.getInstance(algorithm, provider) methods.
Generating a New Private Key
Generating a new PrivateKey requires that you also specify the initial X.509 attributes that the self-signed certificate will have. You can replace the certificate at a later time with a certificate signed by a Certificate Authority.
Generating a New Secret Key
Working with Keystore Entries
Using the AndroidKeyStore provider takes place through all the standard KeyStore APIs.
Listing Entries
List entries in the keystore by calling the aliases() method:
Signing and Verifying Data
Sign data by fetching the KeyStore.Entry from the keystore and using the Signature APIs, such as sign() :
Similarly, verify data with the verify(byte[]) method:
Requiring User Authentication For Key Use
When generating or importing a key into the AndroidKeyStore you can specify that the key is only authorized to be used if the user has been authenticated. The user is authenticated using a subset of their secure lock screen credentials (pattern/PIN/password, fingerprint).
This is an advanced security feature which is generally useful only if your requirements are that a compromise of your application process after key generation/import (but not before or during) cannot bypass the requirement for the user to be authenticated to use the key.
Источник
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.
Источник
Securing Secret Key In Android Using Keystore
At some point in time, we all wanted to keep our data secure from being hacked/reverse engineered. The basic security mechanisms like,
a. ProGuard, ShrinkResources & minifyEnabled
b. Hiding in Manifest
c. Hiding in Build.Gradle
d. Storing in MySQL DB/Room DB/SharedPreference
e. Hiding in Strings.xml.
All these methods fail to provide maximum security. The most common and known logic of securing the key can be bypassed either by reversing and taking it from dex->jar file or by rooting the device and accessing the device storage.
But, there is one more method that beats them all. The mechanism which is generally used by applications for storing very sensitive data like Credit Card details, Bank Account and such.
Keystore is bound to hardware security which is generally used to store cryptographic keys. It becomes incredibly difficult for hackers to get access to it since a Keystore is very specific to every application. More of introduction done let us jump to the code now —
Declare few variables in Cryptor.java
private static final String TRANSFORMATION = “AES/GCM/NoPadding”;
private static final String ANDROID_KEY_STORE = “AndroidKeyStore”;
private byte[] iv;
private KeyStore keyStore;
private static final String SAMPLE_ALIAS = “MYALIAS”;
a. TRANSFORMATION is used for setting the algorithm which will be used for encoding.
b. iv is known as Initialization Vector which is an arbitrary number used along with a secret key for encryption. (It can be stored in public storage like SharedPreference, Room DB or MySQL DB).
c. SAMPLE_ALIAS is used to access the entity stored inside the Keystore.
ENCRYPTING DATA
For encrypting a value with the Keystore, we can do it by,
a. Create an object of the Cryptor class.
b. Use a setIv method to init the cipher using a secret key in Cryptor class.
c. Encrypt the text using an encryption function defined in Cryptor class.
d. Store the Iv and encrypted text (The Iv can be made public and it does not cause any issue) in SharedPreference or Room Database.
In Cryptor.java, we define the following functions
2. getSecretKey_en() method :
3. encryptText(String string_to_encrypt) :
4. encryptData(String text_to_encrypt) :
Explanation: We generate a secret key using the keyStore with specific algorithms and the ALIAS. the secret key which is generated is used to init the cipher and get the IV. The encrypt text function uses the text and the iv to encrypt the text in the Keystore and gives the encrypted text which can be stored in any general storage medium.
DECRYPTING DATA
For decrypting a value with the Keystore, we can do it by,
a. Create an object of the Cryptor class.
b. Initialize the KeyStore instance.
c. Use the decrypt function by passing the encrypted text and the iv (stored in SharedPreference or Room Database).
In HomeScreen.java
In Cryptor.java, add the following functions
2. decryptText(String encrypted_string, String iv) :
3. decryptData(String encrypted_string, byte[] Iv) :
Explanation: While decrypting, we get the stored Iv and encrypted text stored in our one of the storage medium. We initialize the Keystore using the ANDROID_KEY_STORE and decrypt the text using the Iv and by the init and doFinal method of the Cipher.
CONCLUSION:
So, with the above implementation, secrets are now safe in the KeyStore. Why it is probably the best method is because KeyStore is very specific to the application. It cannot be retrieved and hence the text cannot be decrypted without it. Many applications which stores the Credit Card and other sensitive data of the users use this encryption method to keep it safe.
For the entire code, you can look into my GitHub repository.
Источник
Creating Keystores and Signing Android Apps
The SK Engineering Team
As a security measure, Android requires that apps be signed in order to be installed. Signing an app first requires creating keystores. A keystore is a storage mechanism for security certificates. A public key certificate is used to sign an APK before deployment to services like the Google Play Store. Signing the APK in this fashion allows Google to provide a high level of certainty that future updates to your APK of the same app come from you and not some malicious third party.
Considerations
There are some things you will need to consider before first deploying your Android app. Primary among these is the expected lifespan of your app. You will not be able to deploy the same app signed by another key at any point in the near future. Android, as well as Google Play, enforces the use of the same key for updates to an APK. If you need to sign your app with another key for any reason, you will have to deploy the app with a new package name. Any ratings your app had on Google Play will be lost. You will also lose touch with your user base unless you have notified them in some way to expect the existing app to be obsolete.
Creating keystores
After you have decided on an app’s lifespan, you’ll want to generate your keystore. Java includes a tool for just this purpose: keytool . keytool is located in your Java JDK installation and should be on your path for the purposes of this article. keytool will quickly generate a public/private key pair and store them in a keystore for you after you answer a few simple questions.
keytool has a number of commands. The most common command used for signing Android builds -genkeypair , commonly abbreviated -genkey . The other commands may be useful to you, but uncommonly so. Again, there are lots of options for this keytool command. The primary -genkey options we are concerned with are in the table below with a brief description:
-keystore | Filename of the generated keystore |
-alias | Keypair alias name |
-keyalg | Algorithm used to generate keypair |
-keysize | Keypair size, in bits |
-validity | Keypair validity duration, in days |
In other words, running the command
keytool -genkey -v -keystore release.keystore -alias example -keyalg RSA -keysize 2048 -validity 10000
would result in a keystore file called release.keystore which contained an RSA-2048 public/private keypair by the alias name of example and validity of 10,000 days (more than 27 years).
Before running this command, you’ll want to decide on strong passwords for the keystore and key. You’ll need both of these passwords to sign an APK — they can be the same password if you’re into that kind of thing. The tool will also collect some metadata like your name and organization, but all of that is optional.
Signing your APK
After running the command you’ll be the proud owner of a brand new Java Keystore. You probably want to set up your project to use the keystore to sign your APK, so let’s have a look at that.
If you’re using gradle to build your Android project, you will create a android.signingConfig and associate it with one or more android.buildTypes . The two passwords, keystore name, and alias name will all be needed in order to sign an APK. You can handle this in at least a few different ways. The simplest is to enter the relevant information directly into your gradle build script:
If you want to control access to the passwords you can move the information out of the build.gradle file and put it in your local environment or in a properties file to load at build time. To maintain security and control of the information, it’s likely that you would not want to check the keystore properties file into your source control.
Here is an example [from Google] of how to load the information from a file that would be located in your app’s root directory with the project level build.gradle file:
keystore.properties would contain (in this example):
If you prefer the environment variable method, create a script to add the variables to your environment and try something like this:
There are some trade-offs to both of these methods. Figure out what works best for your organization’s methodology and use that one. For the environment variable method, for example, you have to load these variables into your environment somehow. This is less than ideal if you want to generate a signed APK with Android Studio.
If you prefer to sign your APK manually instead of as part of the build process, you’ll want to use apksigner , located at
You’ll want to zipalign your APK, zipalign will ensure that your app’s uncompressed data starts at a predictable offset inside the APK. zipalign ed APKs are required to publish to the Google Play store.
After your APK is zipalign ed, sign it using apksigner :
You will be prompted at the command line to enter the password for your keystore.
If your keystore and key passwords differ, you’re in for a treat! Using the command above, you will be asked for the keystore password, but will not be asked for the key password. Entering either password results in exceptions and you won’t be having a good time. You’ll need to tell apksigner that you want to specify each password individually. Apparently, this is supposed to be the default behavior, but it hasn’t worked for me. To force apksigner to ask you for the keystore and key password independently, use the —ks-pass and —key-pass options. Following each option with stdin will tell apksigner to capture the password from you at the command line.
I hope this has educated you a bit more about how creating keystores and signing an Android APK works.
Источник