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

pto.0.2.0.source-code.Models.kt Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
package se.wollan.crypto

import kotlin.random.Random

@JvmInline
value class SecretKey(val value: ByteArray) {

    init {
        require(value.size == LEN_BYTES) { "key length must be $LEN_BYTES bytes / ${LEN_BYTES * 8} bits (not ${value.size} bytes)" }
    }

    override fun toString(): String = value.toHexString()

    fun clear() {
        for (i in value.indices)
            value[i] = 0
    }

    fun copy() = SecretKey(value.copyOf())

    companion object {
        const val LEN_BYTES = 32

        fun fromHex(hex: String) = SecretKey(hex.fromHexString())

        fun tryCreate(hex: CharArray): SecretKey? = runCatching { fromHex(String(hex)) }.getOrNull()
    }
}

@JvmInline
internal value class Salt(val value: ByteArray) {
    init {
        require(value.size == LEN_BYTES) { "salt must be ${SecretKey.LEN_BYTES} bytes / ${SecretKey.LEN_BYTES * 8} bits (not ${value.size} bytes)" }
    }

    override fun toString(): String = value.toHexString()

    companion object {
        const val LEN_BYTES = 16

        fun random(random: Random) = Salt(random.nextBytes(LEN_BYTES))

        fun fromHex(hex: String) = Salt(hex.fromHexString())
    }
}

@JvmInline
value class Pincode(val value: CharArray) {
    init {
        require(value.size in 6..256) { "invalid pincode length: ${value.size}" }
    }

    fun clear() {
        for (i in value.indices)
            value[i] = ' '
    }

    companion object {
        fun fromString(s: String) = Pincode(s.toCharArray())

        fun tryCreate(value: CharArray) = runCatching { Pincode(value) }.getOrNull()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy