package com.jttools.datacontrol.data

import java.security.MessageDigest
import java.security.SecureRandom

/** Hachage salé (SHA-256) du mot de passe de verrouillage — jamais stocké en clair. */
object PasswordHasher {
    private const val SALT_BYTES = 16

    fun newSalt(): String {
        val bytes = ByteArray(SALT_BYTES)
        SecureRandom().nextBytes(bytes)
        return bytes.toHex()
    }

    fun hash(password: String, saltHex: String): String {
        val digest = MessageDigest.getInstance("SHA-256")
        digest.update(saltHex.toByteArray(Charsets.UTF_8))
        return digest.digest(password.toByteArray(Charsets.UTF_8)).toHex()
    }

    private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
}
