Implementation of irreversible algorithms or HASH in Android

Hossein Kheirollahpour
2 min readNov 17, 2023

--

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 Github link , Main article link)

Let’s move on to implementation…

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:

fun String.sha256(): ByteArray {
val digest = MessageDigest.getInstance("SHA-256")
return digest.digest(this.toByteArray())
}

Now, what’s the use of this hashed text? It’s a good question… Let’s provide a practical example.

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.

Now, based on the discussion above, you can use the following code to check the entered password by the user:

fun verifyHashedMessage(plainData: String, hashedData: ByteArray): Boolean {
return hashedData.contentEquals(plainData.sha256())
}

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.

--

--