commonMain.io.github.lyxnx.util.crypto.Hashing.kt Maven / Gradle / Ivy
@file:JvmName("Hashing")
package io.github.lyxnx.util
import kotlin.jvm.JvmName
/**
* Hashes this string to hexadecimal MD5, zero padding each byte
*
* **Note:** MD5 is very insecure and should not be used for sensitive data storage. There are numerous papers and articles
* that explain why MD5 is terrible. For sensitive data, [sha256] or [sha512] should be used instead
*/
@Deprecated("MD5 is insecure and should not be used for sensitive data storage")
public fun String.md5(): String = hash(MD5)
/**
* Hashes this string to hexadecimal SHA1, zero padding each byte
*
* **Note:** SHA1 is insecure and shouldn't be used for sensitive data if possible.
* [sha256] or [sha512] are better and much more secure alternatives for that application
*/
public fun String.sha1(): String = hash(SHA1)
/**
* Hashes this string to hexadecimal SHA256, zero padding each byte
*/
public fun String.sha256(): String = hash(SHA256)
/**
* Hashes this string to hexadecimal SHA384, zero padding each byte
*/
public fun String.sha384(): String = hash(SHA384)
/**
* Hashes this string to hexadecimal SHA512, zero padding each byte
*/
public fun String.sha512(): String = hash(SHA512)
private fun String.hash(algorithm: String): String {
val digest = when (algorithm) {
MD5 -> org.kotlincrypto.hash.md.MD5()
SHA1 -> org.kotlincrypto.hash.sha1.SHA1()
SHA256 -> org.kotlincrypto.hash.sha2.SHA256()
SHA384 -> org.kotlincrypto.hash.sha2.SHA384()
SHA512 -> org.kotlincrypto.hash.sha2.SHA512()
else -> throw IllegalArgumentException("Unknown algorithm: $algorithm")
}
return digest.digest(encodeToByteArray())
.joinToString(separator = "") { (0xFF and it.toInt()).toString(16).padStart(2, '0') }
}
internal const val MD5 = "MD5"
internal const val SHA1 = "SHA-1"
internal const val SHA256 = "SHA-256"
internal const val SHA384 = "SHA-384"
internal const val SHA512 = "SHA-512"