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

main.wisp.token.RealTokenGenerator.kt Maven / Gradle / Ivy

There is a newer version: 2024.09.20.215132-bd5c0c5
Show newest version
package wisp.token

import wisp.token.TokenGenerator.Companion.CANONICALIZE_LENGTH_MAX
import wisp.token.TokenGenerator.Companion.CANONICALIZE_LENGTH_MIN
import wisp.token.TokenGenerator.Companion.indexToChar
import java.security.SecureRandom
import kotlin.experimental.and

private const val REAL_TOKEN_GENERATOR_BIT_MASK = 31.toByte()

class RealTokenGenerator : TokenGenerator {
    private val random = SecureRandom()

    override fun generate(label: String?, length: Int): String {
        require(length in CANONICALIZE_LENGTH_MIN..CANONICALIZE_LENGTH_MAX) {
            "unexpected length: $length"
        }

        val byteArray = ByteArray(length)
        random.nextBytes(byteArray)

        val result = CharArray(length)
        for (i in 0 until length) {
            result[i] = indexToChar[(byteArray[i] and REAL_TOKEN_GENERATOR_BIT_MASK).toInt()]
        }

        return String(result)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy