CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-utils-jvm

Ktor utilities library for JVM platform containing common utility functions, cryptographic operations, date handling, logging utilities, pipeline functionality, I/O adapters, encoding/decoding utilities, network address handling, and various platform-specific implementations for the Ktor framework.

Pending
Overview
Eval results
Files

crypto.mddocs/

Cryptography & Encoding

Cryptographic operations, encoding/decoding utilities, and secure random generation for the Ktor framework. Provides thread-safe implementations of common cryptographic operations including hashing, encoding, and nonce generation.

Capabilities

Base64 Encoding

Encode and decode data using Base64 format with support for strings, byte arrays, and I/O sources.

/**
 * Encode String in base64 format using UTF-8 character encoding
 * @return Base64 encoded string
 */
fun String.encodeBase64(): String

/**
 * Encode ByteArray in base64 format
 * @return Base64 encoded string
 */
fun ByteArray.encodeBase64(): String

/**
 * Encode Source (I/O stream) in base64 format
 * @return Base64 encoded string
 */
fun Source.encodeBase64(): String

Usage Examples:

import io.ktor.util.*

// Encode strings
val text = "Hello, World!"
val encoded = text.encodeBase64()
println(encoded) // "SGVsbG8sIFdvcmxkIQ=="

// Encode byte arrays
val bytes = byteArrayOf(1, 2, 3, 4, 5)
val encodedBytes = bytes.encodeBase64()

// Encode from I/O source
val source = buildPacket { writeText("Data to encode") }
val encodedSource = source.encodeBase64()

Base64 Decoding

Decode Base64 encoded data back to original format.

/**
 * Decode String from base64 format to UTF-8 string
 * @return Decoded UTF-8 string
 */
fun String.decodeBase64String(): String

/**
 * Decode String from base64 format to ByteArray
 * @return Decoded byte array
 */
fun String.decodeBase64Bytes(): ByteArray

/**
 * Decode Source from base64 format
 * @return Input source with decoded data
 */
fun Source.decodeBase64Bytes(): Input

Usage Examples:

import io.ktor.util.*

// Decode to string
val encoded = "SGVsbG8sIFdvcmxkIQ=="
val decoded = encoded.decodeBase64String()
println(decoded) // "Hello, World!"

// Decode to bytes
val decodedBytes = encoded.decodeBase64Bytes()

// Decode from source
val encodedSource = buildPacket { writeText(encoded) }
val decodedInput = encodedSource.decodeBase64Bytes()

Hexadecimal Encoding

Encode and decode data using hexadecimal format.

/**
 * Encode bytes as a HEX string with no spaces, newlines or 0x prefixes
 * @param bytes Byte array to encode
 * @return Hexadecimal string representation
 */
fun hex(bytes: ByteArray): String

/**
 * Decode bytes from HEX string (no spaces or 0x prefixes)
 * @param s Hexadecimal string to decode
 * @return Decoded byte array
 */
fun hex(s: String): ByteArray

Usage Examples:

import io.ktor.util.*

// Encode bytes to hex
val data = "Hello".toByteArray()
val hexString = hex(data)
println(hexString) // "48656c6c6f"

// Decode hex string to bytes
val decoded = hex("48656c6c6f")
val text = String(decoded)
println(text) // "Hello"

Hash Functions

Cryptographic hash function implementations including SHA-1 and stateful digest operations.

/**
 * Calculate SHA1 hash of byte array
 * @param bytes Input data to hash
 * @return SHA1 hash as byte array
 */
fun sha1(bytes: ByteArray): ByteArray

/**
 * Create Digest from specified hash name (expect/actual function)
 * @param name Hash algorithm name (e.g., "SHA-1", "SHA-256")
 * @return Digest instance for stateful hash calculation
 */
fun Digest(name: String): Digest

/**
 * Stateful digest interface for calculating hash values incrementally
 */
interface Digest {
    /** Add bytes to digest value */
    operator fun plusAssign(bytes: ByteArray)
    
    /** Reset digest state */
    fun reset()
    
    /** Calculate digest bytes from current state */
    suspend fun build(): ByteArray
}

Usage Examples:

import io.ktor.util.*

// Calculate SHA1 hash
val data = "Hello, World!".toByteArray()
val hash = sha1(data)
val hashHex = hex(hash)
println(hashHex) // SHA1 hash in hexadecimal

// Use stateful digest for incremental hashing
val digest = Digest("SHA-1")
digest += "Hello, ".toByteArray()
digest += "World!".toByteArray()
val incrementalHash = digest.build()
val incrementalHex = hex(incrementalHash)

// Reset and reuse digest
digest.reset()
digest += "New data".toByteArray()
val newHash = digest.build()

Nonce Generation

Generate cryptographically secure random values for security purposes.

/**
 * Generate cryptographically secure random nonce
 * @return Random nonce string
 */
fun generateNonce(): String

/**
 * Generates a nonce bytes of specified size
 * @param size Number of bytes for the nonce
 * @return ByteArray containing random nonce data
 */
fun generateNonce(size: Int): ByteArray

/**
 * Interface for nonce management
 */
interface NonceManager {
    /** Generate a new nonce */
    suspend fun newNonce(): String
    
    /** Verify if a nonce is valid */
    suspend fun verifyNonce(nonce: String): Boolean
}

/**
 * Simple nonce manager for testing that generates nonces but accepts all as valid
 */
object GenerateOnlyNonceManager : NonceManager

Usage Examples:

import io.ktor.util.*

// Generate simple nonce
val nonce = generateNonce()
println("Generated nonce: $nonce")

// Generate nonce with specific size
val nonceBytes = generateNonce(32) // 32 bytes
val customNonce = hex(nonceBytes)

// Use built-in generate-only nonce manager (for testing)
val testNonce = GenerateOnlyNonceManager.newNonce()
val isValid = GenerateOnlyNonceManager.verifyNonce("any-nonce") // Always returns true

// Use nonce manager for advanced scenarios
class SimpleNonceManager : NonceManager {
    private val usedNonces = mutableSetOf<String>()
    
    override suspend fun newNonce(): String {
        val nonce = generateNonce()
        usedNonces.add(nonce)
        return nonce
    }
    
    override suspend fun verifyNonce(nonce: String): Boolean {
        return nonce in usedNonces
    }
}

JVM-Specific Cryptography

Additional cryptographic utilities available on the JVM platform.

/**
 * Stateless nonce manager implementation with HMAC verification and timeout.
 * Every nonce provided by this manager consists of a random part, timestamp and HMAC.
 */
class StatelessHmacNonceManager(
    val keySpec: SecretKeySpec,
    val algorithm: String = "HmacSHA256",
    val timeoutMillis: Long = 60000,
    val nonceGenerator: () -> String = { generateNonce() }
) : NonceManager {
    
    /** Helper constructor that makes a secret key from ByteArray */
    constructor(
        key: ByteArray,
        algorithm: String = "HmacSHA256", 
        timeoutMillis: Long = 60000,
        nonceGenerator: () -> String = { generateNonce() }
    )
    
    override suspend fun newNonce(): String
    override suspend fun verifyNonce(nonce: String): Boolean
}

Usage Examples:

import io.ktor.util.*
import javax.crypto.spec.SecretKeySpec

// Use HMAC-based nonce manager with ByteArray key
val secretKey = "my-secret-key".toByteArray()
val nonceManager = StatelessHmacNonceManager(
    key = secretKey,
    timeoutMillis = 300_000 // 5 minutes
)

// Generate and verify nonces
val nonce = nonceManager.newNonce()
val isValid = nonceManager.verifyNonce(nonce) // true within timeout

// Use with explicit SecretKeySpec
val keySpec = SecretKeySpec(secretKey, "HmacSHA256")
val advancedManager = StatelessHmacNonceManager(
    keySpec = keySpec,
    algorithm = "HmacSHA256",
    timeoutMillis = 60000
)

Implementation Notes

  • Platform Support: Base64, hex, and basic crypto functions are available on all platforms (Common)
  • JVM Specifics: StatelessHmacNonceManager and advanced nonce generation features are JVM-only
  • Internal Constants: The library uses an internal constant NONCE_SIZE_IN_BYTES = 16 for default nonce sizing, but this is not part of the public API

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-utils-jvm

docs

attributes.md

collections.md

compression.md

conversion.md

crypto.md

datetime.md

index.md

io.md

logging.md

pipeline.md

strings.md

tile.json