net.dankito.utils.hashing.HashService.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
package net.dankito.utils.hashing
import net.dankito.utils.io.FileUtils
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.charset.Charset
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
open class HashService(protected val fileUtils: FileUtils = FileUtils()) {
companion object {
val DefaultDigestCharset: Charset = Charset.forName("UTF-8")
}
@Throws(NoSuchAlgorithmException::class)
open fun hashString(hashAlgorithm: HashAlgorithm, stringToHash: String,
charset: Charset = DefaultDigestCharset): String {
return String(hashStringToBytes(hashAlgorithm, stringToHash), charset)
}
@Throws(NoSuchAlgorithmException::class)
open fun hashStringToBytes(hashAlgorithm: HashAlgorithm, stringToHash: String,
charset: Charset = DefaultDigestCharset): ByteArray {
val messageDigest = MessageDigest.getInstance(hashAlgorithm.algorithmName)
val stringToHashBytes = stringToHash.toByteArray(charset)
messageDigest.update(stringToHashBytes)
return messageDigest.digest()
}
@Throws(NoSuchAlgorithmException::class, IOException::class, FileNotFoundException::class)
open fun getFileHash(hashAlgorithm: HashAlgorithm, file: File): String {
val messageDigest = MessageDigest.getInstance(hashAlgorithm.algorithmName)
fileUtils.forEachBlock(file) { buffer, _ ->
messageDigest.update(buffer)
}
val digestBytes = messageDigest.digest()
val hexString = StringBuilder()
for(i in 0 until digestBytes.size) {
hexString.append(String.format("%02x", (0xFF and digestBytes[i].toInt())))
}
return hexString.toString()
}
}