All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.hashing.HashService.kt Maven / Gradle / Ivy

The newest version!
package net.dankito.utils.hashing


import net.dankito.utils.extensions.toHexString
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 convertBytesToHexString(hashStringToBytes(hashAlgorithm, stringToHash))
    }

    @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()

        return convertBytesToHexString(digestBytes)

    }

    protected open fun convertBytesToHexString(digestBytes: ByteArray): String {
        return digestBytes.toHexString()
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy