Android Security – Part II: Android KeyStore and cryptography operations

Android Security – Part I: Persisting user credentials

Previous posts in this series

We talked about the Android KeyStore system in brief in the last post. We will delve into more details about the KeyStore and how to use it for generating and storing keys from your application in this post.

To review: The keys that are generated using the KeyStore is not available outside of the Android Keystore. Your application only works with the references to these keys. The cryptographic operations are carried out by the Android Keystore.

To use the Android Keystore, you need to use the standard KeyStore APIs along with either the KeyPairGenerator or the KeyGenerator classes.

KeyGenerator provides the functionality of a secret (symmetric) key generator. A symmetric encryption key is a key that is used for both encryption and decryption of the data, by a symmetric encryption algorithm.  In most cases for Android applications, where you want to persist data in encrypted format, symmetric encryption is sufficient. 

For example, if you want to persist username and password of a user in the SharedPreferences, you can safely use symmetric keys. However, there could be situations where you need to use asymmetric keys for enhanced security. KeyPairGenerator provides the APIs to generate a private-public key pair.

Do remember that, asymmetric cryptography operations take longer time in comparison to symmetric cryptography operations.


Let’s first see how to use the KeyGenerator class, to generate a symmetric key, and use the key for encryption and decryption.

1. Initializing the keystore

private fun initializeKeystore(): KeyStore{
// There could be many keystore providers.
// We are interested in AndroidKeyStore
val ks = KeyStore.getInstance("AndroidKeyStore")
ks.load(null)
return ks
}

2. Generating a symmetric key

fun generateSymmetricKey(alias: String) {
// Specify the algorithm to be used
val generator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore"
)
// Configurations for the key
val generatorSpec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)

generator.init(generatorSpec.build())
// Generate the key
generator.generateKey()
}

3. Retrieving the generated key

// Retrieve the reference to the key by passing the same alias
// that was used while creating
fun getAsymmetricKey(alias: String): SecretKey {
return keystore.getKey(alias, CharArray(0)) as SecretKey
}

4. Cryptographic operations

Symmetric cryptography

4.1. Encryption

fun encryptDataAsymmetric(alias: String, data: String): String {
var key = getAsymmetricKey(alias)
var plainTextByteArray = data.toByteArray(Charset.defaultCharset())

var cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher.init(Cipher.ENCRYPT_MODE, key)
var cipherText = cipher.doFinal(plainTextByteArray)

// IV needs to be preserved which will be used during decryption
// Encode cipher text and the iv to Base64 format
// Concatenate both strings separated by a comma(,)
return Base64.getEncoder()
.encodeToString(cipherText) +
"," +
Base64.getEncoder().encodeToString(cipher.iv)
}

What’s an IV?

IV is “Initialization Vector”. It is an arbitrary string that is used with a secret key for data encryption. It can also be compared with nonce if you are familiar with this term. An IV is supposed to be used once. 

If the same IV is used for all encryptions, the result will always be the same for same inputs. For example, “TechDroid” will always be encrypted to the same cipher text if we do not provide an IV or even use the same IV for all encryptions. Providing a different IV each time, ensures that a hacker cannot employ dictionary attack to try and break the cipher by finding patterns.

In the above example, an IV is generated for you if you do not provide one. Thus, it is important that you preserve it along with the cipher text. Without the IV that was used during encryption, we will not be able to decrypt the cipher text later.

IV’s are not supposed to be private. It can be saved in plaintext or transmitted to other systems without any encryption. 

In this example, we are concatenating the cipher text and the generated IV, separated by a comma(,). While decrypting, we will separately use the cipher text and the IV.

4.2. Decryption

fun decryptDataAsymmetric(alias: String, data: String): String {
var key = getAsymmetricKey(alias)

// Extract the cipher text and the IV
var parts = data.split(",")

// Base64 decode of cipher text
var plainTextByteArray = Base64.getDecoder().decode(parts[0])

// Base64 decode of the IV
var iv = Base64.getDecoder().decode(parts[1])

var cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
var cipherText = cipher.doFinal(plainTextByteArray)

return cipherText.toString(Charset.defaultCharset())
}

You can find the source code on Github.

https://github.com/coomar2841/android-security

1 thought on “Android Security – Part II: Android KeyStore and cryptography operations

  1. Pingback: Android Security – Part I: Persisting user credentials – Techdroid

  2. BruceMype

    Your comment is awaiting moderation.

    Manage MongoDB databases with the help of this user-friendly and efficient application that offers a comprehensive set of advanced tools for the job

    Press the “Download Now” button to download Studio 3T for MongoDB Cracked Latest.
    The whole process will just take a few moments.

    Mirror Link —> Studio 3T for MongoDB crack new

    – Build: 2019.2.0
    – Developer: 3T Software Labs GmbH
    – Downloads: 244
    – Download type: safety (no torrent/no viruses)
    – Status file: clean (as of last analysis)
    – File size: na
    – Price: 0
    – Special requirements: no requirements
    – Home page: studio3t.com
    – User rating:

    Tags:
    Studio 3T for MongoDB Full Crack Latest
    Studio 3T for MongoDB activate code
    Studio 3T for MongoDB crack version
    Studio 3T for MongoDB Full Crack Latest
    Studio 3T for MongoDB crack and keygen free download

    Popular software:
    CopyTrans Shelbee activate code
    3D LUT Creator serial code
    Edraw Infographic Full Crack Latest
    DmitriRender and crack
    PrimoCache serial code
    Как обмануть антиплагиат бесплатно
    Hello world! – Die Klausler Fensterfabrik AG
    download google books
    Hello world! | CrossFit ARKIN

    Reply
  3. BruceMype

    Your comment is awaiting moderation.

    Press the “Download Now” button to download Cypheros TS-Doctor Crack Serial.
    The whole process will just take a few moments.

    Mirror Link —> Cypheros TS-Doctor crack only

    Scan, fix and convert a large number of video streams that pass through a receiver, regardless of the recorder format (TS, MTS or M2TS)

    · Build: 2.2.18
    · Company: Frank Siek
    · Downloads: 634
    · Download type: safety (no torrent/no viruses)
    · File status: clean (as of last analysis)
    · File size: na
    · Price: 0
    · Special requirements: no requirements
    · Rating:

    Keywords:
    cypheros ts-doctor crack fix, cypheros ts-doctor patch, cypheros ts-doctor crack latest, cypheros ts-doctor keygen free download, cypheros ts-doctor + full crack, cypheros ts-doctor full crack, cypheros ts-doctor crack for windows free download, cypheros ts-doctor keygen crack, cypheros ts-doctor cracked latest, cypheros ts-doctor keygen crack

    It may be interesting:
    PC SpeedCat crack keygen for windows
    Bitwar Data Recovery Cracked Latest
    XMind ZEN Cracked Latest
    Как пройти проверку антиплагиат
    C&I (Convenience & Impulse) Article – Jack & Co
    Download Desperados: Wanted Dead or Alive and crack
    download google books free
    download video from youtu.be
    Moving averages – the fast and the slow – Forexxerof
    ГДЗ – готовые домашние задания и решебники
    Software Cracks Keygens
    Repair missing or corrupt avgntopensslx.fmw.1.dll

    Reply
  4. BruceMype

    Your comment is awaiting moderation.

    Press the “Download Now” button to download vfxAlert serial number.
    The whole process will just take a few moments.

    Mirror Link —> vfxAlert crack files

    Obtain binary options signals and manage your desired trading broker platform using a built-in browser, with this powerful application

    · Version: 2.50 Build 5923
    · Company: Aleksandr Mikolyuk
    · Downloads: 1913
    · Download type: safety (no torrent/no viruses)
    · File status: clean (as of last analysis)
    · File size: na
    · Price: 0
    · Special requirements: no
    · Rating:

    Tags cloud:
    vfxalert full patched, vfxalert license code, vfxalert update crack, vfxalert serial key, vfxalert crack hack, vfxalert crack windows, vfxalert cracked latest, vfxalert serial key, vfxalert full crack latest, vfxalert crack only

    Other useful resources:
    PC SpeedCat crack serial number
    PRO100 license
    Kutools for Outlook crack install
    Как сделать текст уникальным
    Pos FTC Jequie Promove Palestra Gratuita | ACIJ – JEQUIE
    Download Battlestar Galactica Full Version Serial Keys Latest
    Convert Google books to PDF, PNG or JPG
    download video from xvideos
    Travis Darcy Out of the Box
    ГДЗ за 1-11 класс
    Windows Software Cracks
    How to repair missing or corrupt vegas130k.dll

    Reply
  5. BruceMype

    Your comment is awaiting moderation.

    Push the “Download Now” button to download BitRecover PST Converter Wizard Full Version Serial Keys Latest.
    The process will just take a few moments.

    Convert Microsoft Outlook PST files to an extensive range of formats and extract specific items easily, with this straightforward utility

    Mirror Link —> https://serial4download.com/crack/bitrecover-pst-converter-wizard-24003

    · Version: 10.0
    · Crack date: Nov 14th 2018
    · Company: BitRecover
    · Downloads: 5153
    · Download type: safety (no torrent/no viruses)
    · File status: clean (as of last analysis)
    · File size: na
    · Price: no cost
    · Special requirements: no
    · Systems: Win All
    · Rating:

    Tags:
    bitrecover pst converter wizard and crack, bitrecover pst converter wizard cracked full, bitrecover pst converter wizard and crack, bitrecover pst converter wizard + crack, bitrecover pst converter wizard cracked full, bitrecover pst converter wizard serial code, bitrecover pst converter wizard keygen serial, bitrecover pst converter wizard license, bitrecover pst converter wizard crack serial, bitrecover pst converter wizard full version with keys latest

    Popular software: this way

    Reply
  6. BruceMype

    Your comment is awaiting moderation.

    Click the “Download Now” button to download AB Bulk Mailer + Crack Latest.
    The whole process will just take a few seconds.

    Easy-to-learn app that sends emails in bulk mode, featuring numerous useful options, including a task scheduler and a contacts manager

    MIRROR LINK —> AB Bulk Mailer Cracked Latest

    · Release version: 9.8.1
    · Build date: Nov 12th 2018
    · Company: Advanced Business Objects
    · Downloads: 16805
    · Download type: safety (no torrent/no viruses)
    · Status: clean (as of last analysis)
    · File size: na
    · Price: no cost
    · Special requirements: no requirements
    · Systems: Windows 10 64 bit, Windows 10, Windows 8 64 bit, Windows 8, Windows 7 64 bit, Windows 7, Windows Vista 64 bit, Windows Vista, Windows XP, Windows 2K
    · Rating:

    Keywords:
    ab bulk mailer cracked latest, ab bulk mailer crack fix, ab bulk mailer full crack, ab bulk mailer keygen serial, ab bulk mailer keygen crack, ab bulk mailer serial number, ab bulk mailer serial number, ab bulk mailer activate code, ab bulk mailer crack install, ab bulk mailer crack keygen serial

    Popular software: https://crackserialnumber.com

    Reply
  7. BruceMype

    Your comment is awaiting moderation.

    Press the “Download Now” button to download NTLite crack only.
    It will just take a few seconds.

    Create a personalized and optimized Windows version by removing unnecessary components, such as languages, screensavers, MS Paint, drivers, services, Internet Explorer and .NET Framework

    Mirror —> NTLite Crack Latest Version

    · Release version: 1.8.0.7046 / 1.9.0.7046 Beta
    · Crack date: July 5 2019
    · Developer: Dino Nuhagic (nuhi)
    · Downloads: 2820
    · Download type: safety (no torrent/no viruses)
    · Status: clean (as of last analysis)
    · File size: small
    · Price: no cost
    · Special requirements: no requirements
    · Supported systems: Windows Server 2016, Windows 10 64 bit, Windows 10, Windows Server 2012, Windows 2008 R2, Windows 8 64 bit, Windows 8, Windows 7 64 bit, Windows 7
    · Rating:

    Keywords:
    ntlite serial keys x86/x64, ntlite cracked latest, ntlite crack windows, ntlite full crack, ntlite serial key, ntlite license code, ntlite crack and keygen free download, ntlite key crack, ntlite patch, ntlite cracked

    More software keygens: here

    More software:
    Hello world! – Alheezan.net
    Антиантиплагиат отзывы
    Rolling into the new year with HALO | Halo Trainer
    Download Conspiracies Cracked Latest
    Przygotowanie scian do malowania | Seo-Lokalnie
    Turn Off Windows Defender tool
    Скачать 10-Страйк: Схема Сети crack и keygen
    ГДЗ для школы
    Repair missing or corrupt teamviewer_resource.dll

    Reply
  8. BruceMype

    Your comment is awaiting moderation.

    Press the “Download Now” button to download LabelJoy + Crack Latest.
    The process will just take a few seconds.

    Create unique labels for your products, badges for an entire team, generate barcodes and more with the help of this easy to use application

    MIRROR —> https://coolwareznik.net/crack?n=66264&t=labeljoy

    · Release version: 6.19.08.12
    · Crack date: August 12 2019
    · Company: eDisplay srl
    · Downloads: 28375
    · Download type: safety (no torrent/no viruses)
    · Status: clean (as of last analysis)
    · File size: unknown
    · Price: no cost
    · Special requirements: no requirements
    · Supported systems: Win All
    · User rating:

    Tags:
    labeljoy crack patch, labeljoy cracked, labeljoy crack only, labeljoy key crack, labeljoy update crack, labeljoy cracked, labeljoy serial key, labeljoy crack, labeljoy full version serial keys latest, labeljoy keygen crack

    More software keygens: here

    More software:
    A Potted History of the Beautiful Game – Carmarthenrfc.co.uk
    Как сделать текст уникальным
    Hello world! | Joerg Heese
    Download Everlight of Magic & Power full crack
    What is a Dedicated or Static IP address? Know if you are using Static IP or Dynamic IP | 1072web WebHosting Blog
    Turn Off Windows Defender programm
    Скачать File & Folder Protector серийный ключ и кряк
    Repair missing or corrupt aclayers.dll
    Sk Favorit – FIG Slovenian v Challenge and Friendship tournament

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *