<?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 Hossein Kheirollahpour on Medium]]></title>
        <description><![CDATA[Stories by Hossein Kheirollahpour on Medium]]></description>
        <link>https://medium.com/@hossein_kheirollahpour?source=rss-a581f031f021------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oabC57_gShi11thAr-tNsA.jpeg</url>
            <title>Stories by Hossein Kheirollahpour on Medium</title>
            <link>https://medium.com/@hossein_kheirollahpour?source=rss-a581f031f021------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:28:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hossein_kheirollahpour/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[Implementing Authentication with JWT in Android (without using a library)]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/implementing-authentication-with-jwt-in-android-without-using-a-library-5b01ea53a9e9?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b01ea53a9e9</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[elliptic-curve]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 10:51:49 GMT</pubDate>
            <atom:updated>2023-12-28T10:51:49.211Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone!</p><p>I hope you are doing well… Today, I want to teach you how to implement <strong>JWT</strong> in <strong>Android</strong> without using any external libraries.</p><p>As you know, there are many libraries available for using <strong>JWT</strong>, but since it follows a standard, its implementation is fixed and does not require the use of libraries and their subsequent updates. Another advantage is that it prevents the addition of dependencies to your project and ultimately, you will gain a deeper understanding of the topic. First, I will give you a brief explanation of the <strong>JWT</strong> structure and then move on to its practical implementation in <strong>Android</strong>. All the source codes are available at <a href="https://github.com/HosseinDevPro/JwtGeneratorApp">this GitHub link</a>. (<a href="https://auth0.com/docs/secure/tokens/json-web-tokens">JWT official document link</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*L9BuxUENz11V_8CH-S5dxg.png" /></figure><h3>What is JSON Web Token or JWT?</h3><p><strong>JWT</strong> stands for JSON Web Token, which is essentially a standard authentication mechanism used in websites and applications. It is composed of three main parts: <strong>Header</strong>, <strong>Payload</strong>, and <strong>Signature</strong>.</p><ul><li><strong>Header</strong>: Contains information in base64 encoded <em>JSON</em> about the type of token (usually <strong>JWT</strong>) and the encryption algorithm used (such as <em>HS256</em> or <em>RS256</em>).</li></ul><p><em>It includes the algorithm type with the key ‘alg’; content type with the key ‘cty’; token type with the key ‘typ’; and key ID with the key ‘kid’.</em></p><ul><li><strong>Payload</strong>: This section contains claims, which are base64 encoded <em>JSON</em> information about the user or other necessary information for authentication. This information can include user ID, username, token expiration date, etc.</li></ul><p><em>It includes a token issuer with the key ‘iss’; a token subject with the key ‘sub’; a token audience with the key ‘aud’; token expiration time in seconds with the key ‘exp’; a time before which the token should not be accepted in seconds with the key ‘nbf’; the time at which the token was issued in seconds with the key ‘iat’; and a unique token identifier with the key ‘jti’.</em></p><ul><li><strong>Signature</strong>: This part is created using the algorithm specified in the Header and either a secret key (in <em>HMAC</em>-based algorithms) or a public/private key pair (in <em>RSA</em> or <em>ECDSA</em>-based algorithms). The token’s signature ensures that the message has not been altered and comes from a credible source.</li></ul><p><em>It includes The encrypted value of the string (header.payload).</em></p><p>&gt; Finally, the complete and integrated structure of a <strong>JWT</strong> token looks like this:</p><pre>val jwt = &quot;$header.$payload.$signature&quot;</pre><h3>What’s our scenario?</h3><p>Imagine we want to authenticate between an <strong>Android</strong> client and a server. We do this by creating a pair of keys and sending the public key to the server. In another request, the server sends us some information with which we create a <strong>JWT</strong> token. We encrypt the Signature part using the private key generated in the first step, and finally, we send the completed token back to the server. On the server side, it can verify the Signature and (<strong><em>Header.Payload</em></strong>) using the public key previously sent to it, thus confirming the authentication.</p><h3>Let’s move on to the implementation :)</h3><ol><li><strong>Key Generation</strong>: The algorithm we’ve chosen for encrypting the third part of the signature, <strong><em>EC</em></strong> or elliptic curve with a key length of 256, is known in the standard <strong><em>ES256</em></strong>. We send the public key to the server and keep the private key for encrypting in step 4. The code for key generation is as follows.</li></ol><pre>val keyPairGenerator = KeyPairGenerator.getInstance(&quot;EC&quot;)<br>keyPairGenerator.initialize(ECGenParameterSpec(&quot;secp256r1&quot;))<br>val keyPair = keyPairGenerator.generateKeyPair()<br>val publicKey = keyPair.public as ECPublicKey // Send to server<br>val privateKey = keyPair.private as ECPrivateKey // Use for signing in step 4</pre><p>2. <strong>Generating Claims</strong>: We use the following attributes to generate the header and payload.</p><pre>val header = JwtHeaderBuilder().run {<br>    algorithm(&quot;ES256&quot;) // elliptic curve with key size 256<br>    type(&quot;JWT&quot;) // Needed<br>    contentType(&quot;application/json&quot;) // Optional<br>    keyId(&quot;UniqueKeyId&quot;) // Optional<br>}.build()</pre><pre>val currentTime = System.currentTimeMillis() / 1000 // current time in seconds<br>val payload = JwtPayloadBuilder().run {<br>    issuer(&quot;Hossein KheirollahPour&quot;)<br>    subject(&quot;Payment&quot;)<br>    audience(&quot;https://blubank.com&quot;)<br>    issuedAt(currentTime)<br>    notBefore(currentTime)<br>    expirationTime(currentTime + 3600)// Expires after 1 hour<br>    jwtID(&quot;UniqueJwtId1234&quot;)<br>}.build()</pre><p>3. <strong>Preparing Data from JSON header, payload</strong>: In this part, we make base64 encode the <em>JSON</em> of each section, combine them, and prepare the final data for encryption in the next step.</p><pre>val headerBytes = Base64.getUrlEncoder().withoutPadding().encodeToString(header.toByteArray(StandardCharsets.UTF_8)).toByteArray(StandardCharsets.UTF_8)<br>val payloadBytes = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.toByteArray(StandardCharsets.UTF_8)).toByteArray(StandardCharsets.UTF_8)<br>val contentBytes = ByteArray(headerBytes.size + 1 + payloadBytes.size)<br>System.arraycopy(headerBytes, 0, contentBytes, 0, headerBytes.size)<br>contentBytes[headerBytes.size] = &#39;.&#39;.code.toByte()<br>System.arraycopy(payloadBytes, 0, contentBytes, headerBytes.size + 1, payloadBytes.size)</pre><p>4. <strong>Preparing the Signature Data</strong>: In this part, using the <em>SHA256ECDSA</em> algorithm and the private key generated in the first step, we sign the data from the previous step.</p><p>Note: Once we have prepared the data, we convert it to the correct format using the <em>DERToJOSE</em> function. To avoid elongating the code here, I haven’t detailed it, but this part is included in the <a href="https://github.com/HosseinDevPro/JwtGenerationApp/blob/f8f5f5ff59538db7283feeb3b9470b3396c2f0f5/app/src/main/java/com/hkh/jwtgenerationapp/jwt/JwtUtil.kt#L93">source code section</a>.</p><pre>val signatureInstance = Signature.getInstance(&quot;SHA256withECDSA&quot;)<br>signatureInstance.initSign(privateKey)<br>signatureInstance.update(contentBytes)<br>val  signatureBytes = signatureInstance.sign()<br><br>val convertedSignatureBytes = DERToJOSE(signatureBytes) // This function exist in source code<br>val signature = Base64.getUrlEncoder().withoutPadding().encodeToString(convertedSignatureBytes)</pre><p>5. <strong>Creating the Final Token</strong>: In this part, the data generated in the previous steps are concatenated together.</p><pre>val jwt = String.format(&quot;%s.%s.%s&quot;, header, payload, signature)</pre><p>Great job… We finally created the <strong>JWT</strong> token :)</p><p>In the end, you can extract your public key using the code below and verify or test your <strong>JWT</strong> token on websites like <a href="https://token.dev/">this site</a> and <a href="https://jwt.io/#debugger-io">this site</a> or <a href="https://jwt.rocks/">this site</a> to see if it has been generated correctly.</p><pre>@RequiresApi(Build.VERSION_CODES.O)<br>fun convertECPublicKeyToPEM(ecPublicKey: ECPublicKey): String {<br>    val base64Encoded = Base64.getEncoder().encodeToString(ecPublicKey.encoded)<br>    return buildString {<br>        append(&quot;-----BEGIN PUBLIC KEY-----\n&quot;)<br>        append(base64Encoded.chunked(64).joinToString(&quot;\n&quot;))<br>        append(&quot;\n-----END PUBLIC KEY-----\n&quot;)<br>    }<br>}</pre><p>There’s also a second verification method, for which I have written a function that you can use if you wish:</p><pre>@RequiresApi(Build.VERSION_CODES.O)<br>fun manualVerifyJWT(publicKey: ECPublicKey, jwt: String): Boolean {<br>    val parts = jwt.split(&quot;.&quot;)<br>    if (parts.size != 3) return false<br>    val signature = Signature.getInstance(&quot;SHA256withECDSA&quot;)<br>    signature.initVerify(publicKey)<br>    signature.update(&quot;${parts[0]}.${parts[1]}&quot;.toByteArray())<br>    return signature.verify(Base64.getUrlDecoder().decode(parts[2]))<br>}</pre><p>I’ll put a screenshot of the <strong>Android</strong> app output from <strong>GitHub</strong> for you to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObkT4MatZ_bAwDIcyLaFMw.png" /></figure><p>Finally, I thank you again for reading and using this article. I hope it has helped deepen your understanding of how <strong>JWT</strong> is produced and that you can use the codes without the need for a library. I look forward to your comments, which will undoubtedly contribute to my growth and improvement.</p><p>In the end thanks from dear <a href="https://medium.com/u/a62c5e182e67">Afshin Honari</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b01ea53a9e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of secure encryption against attacks in financial Android applications]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/implementation-of-secure-encryption-against-attacks-in-financial-android-applications-51a473f4d42e?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a473f4d42e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-hacks]]></category>
            <category><![CDATA[antihacking]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 13:12:24 GMT</pubDate>
            <atom:updated>2023-12-03T17:35:47.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello there,</p><p>Considering the positive reception of the previous articles, I’ve decided to write a new article that serves as a great complement to <a href="https://medium.com/@hossein_kheirollahpour/implementation-of-symmetric-encryption-in-android-d2e5d04686d2">this article</a>. This new article will include a more comprehensive implementation of secure encryption coupled with biometrics, which is resilient against hacker attacks. I’ll be writing this article for you and providing the <a href="https://github.com/HosseinDevPro/SecureBankingApp">source code link on GitHub</a>.</p><p>Now, let’s get to the heart of the matter:</p><p>The main goal of this article is to implement encryption to the highest possible degree of resistance against <a href="https://securitycafe.ro/2022/02/01/root-detection-and-ssl-pinning-bypass/#1-frida">Frida</a> attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*dUsOdX01I9bo_CP78ZnBdA.jpeg" /></figure><h3>Frida</h3><p>What is Frida? Frida is a dynamic code instrumentation toolkit that allows reverse engineers to inject snippets of JavaScript or library into native apps on iOS and Android (but not only) and to debug a running process. In other words, it allows you to inject your custom JavaScript code and programmatically and interactively inspect and change running processes. As Frida performs dynamic instrumentation, it doesn’t need access to the application’s source code. Furthermore, if you don’t have a rooted or Jailbroken device, don’t worry, Frida works also on normal devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*yx47V6KBq3MgozcQm5U3Wg.png" /></figure><h3>Bypass Android Biometric Authentication Attack</h3><p>One of the attacks carried out with Frida is the ‘<a href="https://book.hacktricks.xyz/mobile-pentesting/android-app-pentesting/bypass-biometric-authentication-android">Biometric Authentication Bypass Attack</a>.’ To put it briefly, this attack triggers the <em>onAuthenticationSucceeded</em> method in <em>BiometricPrompt</em> using a JavaScript code (<a href="https://github.com/HosseinDevPro/SecureBankingApp/tree/main/frida-scripts">Attack Source Code Link on GitHub</a>). Now, if you fail to pass the <em>BiometricPrompt.CryptoObject(cipher)</em> when opening the biometric object, and do not utilize the cipher available in <em>BiometricPrompt.AuthenticationResult </em>During encryption and decryption, you become vulnerable to this attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DEoCr0IKMInN-G-gaPhkA.png" /></figure><p>Let’s move on to an awesome implementation where everything is securely coupled and not susceptible to bypassing these attacks :)</p><h3>Creating a Secure Key with Features</h3><ol><li>Our chosen algorithm is AES, recognized as one of the most complex and secure algorithms in the IT world. Additionally, we generate this key using AndroidKeyStore. As you may know, KeyStore is a secure enclave that significantly restricts access to the generated key:</li></ol><pre>KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, &quot;AndroidKeyStore&quot;)</pre><p>2. For this key, we choose a name. Additionally, we assign our goal of encryption and decryption to this key:</p><pre>KeyGenParameterSpec.Builder = KeyGenParameterSpec.Builder(<br>    &quot;sample_symmetric_key_alias&quot;, <br>    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT<br>)</pre><p>3. We set the size of this key, along with block mode and the encryption padding type:</p><pre>setKeySize(KEY_SIZE)<br>setBlockModes(KeyProperties.BLOCK_MODE_GCM)<br>setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)</pre><p>4. This key should only be accessible through biometrics. Therefore, when performing encryption or decryption, the user must have an active fingerprint. We ensure the user’s ownership of the device through the system OS’s fingerprint dialog prompt:</p><pre>setUserAuthenticationRequired(true)</pre><p>5. In each encryption operation, a random text is generated to prevent possible attacks:</p><pre>setRandomizedEncryptionRequired(true)</pre><p>6. If a new fingerprint is added to the device, this key becomes invalid:</p><pre>setInvalidatedByBiometricEnrollment(true)</pre><p>7. During decryption, the screen must be locked, and if the device supports StrongBox, the key generation process must be performed inside it (having two key creation spaces: <a href="https://source.android.com/docs/security/features/keystore">TEE and StrongBox</a>):</p><pre>val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)<br>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {<br>   setUnlockedDeviceRequired(true)<br>   if(hasStrongBox) setIsStrongBoxBacked(true)<br>}</pre><h3>A) Secure Biometrically Coupled Encryption:</h3><p>Firstly, we need to initialize an initial <em>cipher</em> using the key generated in the previous step:</p><pre>val encryptCipher: Cipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;)<br>val secretKey: SecretKey = keyStoreManager.getKeyWithAlias(&quot;sample_symmetric_key_alias&quot;)<br>encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey)</pre><p>Next, we need to create a crypto object using this initialized <em>cipher</em> and pass it to <em>BiometricPrompt</em>:</p><pre>val prompt = BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), AuthenticationCallback(out))<br>val info = PromptInfo.Builder()<br>    .setTitle(&quot;title&quot;)<br>    .setNegativeButtonText(&quot;description&quot;)<br>    .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)<br>    .build()<br>val crypto = BiometricPrompt.CryptoObject(encryptCipher)<br>prompt.authenticate(info, crypto)</pre><p>Now, after the biometric authentication is successful, in the <em>onAuthenticationSucceeded</em> callback, we should use the <em>cipher</em> value from the <em>CryptoObject</em>:</p><pre>override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {<br>    super.onAuthenticationSucceeded(result)<br>    val newEncryptCipher = result.cryptoObject?.cipher<br>    ...<br>}</pre><p>We use the <em>cipher</em> from the previous step for the encryption part:</p><pre>val initializationVector = newEncryptCipher?.iv // we must save it<br>val plainText = ... // user input text<br>val cipheredBytes = newEncryptCipher?.doFinal(plaintext.toByteArray(StandardCharsets.UTF_8))<br>val base64EncryptedText = Base64.getEncoder().encode(cipheredBytes)</pre><p>At this stage, our encryption process concludes, and we can store the encrypted value in a Base64-encoded or Hex-encoded format.</p><p>Note: It’s crucial to store the value of the initialization vector (IV) at this stage (I’ve implemented a method in my source code to store it, which you can utilize).</p><h3>B) Secure Biometrically Coupled Decryption:</h3><p>In this section, we also need to initialize an initial <em>cipher</em> using the key we generated in the previous step and the stored initialization vector (IV):</p><pre>val decryptCipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;)<br>val secretKey = keyStoreManager.getKeyWithAlias(&quot;sample_symmetric_key_alias&quot;)<br>decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, initializationVector))</pre><p>After that, we need to create a crypto object using this initialized <em>cipher</em> and pass it to <em>BiometricPrompt</em>:</p><pre>val prompt = BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), AuthenticationCallback(out))<br>val info = PromptInfo.Builder()<br>    .setTitle(&quot;title&quot;)<br>    .setNegativeButtonText(&quot;description&quot;)<br>    .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)<br>    .build()<br>val crypto = BiometricPrompt.CryptoObject(decryptCiphr)<br>prompt.authenticate(info, crypto)</pre><p>Now, after the biometric authentication is successful, in the <em>onAuthenticationSucceeded</em> callback, we should use the <em>cipher</em> value from the <em>CryptoObject</em>:</p><pre>override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {<br>    super.onAuthenticationSucceeded(result)<br>    val newDecryptCipher = result.cryptoObject?.cipher<br>    ...<br>}</pre><p>After decoding the stored encrypted text from the encryption step and utilizing the <em>cipher</em> from the previous step, we perform the decryption:</p><pre>val encryptedBytes = Base64.getDecoder().decode(base64EncryptedText)<br>val text = newDecryptCipher?.doFinal(encryptedBytes)<br>val plaintext = String(text, StandardCharsets.UTF_8)</pre><p>At this stage, our decryption process concludes, and we can use the resulting text in various parts as needed.</p><p>In the end, we have learned how to generate a secure and symmetric key with various security features in Android. Subsequently, we have comprehended the process of encryption and decryption using that key, which is entirely coupled with biometrics and resilient against Frida attacks. I’m looking forward to your constructive feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51a473f4d42e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of irreversible algorithms or HASH in Android]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/implementation-of-irreversible-algorithms-or-hash-in-android-fb3deb43af31?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb3deb43af31</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-security]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 19:52:57 GMT</pubDate>
            <atom:updated>2023-11-17T19:57:41.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6e0CC2G30w3d0gNDgbf3w.png" /></figure><p>In this type of algorithm, a key isn’t generated. Instead, a user-input text is taken, and ultimately, based on the desired size, a unique text (commonly referred to as a “hash”) is created. It becomes impossible to retrieve the original text from the generated hash, making it completely irreversible and non-retrievable. The most common usage of these algorithms is storing hashed passwords of users on servers or clients. (Sample project <a href="https://github.com/HosseinDevPro/AndroidDataSecurity">Github link</a> , <a href="https://medium.com/@hossein_kheirollahpour/data-security-in-android-5561ed75f24a">Main article link</a>)</p><p>Let’s move on to implementation…</p><p>We use the SHA algorithm to generate a hash text. Our desired size is 256, which ultimately performs the hash text generation task for us through the following extension function:</p><pre>fun String.sha256(): ByteArray {<br> val digest = MessageDigest.getInstance(&quot;SHA-256&quot;) <br> return digest.digest(this.toByteArray())<br>}</pre><p>Now, what’s the use of this hashed text? It’s a good question… Let’s provide a practical example.</p><p>Imagine you’re receiving a password from the user on the client side, and you want to store it. Now, if you store the raw text, you’re basically serving hackers a vulnerable target. So, what’s the solution? We can store the hashed password on the client side. Then, when the user enters their raw password, we can hash it and compare it with the stored hashed text. This way, we can verify the correctness of the entered password by the user. However, I should remind you that storing hashed passwords on the server side is a common practice.</p><p>Now, based on the discussion above, you can use the following code to check the entered password by the user:</p><pre>fun verifyHashedMessage(plainData: String, hashedData: ByteArray): Boolean {<br>    return hashedData.contentEquals(plainData.sha256())<br>}</pre><p>In this article, I’ve also aimed to explain the discussion of irreversible encryption algorithms in a practical manner, accompanied by code snippets for your convenience. I hope it has been useful for you. I look forward to your comments and feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb3deb43af31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Asymmetric Algorithm in Android]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/implementation-of-asymmetric-algorithm-in-android-45cbe0f128e6?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/45cbe0f128e6</guid>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[android-programming]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[elliptic-curve]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 12:06:24 GMT</pubDate>
            <atom:updated>2023-12-03T17:36:00.342Z</atom:updated>
            <content:encoded><![CDATA[<p>In these types of algorithms, two keys are created: one for encryption and another for decryption. Unlike symmetric algorithms, encryption and decryption keys are different. Similar to symmetric algorithms, our aim is to maximize the security of the keys. (Sample project <a href="https://github.com/HosseinDevPro/AndroidDataSecurity">Github link</a> , <a href="https://medium.com/@hossein_kheirollahpour/data-security-in-android-5561ed75f24a">Main article link</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkcVp9xVcBtERLTvmqk3Ig.png" /></figure><p>Let’s move on to implementation…</p><ol><li>Our chosen asymmetric algorithm is EC, which is among the well-known and recognized algorithms. We generate this key using AndroidKeyStore:</li></ol><pre>KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, &quot;AndroidKeyStore&quot;)</pre><p>2. We select a name for this key. Additionally, we assign our goal of signing and verification to this key:</p><pre>KeyGenParameterSpec.Builder(<br>    &quot;sample_asymmetric_key_alias&quot;,<br>    KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY<br>)</pre><p>3. We set the key length and the type of digest:</p><pre>setKeySize(256)<br>setDigests(KeyProperties.DIGEST_SHA256)</pre><p>4. We set a parameter to make this key accessible only through biometrics. Therefore, when signing and verifying, the user must have an active fingerprint. We use the OS’s fingerprint dialog prompt to ensure the user’s ownership of the device:</p><pre>setUserAuthenticationRequired(true)</pre><p>5. Each time a signature is generated, a random encrypted text is created to prevent potential attacks:</p><pre>setRandomizedEncryptionRequired(true)</pre><p>6. We set the precise type of the standard EC key generation algorithm:</p><pre>setAlgorithmParameterSpec(ECGenParameterSpec(&quot;secp256r1&quot;))</pre><p>7. The validity period of the key after a successful biometric authentication:</p><pre>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R) { <br>    setUserAuthenticationParameters(10, KeyProperties.AUTH_BIOMETRIC_STRONG) <br>} else { <br>    setUserAuthenticationValidityDurationSeconds(10) <br>}</pre><p>8. If a new fingerprint is added to the device, this key becomes invalidated:</p><pre>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>    setInvalidatedByBiometricEnrollment(true)<br>}</pre><p>9. During decryption, the screen must be locked, and if the device supports StrongBox, the key generation process must occur inside it (having two key creation spaces: TEE, StrongBox):</p><pre>val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)<br>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {     <br>    setUnlockedDeviceRequired(true)     <br>    if(hasStrongBox) setIsStrongBoxBacked(true) <br>}</pre><ul><li>In the next step, we use the following code for signing:</li></ul><pre>val plainMessage = ... // user input text<br>val signature = Signature.getInstance(&quot;SHA256withECDSA&quot;).run {<br>    initSign(getPrivateKey())<br>    update(plainMessage.toByteArray())<br>    sign()<br>}</pre><ul><li>We also use the following code to verify:</li></ul><pre>val plainMessage = ... // user input text<br>val signature = ... // signed message of user input<br>val isVerified = Signature.getInstance(&quot;SHA256withECDSA&quot;).run {<br>    initVerify(getPublicKey())<br>    update(plainMessage.toByteArray())<br>    verify(signature.toByteArray())<br>}</pre><p>In conclusion, we learned how to generate a secure asymmetric key with various security features in Android. Additionally, we learned the process of signing and verifying using the combination of these keys. If you have further questions or need more assistance, feel free to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45cbe0f128e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Symmetric Algorithm in Android]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/implementation-of-symmetric-encryption-in-android-d2e5d04686d2?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e5d04686d2</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[symmetric-encryption]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 20:02:05 GMT</pubDate>
            <atom:updated>2023-12-03T17:36:09.468Z</atom:updated>
            <content:encoded><![CDATA[<p>In these algorithms, a single key is generated, enabling us to perform encryption on the Android client. Later, decryption must also be performed using the same key. Our goal is to maximize the security of our key. (Sample project <a href="https://github.com/HosseinDevPro/AndroidDataSecurity">Github link</a> , <a href="https://medium.com/@hossein_kheirollahpour/data-security-in-android-5561ed75f24a">Main article link</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*13O3rZCk72xm7sA5zBWgeg.png" /></figure><p>Let’s move on to implementation…</p><ol><li>Our chosen algorithm is AES, recognized as one of the most complex and secure algorithms in the IT world. Additionally, we generate this key using AndroidKeyStore. As you may know, KeyStore is a secure enclave that significantly restricts access to the generated key:</li></ol><pre>KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, &quot;AndroidKeyStore&quot;)</pre><p>2. For this key, we choose a name. Additionally, we assign our goal of encryption and decryption to this key:</p><pre>KeyGenParameterSpec.Builder = KeyGenParameterSpec.Builder(<br>    &quot;sample_symmetric_key_alias&quot;, <br>    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT<br>)</pre><p>3. We set the size of this key, along with block mode and the encryption padding type:</p><pre>setKeySize(KEY_SIZE)<br>setBlockModes(KeyProperties.BLOCK_MODE_GCM)<br>setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)</pre><p>4. This key should only be accessible through biometrics. Therefore, when performing encryption or decryption, the user must have an active fingerprint. We ensure the user’s ownership of the device through the system OS’s fingerprint dialog prompt:</p><pre>setUserAuthenticationRequired(true)</pre><p>5. In each encryption operation, a random text is generated to prevent possible attacks:</p><pre>setRandomizedEncryptionRequired(true)</pre><p>6. The validity period of the key after successful biometric verification:</p><pre>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R) {<br>   setUserAuthenticationParameters(10, KeyProperties.AUTH_BIOMETRIC_STRONG)<br>} else {<br>   setUserAuthenticationValidityDurationSeconds(10)<br>}</pre><p>7. If a new fingerprint is added to the device, this key becomes invalid:</p><pre>setInvalidatedByBiometricEnrollment(true)</pre><p>8. During decryption, the screen must be locked, and if the device supports StrongBox, the key generation process must be performed inside it (having two key creation spaces: TEE and StrongBox):</p><pre>val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)<br>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {<br>   setUnlockedDeviceRequired(true)<br>   if(hasStrongBox) setIsStrongBoxBacked(true)<br>}</pre><ul><li>In the next step, we use the following code for encryption:</li></ul><pre>val plainText = ... // user input text<br>val plainBytes = plainText.toByteArray(StandardCharsets.UTF_8)<br>val key = keyStoreManager.getKeyWithAlias(KEY_ALIAS_SYMMETRIC)<br>val cipher = Cipher.getInstance(AES_GCM_NOPADDING)<br>cipher.init(Cipher.ENCRYPT_MODE, key)<br>val initailVector = cipher.iv<br>val encryptedBytes = cipher.doFinal(plainBytes)</pre><ul><li>We also use the following code to decrypt:</li></ul><pre>val encryptedBytes = ... // encrypted byte array<br>val key = keyStoreManager.getKeyWithAlias(KEY_ALIAS_SYMMETRIC)<br>val spec = GCMParameterSpec(AUTHENTICATION_TAG_SIZE, iv)<br>val cipher = Cipher.getInstance(AES_GCM_NOPADDING)<br>cipher.init(Cipher.DECRYPT_MODE, key, spec)<br>val decryptedBytes = cipher.doFinal(encryptedBytes)<br>val palinText = String(decryptedBytes, StandardCharsets.UTF_8)</pre><p>In conclusion, we&#39;ve learned how to generate a secure symmetric key with various security features. Additionally, we&#39;ve covered the process of encrypting and decrypting using that key. If you have further questions or if there&#39;s anything specific you&#39;d like to explore or clarify, feel free to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e5d04686d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Security in Android]]></title>
            <link>https://medium.com/@hossein_kheirollahpour/data-security-in-android-5561ed75f24a?source=rss-a581f031f021------2</link>
            <guid isPermaLink="false">https://medium.com/p/5561ed75f24a</guid>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[decryption]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Hossein Kheirollahpour]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 15:23:06 GMT</pubDate>
            <atom:updated>2023-11-17T19:53:29.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4I4xtH640L_EU4cjLgfiLw.jpeg" /></figure><p>Hello! I hope you’re doing well. In this article, I aim to provide a concise and practical overview of data security in Android. Initially, I’ll give a brief explanation of encryption algorithms, followed by the implementation of each method in Android.</p><p>All implementations are available in a single Android project on <a href="https://github.com/HosseinDevPro/AndroidDataSecurity">this GitHub link</a> for your reference. Due to the extensive content, I’ve dedicated a separate article to each implementation, and you can find their links at the end of this article.</p><h3>Data Encryption Methods:</h3><p>In any software, data encryption holds special importance, and Android applications are no exception. Considering the diverse tasks performed in Android, various encryption methods can be employed. Generally, encryption methods fall into two categories: reversible (symmetric/asymmetric) and irreversible (hash).</p><h3>1. Reversible Algorithms</h3><p>Reversible algorithms, also known as symmetric algorithms, encrypt and decrypt text in a way that the encrypted text can be precisely reversed to the original text using decryption algorithms. For enhanced security in Android, we utilize the AndroidKeyStore to generate keys. These algorithms are further divided into symmetric and asymmetric.</p><p><strong><em>— Symmetric Algorithms:</em></strong><em><br></em>These algorithms use the same key for both encryption and decryption. In this article, we delve into the implementation of the <strong>AES</strong> algorithm using AndroidKeyStore.</p><p><strong><em>— Asymmetric Algorithms:<br></em></strong>These algorithms use different keys for encryption and decryption. This article covers the implementation of the <strong>EC</strong> algorithm with AndroidKeyStore.</p><h3>2. Irreversible Algorithms</h3><p>Irreversible algorithms, also known as hash functions, encrypt text in a way that it cannot be reversed to the original text. In this article, we discuss the implementation of the <strong>SHA</strong> algorithm in Android.</p><p>Now, let’s move on to the core content and the implementation of the aforementioned methods:</p><p><strong>1. </strong><a href="https://medium.com/@hossein_kheirollahpour/implementation-of-symmetric-encryption-in-android-d2e5d04686d2"><strong>Implementation of Symmetric Encryption in Android</strong></a></p><p><strong>2. </strong><a href="https://medium.com/@hossein_kheirollahpour/implementation-of-asymmetric-algorithm-in-android-45cbe0f128e6"><strong>Implementation of Asymmetric Algorithms in Android</strong></a></p><p><strong>3. </strong><a href="https://medium.com/@hossein_kheirollahpour/implementation-of-irreversible-algorithms-or-hash-in-android-fb3deb43af31"><strong>Implementation of Hash Algorithms in Android</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5561ed75f24a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>