<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hayk Mkrtchyan on Medium]]></title>
        <description><![CDATA[Stories by Hayk Mkrtchyan on Medium]]></description>
        <link>https://medium.com/@hayk.mkrtchyan8998?source=rss-ed52c436296------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4gZ9qrCoFaTGIIvQIsgxLA.jpeg</url>
            <title>Stories by Hayk Mkrtchyan on Medium</title>
            <link>https://medium.com/@hayk.mkrtchyan8998?source=rss-ed52c436296------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:11:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hayk.mkrtchyan8998/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Shedding light on Android Encryption. Android Crypto API Part 3 — Android Keystore]]></title>
            <link>https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-3-android-keystore-0054fb386a98?source=rss-ed52c436296------2</link>
            <guid isPermaLink="false">https://medium.com/p/0054fb386a98</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hayk Mkrtchyan]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 06:26:28 GMT</pubDate>
            <atom:updated>2025-11-28T07:48:04.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>Android data encryption and decryption</h4><h3>Shedding light on Android Encryption. Android Crypto API Part 3 — Android Keystore</h3><h4>Hey folks. If you are reading this article, you may be having trouble figuring out how to encrypt data in your Android application to store it securely or send it to a server. Or maybe you just want to learn something new, and I am delighted to help you with that. Welcome to the last part of the Android Crypto API :)</h4><figure><img alt="Android Crypto API article poster which includes all the terminology that confuses developers, like Cipher, MessageDigest, TEE, Algorithms, Block Mode and Paddings, Android KeyStore, KeyGenerator, etc." src="https://cdn-images-1.medium.com/max/1024/1*_1RutprNNiZjTK36QBv7Tg.png" /><figcaption>Android Cryptography</figcaption></figure><p>This article consists of 3 parts:</p><ul><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2">Part 1 — Introduction</a></li><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d">Part 2 — Cipher</a></li><li>Part 3 — Android Keystore (You are here)</li></ul><p>Welcome to the last part of our <strong>Android Crypto API</strong>. Please make sure to take a look at the previous parts for a better understanding. The ones who did, great job! Now let’s finish what we have started once and for all.</p><blockquote><strong>- </strong><a href="#939a"><strong>Android Keystore and TEE</strong></a><strong><br>- </strong><a href="#4cd3"><strong>Revealing Android Keystore — Initialization</strong></a><strong><br>- </strong><a href="#d953"><strong>Generating Secure Keys with KeyGenerator</strong></a><strong><br>- </strong><a href="#9046"><strong>Encrypting our data</strong></a><strong><br>- </strong><a href="#44a3"><strong>Additional Info</strong></a><strong><br>- </strong><a href="#1cf5"><strong>Further resources and gists</strong></a><strong><br>- </strong><a href="#ba26"><strong>Conclusion</strong></a></blockquote><h3>Android Keystore and TEE</h3><p>Previously, we used SecretKeySpec to generate our key. We created a <strong>key material</strong>, which is an array of bytes, and passed it to SecretKeySpec which constructs a key from it.</p><blockquote>But is it that secure?</blockquote><p>Let’s remember what issues we have encountered in the previous part. First of all — <strong>key material length</strong>. We should always give a precise key length (16/24/32). Otherwise, our app crashes with the message <strong>InvalidKeyException: Unsupported key size. </strong>Second is that we are the ones who generate the key material. Let’s be honest, it’s not that secure, and if someone obtains that key material, they can create the same key.</p><p>Even though we perform <strong>key wrapping</strong> and generate random key material for the second key, we still need to handle our first key. Besides, the key generally lives in a non-secure environment, i.e., Android OS, and there’s a chance that the OS or our app can be compromised. As you see, this approach is not that much secure.</p><p>Here comes the <a href="https://developer.android.com/privacy-and-security/keystore"><strong>Android Keystore</strong></a> system that offers secure storage for our keys. It operates within a <a href="https://source.android.com/docs/security/features/trusty"><strong>Trusted Execution Environment</strong></a> (<em>TEE</em>) provided by Trusty OS. It is in an isolated environment within the device’s processor or chipset (<a href="https://en.wikipedia.org/wiki/System_on_a_chip"><strong>SoC</strong></a>), i.e. <em>decoupled from the device’s operating system</em>.</p><figure><img alt="An overview of Trusty TEE diagram. It emphasizes non-secure and secure environment communication through a secret channel." src="https://cdn-images-1.medium.com/max/1024/1*LCxwWtujvFw__IHwXH153w.jpeg" /><figcaption>Trusty TEE overview diagram</figcaption></figure><blockquote>Thus it protects our keys and key material against extraction and unauthorized access. Key material never enters the application process. Even if an attacker manages to access our keys, they won’t be able to extract their key material.</blockquote><figure><img alt="An overview of Android Keymaster module. It shows how we access to keymaster using a hardware abstraction layer. Keymaster is the one who manages our key inside a safe environment." src="https://cdn-images-1.medium.com/max/1024/1*UMfxz0uZWTWXxHST_64W0Q.png" /><figcaption>Access to Keymaster through Keymaster HAL</figcaption></figure><p>We won’t dive deep into the above diagram, but just you know — this <strong>keymaster</strong> module is intended to keep our cryptographic keys safe. It runs in a TEE, which is completely separate from the Android OS. The <strong>Keymaster TA</strong> (trusted application), which is also called <strong>Hardware-backed Keystore</strong>, provides all the secure Keystore operations and has our key material. To protect the key material, the keys are encrypted with a <strong>hardware-derived key</strong> inside TEE. It doesn’t expose key materials outside the trusted environment. Instead, it just exposes so-called <em>key “blobs”</em>, i.e., wrapped (encrypted) keys. Wrapping, unwrapping, and all that stuff is done inside the Keymaster TA.</p><h3>Revealing Android Keystore — Initialization</h3><p>The encryption and decryption part is generally the same as in our previous code. The difference is in how we generate the key. This time, let’s make it a little cleaner and create an interface for encryption/decryption.</p><pre>interface CipherManager {<br>    @Throws(Exception::class)<br>    fun encrypt(inputText: String): String<br><br>    @Throws(Exception::class)<br>    fun decrypt(data: String): String<br>}</pre><blockquote>Again, consider working directly with ByteArrays.</blockquote><p>Let’s create the implementation class and define some constants.</p><pre>class CipherManagerImpl : CipherManager {<br><br>    @Throws(Exception::class)<br>    override fun encrypt(inputText: String): String {<br>        TODO(&quot;Not yet implemented&quot;)<br>    }<br><br>    @Throws(Exception::class)<br>    override fun decrypt(data: String): String {<br>        TODO(&quot;Not yet implemented&quot;)<br>    }<br><br>    companion object {<br>        private const val ANDROID_KEY_STORE = &quot;AndroidKeyStore&quot;<br>        private const val AES_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES<br>        private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC<br>        private const val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7<br>        private const val TRANSFORMATION = &quot;$AES_ALGORITHM/$BLOCK_MODE/$PADDING&quot;<br>    }<br>}</pre><p>Using this approach you can have other implementations too. In the constants sections everything is like before despite <strong><em>ANDROID_KEY_STORE</em></strong>, which is the provider name we pass to get our Keystore instance.</p><pre>private val keyStore = KeyStore.getInstance(ANDROID_KEY_STORE).apply {<br>    load(null) // With load function we initialize our keystore<br>}</pre><h3>Generating Secure Keys with KeyGenerator</h3><blockquote><a href="https://developer.android.com/reference/javax/crypto/KeyGenerator"><strong>KeyGenerator</strong></a> is a class, well it’s obvious that it’s a class for generating cryptographic keys. However, it’s used for symmetric key generation. To generate asymmetric keys you should take a look at <a href="https://developer.android.com/reference/java/security/KeyPairGenerator"><strong>KeyPairGenerator</strong></a> which generates a pair of public and private keys.</blockquote><pre>private val keyAlias = &quot;aes_key_alias&quot; // TODO - Should be secure<br><br>@Throws(Exception::class)<br>private fun createKey(): SecretKey {<br>    @Throws(Exception::class)<br>    private fun createKey(): SecretKey {<br>        val keyGenParameterSpec = KeyGenParameterSpec.Builder(<br>            keyAlias,<br>            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT<br>        )<br>            .setBlockModes(BLOCK_MODE)<br>            .setEncryptionPaddings(PADDING)<br>            .setUserAuthenticationRequired(false)<br>            .setRandomizedEncryptionRequired(true)<br>            .build()<br><br>        return KeyGenerator.getInstance(AES_ALGORITHM).apply {<br>            init(keyGenParameterSpec)<br>        }.generateKey()<br>    }<br>}</pre><p>Before creating our KeyGenerator we create a KeyGenParameterSpec. In simpler words, it’s a class using which we customize the key generation by passing different parameters to it. Let’s analyze it line by line.</p><blockquote>You can use it for both KeyGenerator and KeyPairGenerator, but only since API 23+. Before that, for KeyPairGenerator you should have used KeyPairGenParameterSpec. We do not have symmetric keys until API 23.</blockquote><p>We utilize the KeyGenParameterSpec.Builder to build our KeyGenParameterSpec. That Builder requires two arguments: an alias name and a purpose. Threat the alias name as a <strong>unique identifier</strong> assigned to the generated key within the Android Keystore. Later we’ll use it to get our key from the Keystore.</p><blockquote>Notice how we don’t need to manually generate any key material. Isn’t that perfect? In case of SecretKeySpec if someone obtains the key material, they can generate the same key in their devices and use it. But in Android Keystore the key material never enters the application process. Even if someone gets our alias, they can&#39;t create the same key on their devices because the key material will be different. Still, consider keeping your alias somewhere safe :)</blockquote><p>Let’s continue. The second parameter of KeyGenParameterSpec.Builder means for what purpose we use our key. Simply just pass PURPOSE_ENCRYPT or PURPOSE_DECRYPT.</p><p>Next, we invoke multiple builder methods. We specify our <strong>block mode</strong> and <strong>padding</strong>. Let’s talk a little about the other two functions:</p><p><strong><em>setUserAuthenticationRequired(false)</em></strong> — This method is used to specify whether user authentication is required to use the key. When set to true, it means that the key can only be used after the user has been authenticated through methods like a PIN, password, or biometric authentication (e.g., fingerprint or face recognition). By default, the key is authorized to be used regardless of whether the user has been authenticated. So we actually don’t need this function in the scope of this article. I wrote it just to let you know that there’s a such thing too.</p><p><strong><em>setRandomizedEncryptionRequired(true)</em></strong> — According to <a href="https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.Builder#setRandomizedEncryptionRequired(boolean)">docs</a>: Sets whether encryption using this key must be sufficiently randomized to produce different ciphertexts for the same plaintext every time. <em>But didn’t we already get a different ciphertext each time using a random IV?</em> Well, that’s not the case with Android Keystore. What if someone uses some <strong>fixed value</strong> instead of randomly generating the IV? To prevent such cases, the Android Keystore provider is not allowing the use of custom IV values. This function indicates whether you can use your own IV or not.</p><blockquote>However, even passing false to this function we will get <strong>java.security.InvalidAlgorithmParameterException: Caller-provided IV not permitted</strong> exception. Cipher automatically generates a random IV each time under the hood.</blockquote><blockquote>All the functions of <em>KeyGenParameterSpec.Builder</em> you can find <a href="https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.Builder">here</a>.</blockquote><p>Lastly, we get our KeyGenerator instance, initialize it by passing our KeyGenParameterSpec as an argument, and call generateKey(). The key is being securely stored in the <strong>Android Keystore System</strong>.</p><p>Later, to perform encryption/decryption, we should check if that key already exists.</p><pre>@Throws(Exception::class)<br>private fun getOrCreateKey(): SecretKey {<br>    val existingKey = keyStore.getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry<br>    return existingKey?.secretKey ?: createKey()<br>}</pre><p>We retrieve our key via its alias and use, if it exists, otherwise, we create a new one.</p><h3>Encrypting our data</h3><p>Time to do some encryption.</p><pre>@Throws(Exception::class)<br>override fun encrypt(inputText: String): String {<br>    val cipher = Cipher.getInstance(TRANSFORMATION)<br>    cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())<br><br>    val encryptedBytes = cipher.doFinal(inputText.toByteArray())<br>    val iv = cipher.iv<br><br>    val encryptedDataWithIV = ByteArray(iv.size + encryptedBytes.size)<br>    System.arraycopy(iv, 0, encryptedDataWithIV, 0, iv.size)<br>    System.arraycopy(encryptedBytes, 0, encryptedDataWithIV, iv.size, encryptedBytes.size)<br>    return Base64.encodeToString(encryptedDataWithIV, Base64.DEFAULT)<br>}</pre><p>It’s so similar to what we’ve seen in <a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d"><strong>part 2</strong></a>. When we initialize our Cipher, for the second param we pass our <strong>generated key</strong>. But we are not passing our <strong>IV</strong> as we did in the previous part. As mentioned earlier, Cipher handles random IV generation under the hood (considering our block mode). Later we can retrieve that IV from it. The functions here are similar to the ones we used before. If it’s not clear, refer to the step-by-step explanations provided in the previous part.</p><p>Similarly, the decrypt function looks like this:</p><pre>@Throws(Exception::class)<br>override fun decrypt(data: String): String {<br>    val encryptedDataWithIV = Base64.decode(data, Base64.DEFAULT)<br>    val cipher = Cipher.getInstance(TRANSFORMATION)<br>    val iv = encryptedDataWithIV.copyOfRange(0, cipher.blockSize)<br>    cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), IvParameterSpec(iv))<br><br>    val encryptedData = encryptedDataWithIV.copyOfRange(cipher.blockSize, encryptedDataWithIV.size)<br>    val decryptedBytes = cipher.doFinal(encryptedData)<br>    return String(decryptedBytes, Charsets.UTF_8)<br>}</pre><p>For decryption, we should pass the <strong>IV</strong> ourselves. First, we extract it from our encrypted data and then pass an IvParameterSpec in the init function.</p><p>Let’s test it :)</p><figure><img alt="The application demo where we illustrate the process of encryption and decryption" src="https://cdn-images-1.medium.com/max/400/1*DzjSV4txm0O-AlDci0zWQg.gif" /><figcaption>Application Demo</figcaption></figure><h3>Additional Info</h3><blockquote>* You can delete your key entry by its alias name using deleteEntry() function. If the entry cannot be removed a <strong>KeyStoreException</strong> will be thrown.</blockquote><pre>keyStore.deleteEntry(keyAlias)<br><br>// Under the hood it is implemented this way<br>public final void deleteEntry(String alias) throws KeyStoreException</pre><blockquote>* If you want to encrypt your shared preferences, use <a href="https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences"><strong>EncryptedSharedPreferences</strong></a> from the <a href="https://developer.android.com/jetpack/androidx/releases/security">Android Security</a> library (part of Android Jetpack). You can encrypt both keys and values.</blockquote><blockquote>P.S. It’s deprecated :(</blockquote><blockquote>* If you want to encrypt your <strong>Room DB</strong>, one way is to perform it manually with the above steps. Before persisting them in a DB, you can encrypt them and then only persist. For objects, you can serialize them with <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#json">JsonSerializer</a> or <a href="https://github.com/google/gson">Gson</a>, then encrypt and persist in your DB. Another way is to use <a href="https://github.com/sqlcipher/android-database-sqlcipher">SQLCipher</a>. It is an open-source library using which you can encrypt your SQLite database files via AES-256 encryption algorithm.</blockquote><blockquote>* At the moment of writing this article, AndroidX does not provide a library for encrypting or decrypting <strong>Datastore</strong>. So if you use it, you can find third-party libraries in Github, but mostly you should do it manually. You can write extensions over Datastore edit and map functions, serialize objects, encrypt them, and persist. Make sure to implement proper exception handling.</blockquote><h3>Further resources and gists</h3><ul><li><a href="https://developer.android.com/privacy-and-security/cryptography">Android Cryptography</a></li><li><a href="https://developer.android.com/privacy-and-security/keystore">Android Keystore System</a></li><li><a href="https://source.android.com/docs/security/features/trusty">Trusty TEE</a></li><li><a href="https://source.android.com/docs/security/features/keystore">Hardware-backed Keystore</a></li><li><a href="https://developer.android.com/reference/javax/crypto/KeyGenerator">KeyGenerator</a></li><li><a href="https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec">KeyGenParameterSpec</a></li><li><a href="https://mobile-security.gitbook.io/mobile-security-testing-guide/android-testing-guide/0x05e-testing-cryptography">Android Cryptographic APIs</a></li><li><a href="https://www.amazon.com/Android-Security-Internals-Depth-Architecture/dp/1593275811">Android Security Internals: An In-Depth Guide to Android’s Security Architecture</a></li><li><a href="https://gist.github.com/Hayk985/05e5624b619ae3f248c0ab345b063b30">Complete Code</a></li></ul><h3>Conclusion</h3><blockquote>Congratulations on reaching the end! In this final part, our main focus has been on the Android Keystore System. We briefly introduced the Android Keystore and Trusted Execution Environment, emphasizing their importance. We then delved into the key generation process using the KeyGenerator class and highlighted the differences when generating keys via SecretKeySpec. We then proceeded to encryption and decryption. We have also included some additional information and added all the code in the resources section, feel free to explore. If there are some points you couldn’t understand, don’t hesitate to ask them in the comments section. I hope you have enjoyed reading this article series and learned many new things. Thank you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0054fb386a98" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-3-android-keystore-0054fb386a98">Shedding light on Android Encryption. Android Crypto API Part 3 — Android Keystore</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shedding light on Android Encryption. Android Crypto API Part 2 — Cipher]]></title>
            <link>https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d?source=rss-ed52c436296------2</link>
            <guid isPermaLink="false">https://medium.com/p/147ff4411e1d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Hayk Mkrtchyan]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 14:02:04 GMT</pubDate>
            <atom:updated>2024-03-13T16:24:25.837Z</atom:updated>
            <content:encoded><![CDATA[<h4>Android data encryption and decryption</h4><h3>Shedding light on Android Encryption. Android Crypto API Part 2 — Cipher</h3><h4>Hey folks. If you are reading this article, you may be having trouble figuring out how to encrypt data in your Android application to store it securely or send it to a server. Or maybe you just want to learn something new, and I am delighted to help you with that. Welcome to the second part of the Android Crypto API :)</h4><figure><img alt="Android Crypto API article poster which includes all the terminology that confuses developers, like Cipher, MessageDigest, TEE, Algorithms, Block Mode and Paddings, Android KeyStore, KeyGenerator, etc." src="https://cdn-images-1.medium.com/max/1024/1*_1RutprNNiZjTK36QBv7Tg.png" /><figcaption>Android Cryptography</figcaption></figure><p>This article consists of 3 parts:</p><ul><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2">Part 1 — Introduction</a></li><li>Part 2 — Cipher (You are here)</li><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-3-android-keystore-0054fb386a98">Part 3 — Android Keystore</a></li></ul><p>Welcome to the second part of our <strong>Android Crypto API</strong>. Please make sure to take a look at <a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2"><strong>part 1</strong></a> for a better understanding. The ones who did, great job! Now join me to explore today’s topic where we will puzzle out the following:</p><blockquote><strong>- </strong><a href="#6cad"><strong>Revealing Cipher</strong></a><strong><br>- </strong><a href="#df50"><strong>Transformation (Algorithm/Block mode/Padding)</strong></a><strong><br>- </strong><a href="#117b"><strong>Encrypt and decrypt data using Cipher</strong></a><strong><br>- </strong><a href="#54f2"><strong>Key material and SecretKeySpec</strong></a><strong><br>- </strong><a href="#c1ae"><strong>Additional Info</strong></a><strong><br>- </strong><a href="#1cf5"><strong>Further resources and gists</strong></a><strong><br>- </strong><a href="#ba26"><strong>Conclusion</strong></a></blockquote><h3>Revealing Cipher</h3><p>Let’s begin by adding some constants.</p><pre>private const val AES_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES<br>private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC<br>private const val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7<br>private const val TRANSFORMATION = &quot;$AES_ALGORITHM/$BLOCK_MODE/$PADDING&quot;</pre><p>We will break down every line of this a little later. For now, let’s just get our Cipher instance:</p><pre>// If we have a look at the docs it says: <br>// Returns a Cipher object that implements the specified transformation.<br>val cipher = Cipher.getInstance(TRANSFORMATION)</pre><h3>Transformation (Algorithm/Block mode/Padding)</h3><p>Now what is that TRANSFORMATION?<em> </em>Let’s find out. As you can see, the transformation is a combination of AES_ALGORITHM, BLOCK_MODE, and PADDING.</p><p><strong><em>AES_ALGORITHM:</em></strong> We’ll use <a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard"><strong>AES</strong></a><strong> </strong>for our encryption. It is a <strong>symmetric key encryption algorithm,</strong> meaning the same key is used for both encryption and decryption. Let’s have a closer look at how AES performs encryption. Suppose we have our initial data (<em>plain text</em>). AES breaks it into smaller parts that we call <strong>blocks</strong>. Each block has a fixed size and for AES it’s <strong>128</strong> bits (<strong><em>16</em></strong><em> bytes</em>). It encrypts each block separately and then goes through multiple rounds of encryption. The number of rounds depends on the key length. It can be <strong>128/192/256</strong> bits. That’s all we need to know, but you can always delve deeper.</p><blockquote>We do not have symmetric keys until API level 23 (Android 6). They are available from API 23 onwards.</blockquote><p><strong><em>BLOCK_MODE: </em></strong>Block modes define how a <strong>block cipher</strong>, like AES, processes and encrypts data in blocks. They determine the interactions between these blocks during encryption. There are different block modes like ECB, CBC, CFB, etc. For our tutorial, we will go with <strong>CBC (</strong><em>Cipher block chaining</em>). In CBC mode, each block is mixed with the previous <a href="https://en.wikipedia.org/wiki/Ciphertext"><strong>ciphertext</strong></a> block, creating a chain of interdependent encrypted blocks. This prevents an identical plaintext from producing the same ciphertext and adds an additional layer of security.</p><blockquote>Hmm, no, it won’t actually:)) Still, we would get the same ciphertext for an identical plaintext.</blockquote><p><strong><em>IV: </em></strong>So why do we still get the same ciphertext for the same plaintext? The chaining effect in CBC is based on <strong>XOR</strong>ing each plaintext block with the ciphertext of the previous block. This creates dependencies between the blocks. But what about the very first block? There is no previous block. And here comes the <strong>Initialization Vector (IV) — </strong>a random generated value that is combined with the first block of plaintext before encryption. It has the same size as the block, i.e. <strong>16 bytes</strong>. As it is random, each time a different mix is generated for each block, and thus we always get a different ciphertext for the same plaintext.</p><p><strong><em>PADDING:</em></strong> As previously mentioned, CBC processes data in a fixed-size blocks. However, not all messages perfectly fit into these blocks. That’s where padding comes in. It adds extra bytes to ensure it aligns with the block size. There are paddings like <strong>PKCS5, Zero Padding, ISO Padding, </strong>etc. We will use <strong>PKCS7</strong>.</p><blockquote>So overall here are all the steps involved: First, we break our data into blocks (<strong>AES</strong>). If the data doesn’t completely fit inside the block, we add extra bytes to it (<strong>Padding</strong>). Then we generate a random <strong>IV</strong> and mix when encrypting our first block (<strong>CBC</strong>). In the end, we get our ciphertext which is always different even for the same plaintext. And that makes our <strong>TRANSFORMATION</strong> that we pass to Cipher.</blockquote><figure><img alt="A diagram that illustrates the process of encryption with AES algorithm and CBC mode. We see the whole process how a plain text is converted to a ciphertext. The initialization vector is there too and you can see how it is combined with the very first block." src="https://cdn-images-1.medium.com/max/1024/1*_rAPp_ic4A0oxi5MfWmipw.png" /><figcaption>Encrypting data using the AES CBC mode.</figcaption></figure><figure><img alt="Same diagram as the previous one, except padding is applied." src="https://cdn-images-1.medium.com/max/1024/1*Y7cyH1lsEImeh0-N2GV6tQ.png" /><figcaption>Encrypting data using the AES CBC mode with padding.</figcaption></figure><figure><img alt="A diagram that illustrates the process of decryption with AES algorithm and CBC mode. We see the whole process how a ciphertext is decrypted back to a plain text." src="https://cdn-images-1.medium.com/max/1024/1*1gAdmj8P1aZnMpS0RZriLw.jpeg" /><figcaption>Decrypting data using the AES CBC mode.</figcaption></figure><h3>Encrypt and decrypt data using Cipher</h3><p>Back to our code. To start working with the Cipher instance, we need to initialize it for a specific <strong>operation</strong> with a <strong>key</strong>.</p><pre>// Operation Mode - Cipher.ENCRYPT_MODE<br>// Key - SecretKeySpec(keyValue, AES_ALGORITHM)<br>// Algorithm params - IvParameterSpec(iv)<br><br>val cipher = Cipher.getInstance(TRANSFORMATION)<br>cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyValue, AES_ALGORITHM), IvParameterSpec(iv))</pre><p>For the operation mode, we pass <strong><em>ENCRYPT_MODE </em></strong>as we want to do encryption. Similarly, for decryption, we would pass <strong><em>DECRYPT_MODE. </em></strong>The second parameter is our key. We’ll talk about it later. With the third parameter, we specify our <strong>Initialization Vector</strong> (<em>IV</em>). Let’s have a look at how to generate it.</p><pre>private fun generateRandomIV(size: Int): ByteArray {<br>    val random = SecureRandom()<br>    val iv = ByteArray(size)<br>    random.nextBytes(iv)<br>    return iv<br>}</pre><p>Here we generate a random IV with a given size. As we have initialized our Cipher and generated IV, we can proceed to encryption. First, I’ll show the full code then we will go line by line:</p><pre>@Throws(Exception::class)<br>fun encrypt(inputText: String): String {<br>    val cipher = Cipher.getInstance(TRANSFORMATION)<br>    val iv = generateRandomIV(cipher.blockSize)<br>    cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyValue, AES_ALGORITHM), IvParameterSpec(iv))<br><br>    val encryptedBytes = cipher.doFinal(inputText.toByteArray())<br>    val encryptedDataWithIV = ByteArray(iv.size + encryptedBytes.size)<br>    System.arraycopy(iv, 0, encryptedDataWithIV, 0, iv.size)<br>    System.arraycopy(encryptedBytes, 0, encryptedDataWithIV, iv.size, encryptedBytes.size)<br>    return Base64.encodeToString(encryptedDataWithIV, Base64.DEFAULT)<br>}</pre><p>You are already familiar with the first 3 lines))) Worth mentioning that we have the cipher’s <strong>block size</strong>. Also, this function can throw several exceptions, that’s why we simply throw a general Exception.</p><blockquote>Error handling is essential when dealing with encryption/decryption.</blockquote><pre>val encryptedBytes = cipher.doFinal(inputText.toByteArray())</pre><p>The doFinal() function takes a ByteArray as an input and does the encryption. So here we have our encrypted bytes in the output. But how to connect it with our IV? Later, we should use the same generated IV in our decryption, otherwise, we can’t decrypt our message back :(</p><pre>val encryptedDataWithIV = ByteArray(iv.size + encryptedBytes.size)<br>System.arraycopy(iv, 0, encryptedDataWithIV, 0, iv.size)<br>System.arraycopy(encryptedBytes, 0, encryptedDataWithIV, iv.size, encryptedBytes.size)</pre><p>We create a new ByteArray that has the summary length of our generated IV and encrypted bytes. First, we copy our IV into that ByteArray using System.arrayCopy(). The initial 16 bytes are occupied by our IV. We then append our encrypted bytes to our IV. In the end, we use Base64 to encode it to String.</p><blockquote>Consider working directly with ByteArray and encoding it to String or another type outside this function. I did this in the same function for simplicity.</blockquote><p>Let’s take a look at our decrypt function, and then we will test our code.</p><pre>@Throws(Exception::class)<br>fun decrypt(data: String): String {<br>    val encryptedDataWithIV = Base64.decode(data, Base64.DEFAULT)<br>    val cipher = Cipher.getInstance(TRANSFORMATION)<br>    val iv = encryptedDataWithIV.copyOfRange(0, cipher.blockSize)<br>    val encryptedData = encryptedDataWithIV.copyOfRange(cipher.blockSize, encryptedDataWithIV.size)<br>    cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyValue, AES_ALGORITHM), IvParameterSpec(iv))<br>    <br>    val decryptedBytes = cipher.doFinal(encryptedData)<br>    return String(decryptedBytes, Charsets.UTF_8)<br>}</pre><p>First, we decode our String to ByteArray. Then we split our ByteArray to extract the IV from it using the copyOfRange() function. When we have separated our IV and encrypted bytes, we can initialize our Cipher and pass that IV as an argument. As you can see this time we pass the operation mode <strong><em>DECRYPT_MODE</em></strong>. Then with the doFinal() function, we decrypt our data. In the end, we just convert our decrypted ByteArray to String.</p><blockquote>If you look closely, you’ll notice that we use the same <em>doFinal()</em> in both our encryption and decryption. Then how is that function aware should it encrypt or decrypt our message? Well, it does base on which operation mode our Cipher was initialized.</blockquote><p>On a button click you call either encrypt() by passing the <em>input text</em> or decrypt() by passing the <em>encrypted data</em>.</p><pre>Button(onClick = { AESUtils.encrypt(input) }) {<br>    Text(text = &quot;Encrypt&quot;)<br>}<br><br>Button(onClick = { AESUtils.decrypt(encryptedText) }) {<br>    Text(text = &quot;Decrypt&quot;)<br>}</pre><p>Now, let’s test our code.</p><figure><img alt="The application demo where we illustrate the process of encryption and decryption" src="https://cdn-images-1.medium.com/max/400/1*nudgP-AzayIHUJOOxYlhLw.gif" /><figcaption>Application Demo</figcaption></figure><p>Works like a charm. You can find the complete code at the end of this article.</p><h3>Key material and SecretKeySpec</h3><blockquote>To encrypt and decrypt our data we need a key. In the above examples we used SecretKeySpec class and passed it as an argument for the key. This class is used to construct a key from a given byte array.</blockquote><p>But what is this byte array we are talking about? To gain a better understanding, let&#39;s take a closer look at its constructor.</p><pre>/**<br> @param key - the key material of the secret key.<br> @param algorithm - the name of the secret-key algorithm to be associate with the given key material.<br>*/<br>public SecretKeySpec(byte[] key, String algorithm) { ... }</pre><p>So to construct a key it needs a <strong>key material</strong>. In this context, it is a byte[].</p><blockquote>To understand better, treat it as some kind of <strong>signature</strong> for that <strong>key</strong>. If someone has that key material (<strong>signature</strong>), they can construct the same key. So it is vital to keep it as safe as possible.</blockquote><p>Let’s see how we can create our byte array (<strong>key material</strong>).</p><pre>private val keyValue = &quot;keep_this_key_in_secret&quot;.toByteArray(Charsets.UTF_8)</pre><p>If we run our code and click on encrypt, our app will crash with the following message: <strong>java.security.InvalidKeyException: Unsupported key size: 23 bytes.</strong></p><p>So why is that? Somewhere above we mentioned the significance of the <strong>key length</strong>. For AES it can be <strong>128</strong>, <strong>192</strong>, or <strong>256</strong> bits. You can see in some places something like <strong>AES-192</strong> or <strong>AES-256</strong>. That value specifies the key length. <em>More key length means more security</em>. You are free to delve deep if you want to. <strong>AES-128</strong> is sufficient to ensure the security we need. So for our input we pass a ByteArray, which is <strong>23 bytes</strong> or <strong>184 bits</strong>. SecretKeySpec can’t find an AES algorithm that can have a key with that length, that’s why it crashes. <em>For AES-128 our key size should be 128 bits or 16 bytes</em>. Let’s fix it.</p><pre>private val keyValue = &quot;keep_this_key_sc&quot;.toByteArray(Charsets.UTF_8)</pre><blockquote>As we’ve said, it is crucial to keep it as safe as possible. In real applications, you should at least consider keeping it in local properties and reading from there instead of hardcoding. For demonstration purposes, I keep it hardcoded.</blockquote><h3>Additional Info</h3><p>Sometimes you may need to persist the key in some storage. To make this operation secure you should perform <strong>key wrapping</strong>. In simpler words, you <em>create a new key and encrypt the key you want to save</em>. Afterward, you should store that Base64 String in a database or another place. This will also give you an additional layer of security. Then you can <strong>unwrap</strong> it with the key you wrapped with and perform cryptographic operations.</p><figure><img alt="A diagram that illustrates how key wrapping is performed. It demonstrates 2 keys, one is the key generated via some key material or based on user input, and the other one is the actual key that we use for encryption/decryption purposes. We use the first key to wrap our second key, which also gives an additional security." src="https://cdn-images-1.medium.com/max/1024/1*SBTvImW0mJ3Hipee8fuXqw.png" /><figcaption>Key Wrapping</figcaption></figure><blockquote>Important: For key wrapping you should use Cipher.<em>WRAP_MODE. Similarly, for unwrapping use </em>Cipher.<em>UNWRAP_MODE. </em>I’ll provide an example gist below. Make sure to check.</blockquote><blockquote>What if you want to generate a key based on some user input? For example, a password-protected application. For that you should take a look at <a href="https://developer.android.com/reference/javax/crypto/spec/PBEKeySpec">PBEKeySpec</a>.</blockquote><h3>Further resources and gists</h3><ul><li><a href="https://developer.android.com/privacy-and-security/cryptography">Android Cryptography</a></li><li><a href="https://developer.android.com/reference/javax/crypto/Cipher">Cipher</a></li><li><a href="https://developer.android.com/reference/javax/crypto/spec/SecretKeySpec">SecretKeySpec</a></li><li><a href="https://www.amazon.com/Android-Security-Internals-Depth-Architecture/dp/1593275811">Android Security Internals: An In-Depth Guide to Android’s Security Architecture</a></li><li><a href="https://gist.github.com/Hayk985/8deb740b85e4ef443a62dbef672cd882">Complete Code</a></li><li><a href="https://gist.github.com/Hayk985/d5e6c3dcaa6ae37a7c6eeba3c4f9758c">An example of Key Wrapping</a></li><li><a href="https://gist.github.com/Hayk985/f05eb98dbb676fc45d0fe22ce1e109b6">An example of Password Based Encryption (PBE)</a></li></ul><h3>Conclusion</h3><blockquote>In this second part of our article, we introduced Cipher, explored cipher block chaining, initialization vector, and padding. Next, we have illustrated an example of how to encrypt and decrypt data with Cipher. We broke down the code and explained it in detail, line by line. Also, we discussed about key material and how to construct a key using SecretKeySpec. In conclusion, we have included some additional information and added the code in the resources section, allowing you to explore further and enhance your knowledge on your own. If there are some points you couldn’t understand, feel free to ask in the comments section. Hope you enjoyed reading. Thank you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147ff4411e1d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d">Shedding light on Android Encryption. Android Crypto API Part 2 — Cipher</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shedding light on Android Encryption. Android Crypto API Part 1 — Introduction]]></title>
            <link>https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2?source=rss-ed52c436296------2</link>
            <guid isPermaLink="false">https://medium.com/p/9623ca992dc2</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[android-encryption]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[cipher]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Hayk Mkrtchyan]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 18:55:13 GMT</pubDate>
            <atom:updated>2024-03-12T19:58:20.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>Android data encryption and decryption</h4><h3>Shedding light on Android Encryption. Android Crypto API Part 1 — Introduction</h3><h4>Hey folks. If you are reading this article, you may be having trouble figuring out how to encrypt data in your Android application to store it securely or send it to a server. Or maybe you just want to learn something new, and I am delighted to help you with that. Welcome to the first part of the Android Crypto API :)</h4><figure><img alt="Android Crypto API article poster which includes all the terminology that confuses developers, like Cipher, MessageDigest, TEE, Algorithms, Block Mode and Paddings, Android KeyStore, KeyGenerator, etc." src="https://cdn-images-1.medium.com/max/1024/1*_1RutprNNiZjTK36QBv7Tg.png" /><figcaption>Android Cryptography</figcaption></figure><p>I will divide this article into 3 parts:</p><ul><li>Part 1 — Introduction (You are here)</li><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d">Part 2 — Cipher</a></li><li><a href="https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-3-android-keystore-0054fb386a98">Part 3 — Android Keystore</a></li></ul><p>As usual, let’s start by breaking down everything from the very foundation. So for today’s article we’re gonna walk through</p><blockquote><strong>- </strong><a href="#7270"><strong>Cryptography basics</strong></a><strong><br>- </strong><a href="#0516"><strong>How can we encrypt our data?</strong></a><strong><br>- </strong><a href="#b1cb"><strong>Cryptography in Android</strong></a><strong><br>- </strong><a href="#67ac"><strong>MessageDigest</strong></a><strong><br>- </strong><a href="#2d69"><strong>Further resources and gists</strong></a><strong><br>- </strong><a href="#ba26"><strong>Conclusion</strong></a></blockquote><h3>Cryptography basics</h3><p>As an Android developer, we don’t have to dive deep into Cryptography to understand how to encrypt our data. However, many developers are still confused by the lack of knowledge of cryptographic terminology.</p><blockquote>We don’t want to write code blinded, rather we want to understand what we’re writing.</blockquote><p>So what is Cryptography? In simple terms, it is a way to keep our data secret, i.e., no one could see what’s behind it. Imagine you want to protect your phone from others from accidentally using it. Well, you would apply some security measures. Suppose you set a pin on your device, so only you can unlock it. In this way only you know the <strong><em>key</em></strong> (pin), and only you can use that <strong><em>key</em></strong> to unlock and see what’s in your phone. Others, who don’t know the <strong><em>key</em></strong>, can’t sneak their nose into your phone :D</p><p>Imagine another scenario, where you want to secretly communicate with your friend, so no one could understand you both. You and your friend choose to create a new language that only the two of you will understand, using special code for every word. And that is what <strong>Cryptography</strong> is all about. It is like using magical codes to lock and unlock your messages, ensuring that only you and your friend can understand them.</p><figure><img alt="An illustration of an image where two friends choose to create some special language where every letter will correspond to some character set that only they can understand. This is what generally cryptography is all about." src="https://cdn-images-1.medium.com/max/1024/1*mDXxTs9lLk_0TObvJwymhA.png" /><figcaption>Basic illustration of Cryptography</figcaption></figure><p>In the digital world, these magical codes are mathematical techniques and algorithms that keep your messages safe from prying eyes. It’s like having a <strong>special key</strong> using which you make your message look like gibberish to others. However, your friend can use that same key to turn it back into its original form.</p><h3>How can we encrypt our data?</h3><p>So what about all these algorithms that we use to ensure the security of our messages? Well, there are lots of techniques to make our information secure, like using</p><ul><li><strong>Symmetric Key Algorithms (<em>AES</em>, <em>GMS</em>)</strong></li><li><strong>Asymmetric Key Algorithms (<em>RCA</em>, <em>ECC</em>)</strong></li><li><strong>Hash Functions (<em>MD5</em>, <em>SHA</em>)</strong></li></ul><p>Let’s talk a little about them.</p><p><strong><em>Symmetric-key algorithm:</em></strong> Imagine having a treasure chest and a single key. You lock the chest (<strong>encrypt</strong>) with that key, and only someone with the same key can unlock (<strong>decrypt</strong>) it. In other words, we use the same key for encryption and decryption. So if someone has the same key, they can open the chest.</p><figure><img alt="A diagram that shows how symmetric encryption is performed. It uses the same secret key for encryption and decryption. It shows how a plain text is encrypted to a cipher text, and later decrypted to a plain text." src="https://cdn-images-1.medium.com/max/1024/1*ZxWX51UZ3O1IHmQ4I9Kdpw.png" /><figcaption>Symmetric Encryption Illustration. It uses the same Secret Key for encryption and decryption.</figcaption></figure><p><strong><em>Asymmetric-key algorithm:</em></strong> Also known as <strong>public key cryptography</strong>. Suppose you have 2 keys, one that locks the treasure chest and the other one unlocks. Let’s call them <strong>public</strong> and <strong>private</strong> keys. You lock the chest (encrypt) with your public key. Others can’t open (decrypt) it with the same public key. Only the private key can open the chest. It is widely used, especially for TLS/SSL, which makes HTTPS possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrMrg6L5zvIzUKhodES6Yw.png" /><figcaption>Asymmetric Encryption Illustration. It uses different keys for encryption and decryption.</figcaption></figure><p><strong><em>Hash Functions:</em></strong> As the name implies, hash functions are algorithms that take any input and generate a hash value for it. The output hash size is always <strong>fixed</strong> regardless of the input size. For example, the MD5 algorithm output hash size is <strong>128 bits</strong> or <strong>16 bytes</strong>. It’s important to note that hash functions are <strong>one-way operations</strong>, meaning we can only encrypt our data but not decrypt it, unlike Symmetric and Asymmetric-key algorithms.</p><blockquote>The process of generating a hash value is called <strong>hashing</strong>. For simplicity, I used encrypt/decrypt but in general hashing and encryption have different meanings.</blockquote><p>So why would we need hash functions if we can’t decrypt them back?))) There are certain scenarios where we need only hash values. For example, we can use them to securely store passwords. Instead of saving the actual password, we would rather save the hash value of that password. During login, we will check the entered password’s hash against the stored hash.</p><figure><img alt="An illustration that shows how hashing is performed. It takes the input, applies some hash function to it, and generates the hash of that input. This process is called hashing." src="https://cdn-images-1.medium.com/max/1024/1*tkMRS1lQuDQQpSVqAtcpew.jpeg" /><figcaption>Hash generation (hashing) example</figcaption></figure><h3>Cryptography in Android</h3><p><a href="https://developer.android.com/privacy-and-security/cryptography"><strong>Android Cryptography API</strong></a> provides a set of classes and interfaces that allow us to implement cryptographic operations in our application. We’ll take a look at MessageDigest and Cipher.</p><p>The MessageDigest class from java.security provides a way to implement hash functions. We can use that to generate a hash value for our data using hashing algorithms like <strong>MD5</strong>, <strong>SHA-1</strong>, <strong>SHA-256</strong>, etc.</p><p>A Cipher in cryptography is a set of rules that allows us to encrypt and decrypt data. A cipher transforms data by processing the original <strong>plaintext </strong>or other data into a <strong>ciphertext</strong>. The ciphertext should appear as random data. We have a Cipher class from javax.crypto that we can use for these purposes.</p><p>I will illustrate a small example of generating a hash value using the <strong>MD5 (message-digest)</strong> algorithm.</p><blockquote>We’ll talk about Cipher class in the next part.</blockquote><h3>MessageDigest</h3><p>First, we need to get our MessageDigest instance passing the corresponding <strong>algorithm</strong> as an argument.</p><pre>val md = MessageDigest.getInstance(&quot;MD5&quot;)</pre><p>We will use <strong>MessageDigest’s</strong> public byte[] digest(byte[] input) method to generate a hash value for our input. As you see, it takes an input as an array of bytes and returns the same. We can convert the user’s input to a byte array, and call the digest function to generate the hash value for that input. Suppose the user has entered some text and we want to generate a hash value for it.</p><pre>val inputBytes: ByteArray = userInput.encodeToByteArray()<br>val hashData: ByteArray = md.digest(inputBytes)</pre><p>This hashData is the generated hash value. Let’s have a glance at the complete function.</p><pre>private const val MD5_ALGORITHM = &quot;MD5&quot;<br><br>@Throws(NoSuchAlgorithmException::class, NullPointerException::class)<br>fun String.generateMD5Hash(): String {<br>    val md = MessageDigest.getInstance(MD5_ALGORITHM)<br>    val inputBytes: ByteArray = this.encodeToByteArray()<br>    val hashData: ByteArray = md.digest(inputBytes)<br><br>    return hashData.toHex()<br>}</pre><p>For simplicity, I’ve created an extension function for String that will generate our <strong>hash</strong>. The MessageDigest.getInstance(String algorithm) function may throw exceptions, so we need to handle them. That’s why we annotate our function with @Throws.</p><p>This function takes String as an input and returns String. To avoid unrecognized characters in the output, we use the toHex() function to convert ourByteArray to a human-readable hexadecimal String.</p><pre>fun ByteArray.toHex(): String {<br>    return joinToString(&quot;&quot;) { &quot;%02x&quot;.format(it) }<br>}</pre><p>But generally, you should work only with ByteArray. So let’s test our code and see if it works.</p><pre>fun main() {<br>    val inputText = &quot;Let&#39;s encrypt this message with MD5&quot;<br><br>    // You should apply error handling as this function may through an exception<br>    val hashValue = inputText.generateMD5Hash()<br>    println(&quot;#1 Generated hash is: $hashValue&quot;)<br><br>    val anotherInput = &quot;Completely another message, could be song lyrics&quot;<br>    val anotherHashValue = anotherInput.generateMD5Hash()<br>    println(&quot;#2 Generated hash is: $anotherHashValue&quot;)<br>}</pre><p>After running our code we will see the following output in the console:</p><pre>#1 Generated hash is: 867cf9069b40121f451b22013ec03e54<br>#2 Generated hash is: a2860d6a8d92c785067fc5ad081081f4</pre><blockquote>As we said earlier, the <strong>MD5 algorithm</strong> hash size is <strong>128 bits</strong> or <strong>16 bytes</strong>. If we take a look at our output, you can notice that the hexadecimal string length is <strong>32</strong> characters long. Since each pair of characters in a hexadecimal string represents one byte, our hash size is <strong>16 bytes</strong>.</blockquote><figure><img alt="A diagram illustrating our code, where we give two different inputs, apply MD5 hash algorithm and generate the hash using MessageDigest class." src="https://cdn-images-1.medium.com/max/1024/1*uL4ikSW7KCtEaT2sRRyPUg.png" /><figcaption>MessageDigest (MD5) Example</figcaption></figure><h3>Further resources and gists</h3><ul><li><a href="https://developer.android.com/privacy-and-security/cryptography">Android Cryptography</a></li><li><a href="https://developer.android.com/reference/java/security/MessageDigest">MessageDigest</a></li><li><a href="https://www.amazon.com/Android-Security-Internals-Depth-Architecture/dp/1593275811">Android Security Internals: An In-Depth Guide to Android’s Security Architecture</a></li><li><a href="https://gist.github.com/Hayk985/a0a83ce8ae90f07be6a5445126dc14aa">MD5 Hash Generator Code Example</a></li></ul><h3>Conclusion</h3><blockquote>In this article, we have covered some basics of cryptography and illustrated some examples. Next, we discussed different encryption techniques, such as symmetric key algorithms, asymmetric key algorithms, and hash functions. We learned about the Android Cryptography API, looked at the MessageDigest and Cipher classes, and created a small program for generating a hash value using the MD5 algorithm. Don’t forget to check out the resources and gist files above to dive deeper. If there are some points you couldn’t understand, feel free to ask in the comments section. Hope you enjoyed reading. Thank you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9623ca992dc2" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2">Shedding light on Android Encryption. Android Crypto API Part 1 — Introduction</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking Android Screen Sizes]]></title>
            <link>https://medium.com/better-programming/cracking-android-screen-sizes-88228822-98b28d23260c?source=rss-ed52c436296------2</link>
            <guid isPermaLink="false">https://medium.com/p/98b28d23260c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hayk Mkrtchyan]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 15:37:38 GMT</pubDate>
            <atom:updated>2022-03-04T12:05:25.843Z</atom:updated>
            <content:encoded><![CDATA[<h4>We will explore Android’s different screen sizes and have a clear understanding of various terminologies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtT-PxLyt7CHVCLB_hg7Jg.jpeg" /></figure><pre><strong>Table of Contents</strong></pre><pre>Introduction<br>Pixel and Screen size<br>Pixels Per Inch (PPI) and how it is calculated<br>Different Densities in Android<br>How to calculate device density<br>Working with sizes<br>Wrap Up</pre><h3>Introduction</h3><p>In Android, there are many display-related qualifiers, which sometimes confuse developers. What are DPs? How are they different from DIP? What are the various densities? How do all the calculations happen? Is it possible to get screen width and height in inches? In this article, I will answer all of these questions.</p><p>P.S. This article is not about how to support multiple screen sizes.</p><h3>Pixel and Screen Size</h3><p>I guess everyone knows what are pixels. If you will capture your monitor and zoom in, you can see small squares with an RGB color in them. All these small squares are pixels. Pixel is also stand for picture element (pix = picture, el = element). They are the basic building blocks of a digital image or display. If the monitor resolution is 1280px width and 720px height then overall that monitor has 921 600 pixels. It also represents the pixel density. With higher density, the quality of the image will become better. If the monitor resolution is 3840x2160, overall it has 8 294 400 pixels.</p><p>Now, what is the screen size? It is the distance between opposite corners. It’s also called diagonal. If the distance is 6.5 inches then the screen size is 6.5.</p><p>So how these screen size and pixels are connected? Let’s take a display, which resolution is 1080x1920 (width x height) and screen size is 5.5 inches. Overall there will be 1080 * 1920 = 2 073 600 pixels on the screen.</p><p>Now a question for you:<strong> </strong>Suppose we have 2 devices, they have the same resolution 1080x1920, but the first device screen size is 7.0 inches and the other one 5.5 inches. In which device the screen quality will be better? The answer we need to find in the next section.</p><h3>Pixels per inch (PPI) and how it is calculated</h3><p>Before starting, let’s make clear one thing. In Android PPI and DPI (dots-per-inch) are the same thing. In real life they are different, but Android team chose to use DPI rather than PPI.</p><p>Sometimes, if you will have a look at device specifications, in the display section you may see PPI value. It stands for Pixels-Per-Inch, which represents pixels count in one inch of the device.</p><p>How is PPI calculated? To calculate PPI, we need screen resolution WxH and the screen size. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*w3XTR64VeDj3OxMAs1EYXw.png" /><figcaption>Formula to calculate screen PPI</figcaption></figure><p>Let’s take the values from the section above. If our screen resolution is 1080x1920 and screen size is 7.0 inches, then PPI will be:</p><pre>1080 x 1080 = 1 166 400<br>1920 x 1920 = 3 686 400<br>1 166 400 + 3 686 400 = 4 852 800<br>sqrt(4 852 800) = ~2203<br>2203 / 7.0 = ~315</pre><p>So our PPI value for the 7 inches screen is approximately 315. Let’s do the same operation for another screen with the same resolution but 5.5 inches in size. In this case, PPI will be approximate ~401.</p><p>The screen quality is directly proportional to pixels count in 1 inch (PPI). If the PPI value is high, that device screen quality will be better.</p><p>Now let’s answer that question from the previous section. Which device screen quality will be better? Of course, 5.5 inches screen, because in 1 inch it has more pixels.</p><h3>Different Densities in Android</h3><p>From now, I will use DPI instead of PPI, because those are the same thing. Take a bit of special care here to not get confused later.</p><p>* In Android, when we create the UI, mostly we use DP as the size specifier for the views. DP (Density-independent pixels) is the same as DIP, don’t get confused. The only reason is that DP is more consistent with SP (Scale-independent pixels).</p><p>* SP (Scale-independent pixels) is the same as DP, with an additional scaling factor that is based on the font size which the user selects in the device’s system settings. SP should be used only as a unit for text. Avoid using SP as a unit for non-text components.</p><p>*Density is the same as DPI, it shows the pixels count in 1 inch area. In Android, DPI is just a measurement unit, which represents the density. E.g. for the device with a resolution 1080x1920 and 5.5 inches size we can say that device screen density is ~401.</p><p>I hope the terminology is clear. No? Just read it again more carefully))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*eqZQuAtuARj4Lj0lXxMiTg.png" /><figcaption>Density, DPI and PPI are interconnected. Those are the same thing.</figcaption></figure><p>So what means density-independent? It means, that our view size will be independent of the screen density. You know, if we will specify our view size in pixels, it will change its size regarding density. Assume we have an ImageView which width and height are 200x200px. Now, if the device density will be 100 dpi, this ImageView will take 2 inches width and height on the screen. But if the device density will be 400 dpi, it will take 0.5 inches instead. I hope the terminology is clear. If you’re confused, read about PPI/DPI one more time.</p><p>So how it can be independent of density? To answer this, let me introduce the different density buckets, which exist in Android:</p><pre>ldpi - low density bucket (~120dpi, 0.75x).<br>mdpi - medium density bucket (~160dpi, 1x)<br>hdpi - high density bucket (~240dpi, 1.5x)<br>xhdpi - extra high density bucket (~320dpi, 2x)<br>xxhdpi - extra-extra high density bucket (~480dpi, 3x)<br>xxxhdpi - extra-extra-extra high density bucket (~640dpi, 4x)</pre><blockquote>The ldpi bucket is not very common anymore.</blockquote><p>As you see, Android has 6 density buckets. Of course, there is also nodpi (resources for all densities) and tvdpi (resources intended for TVs) buckets, but we will not cover them in this article. In screens with 160 dpi, 1dp is roughly equal to 1px. That’s why it’s called medium density. Also, it’s called in some places baseline density.</p><h3>How to calculate device density</h3><p>Let’s take the device from our examples, which density was ~315 dpi. If we’ll have a look at the densities table, we see that 315 dpi is in the middle of hdpi and xhdpi. Now to which density bucket our device belongs? Maybe hdpi? Or maybe xhdpi? Well, it can be either hdpi or xhdpi, we can’t expect. Manufacturers have some flexibility in picking the density. But usually, the device belongs to its nearest bucket. This means, the device which is 315 dpi, will be xhdpi and the device which is 401 dpi, will be xxhdpi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*GuY3wizS8IMmkOVz_SfBJg.png" /><figcaption>Device density is 401 dpi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*Cn1ntinhSlN9ZHU2bbinig.png" /><figcaption>Device density is 315 dpi</figcaption></figure><p>When we specify our view size in dp, our view gets scaled regarding screen density. But how does Android know how much it has to scale the view? As we mentioned above, in 160 dpi screens 1dp is equal to 1px.</p><p>Let’s take the device whose density is 401 dpi. To get the scale factor we have to divide 401 to 160. The result determines how much the view will be scaled on this device. The answer is 2.51.</p><p>We can also determine how many pixels it is. Let’s take a simple view with the size 50x50dp. In our device, Android will multiply 50 with the scale factor to get view size in pixels for the current device. We’ll get 126px.</p><p>For the other device, which density is ~315 dpi, the scale factor will be ~1.97. So the same view with 50dp size, in this device will be 99 pixels. That’s why dp is density-independent. Each screen has its own scale factor which determines how many pixels will take the view on the screen.</p><h3>Working with sizes</h3><p>At this point, we already know many things about dp, px, screen size, and densities. Now it’s time for coding :)</p><p>We will cover some subtopics here:</p><ul><li>How to get display real width and height?</li><li>How to determine device density and its scale factor?</li><li>Can we get display width and height in inches?</li><li>Find device screen size.</li></ul><h4><strong>How to get display real width and height?</strong></h4><p>We can get the display’s real width and height in pixels using WindowManager class.</p><pre>fun WindowManager.currentDeviceRealSize(): Pair&lt;Int, Int&gt; {<br>    return if (Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>R</em>) {<br>        return Pair(<br>            <em>maximumWindowMetrics</em>.<em>bounds</em>.width(),<br>            <em>maximumWindowMetrics</em>.<em>bounds</em>.height())<br>    } else {<br>        val size = Point()<br>        <em>defaultDisplay</em>.getRealSize(size)<br>        Pair(size.x, size.y)<br>    }<br>}</pre><pre>val (width, height) = windowManager.currentDeviceRealSize()</pre><p>In the above program, we have 1 extension function, which returns a Pair of Int. The Pair represents display width and height. Starting from Android 11 (API 30) defaultDisplay.getRealSize() function is deprecated.</p><h4><strong>How to determine device density and its scale factor?</strong></h4><p>How to determine the device density and its scale factor? Can we somehow determine what’s the device dpi?</p><p>Unfortunately, there’s no guarantee we can always get the correct values. There is one class which is called DisplayMetrics. It includes information about our display characteristics. We can retrieve DisplayMetrics instance using:</p><pre>val displayMetrics = <em>resources</em>.<em>displayMetrics</em></pre><p>DisplayMetrics has some variables:</p><pre>displayMetrics.density //The scale factor of the density<br>displayMetrics.densityDpi // The density of the screen</pre><p>Sad news: These values don’t return the correct information about the scale factor and density. But instead, there are 2 variables, which usually return more accurate values.</p><pre>displayMetrics.xdpi // The pixels count in inch for screen width<br>displayMetrics.ydpi // The pixels count in inch for screen height</pre><p>The “xdpi” represents the pixels per inch of the screen in the X dimension. The “ydpi” is the same but for the Y dimension. Even in this case, we don’t have a 100% guarantee, that we’ll get the correct values. But in my practice I give advantage to these values. In most cases “xdpi/ydpi” return the same value, so it’s up to you which one to use.</p><h4><strong>Can we get display width and height in inches?</strong></h4><p>If we are lucky and got the correct values, we can easily count display width and height in inches.</p><pre>val (width, height) = <em>windowManager</em>.currentDeviceRealSize()<br>val displayMetrics = <em>resources</em>.<em>displayMetrics<br></em>val widthInInches = width / displayMetrics.xdpi<br>val heightInInches = height / displayMetrics.ydpi</pre><p>We just have to divide our width in pixels by the pixels count per inch. For the width we use xdpi and for the height ydpi, because in the coordinates system x axis is the width and the y axis is the height.</p><h4><strong>Find device screen size</strong></h4><p>Well, it’s easy to calculate as we already have screen width and height in inches. Using the Pythagorean theorem we can easily determine our screen size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*SL5zcU6ZjGrqgTXOrLcMDQ.jpeg" /></figure><p>The program will look like this:</p><pre>val (width, height) = <em>windowManager</em>.currentDeviceRealSize()<br>val widthInInches: Double = (width / <em>resources</em>.<em>displayMetrics</em>.xdpi).toDouble()<br>val heightInInches: Double = (height / <em>resources</em>.<em>displayMetrics</em>.ydpi).toDouble()<br><br>val widthAndHeightSum = widthInInches.<em>pow</em>(2) + heightInInches.<em>pow</em>(2)<br>val screenSize = <em>sqrt</em>(widthAndHeightSum)</pre><p>We can also use the Math class hypot() function which will internally do this calculation for us.</p><p>hypot() - Computes sqrt(x^2 + y^2) without intermediate overflow or underflow.</p><pre>val (width, height) = <em>windowManager</em>.currentDeviceRealSize()<br>val widthInInches: Double = (width / <em>resources</em>.<em>displayMetrics</em>.xdpi).toDouble()<br>val heightInInches: Double = (height / <em>resources</em>.<em>displayMetrics</em>.ydpi).toDouble()<br><br>val screenSize = <em>hypot</em>(widthInInches, heightInInches)</pre><p>In both cases, our program works fine. My device screen size is 6.3. The output I’ve got is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*7R-dGQxvncx3Wh3kAgtzNg.png" /><figcaption>Output</figcaption></figure><h3>Wrap Up</h3><p>In this article, we covered most of the things which confuse Android developers. Now you have a clear understanding of the pixels and the PPI, different density buckets and their specifiers, what is dp, and how it is independent of the density. You know about all the formulas and you can make your own calculations to get screen density.</p><p>In the end, we even wrote a program and performed different calculations, so you will have a clear understanding. From now you can dive deeper and explore more. Thank you for your provided time.</p><p>You can find the above source code in this <a href="https://gist.github.com/Hayk985/ba0945ef7d8da2289f07119dfa77504e">gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98b28d23260c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/cracking-android-screen-sizes-88228822-98b28d23260c">Cracking Android Screen Sizes</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>