Last active
February 20, 2024 19:02
-
-
Save Hayk985/a0a83ce8ae90f07be6a5445126dc14aa to your computer and use it in GitHub Desktop.
MD5 Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.MessageDigest | |
import java.security.NoSuchAlgorithmException | |
// Source - https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-1-introduction-9623ca992dc2 | |
// Our algorithm name. As there's no a predefined constant, we'll make our own :) | |
private const val MD5_ALGORITHM = "MD5" | |
// A String extension to generate a hash value | |
@Throws(NoSuchAlgorithmException::class, NullPointerException::class) | |
fun String.generateMD5Hash(): String { | |
val md = MessageDigest.getInstance(MD5_ALGORITHM) | |
val inputBytes: ByteArray = this.encodeToByteArray() | |
val hashData: ByteArray = md.digest(inputBytes) | |
return hashData.toHex() | |
} | |
// An extension to convert ByteArray to hexadecimal String representation | |
fun ByteArray.toHex(): String { | |
return joinToString("") { "%02x".format(it) } | |
} | |
fun main() { | |
// You can also use runCatching, but it will catch all the Exceptions. | |
try { | |
val inputText = "Let's encrypt this message with MD5" | |
// You should apply error handling as this function may through an exception | |
val hashValue = inputText.generateMD5Hash() | |
println("#1 Generated hash is: $hashValue") | |
val anotherInput = "Completely another message, could be song lyrics" | |
val anotherHashValue = anotherInput.generateMD5Hash() | |
println("#2 Generated hash is: $anotherHashValue") | |
} catch (e: NoSuchAlgorithmException) { | |
// In case an incorrect algorithm is passed or the algorithm is not supported | |
e.printStackTrace() | |
} catch (e: NullPointerException) { | |
// Just try passing null in MessageDigest.getInstance() | |
e.printStackTrace() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment