Cryptography

suggest change

Cryptography ensures confidentiality, integrity, authenticity, and non-repudiation in modern software systems. On the JVM, Kotlin interacts with the robust Java Cryptography Architecture (JCA) (javax.crypto and java.security), benefiting from hardware-accelerated CPU instructions (such as AES-NI).


Cryptographically Secure Randomness

Never use standard pseudo-random number generators (kotlin.random.Random or java.util.Random) for security-sensitive tokens, salts, or keys—their output is predictable. Always use java.security.SecureRandom:

import java.security.SecureRandom
import java.util.Base64

object CryptoRandom {
    private val secureRandom = SecureRandom()

    fun generateSecureBytes(length: Int): ByteArray {
        val bytes = ByteArray(length)
        secureRandom.nextBytes(bytes)
        return bytes
    }

    fun generateSecureToken(byteLength: Int = 32): String {
        val bytes = generateSecureBytes(byteLength)
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
    }
}

fun main() {
    val sessionToken = CryptoRandom.generateSecureToken(32)
    println("Secure Session Token: $sessionToken")
}

Hashing and Message Authentication (HMAC)

SHA-256 Hashing

One-way cryptographic hashes verify data integrity. Note that raw SHA-256 is not suitable for passwords (use BCrypt or Argon2 instead), but is ideal for file checksums and tamper detection:

import java.security.MessageDigest

fun sha256(input: String): String {
    val digest = MessageDigest.getInstance("SHA-256")
    val hashBytes = digest.digest(input.toByteArray(Charsets.UTF_8))
    return hashBytes.joinToString("") { "%02x".format(it) }
}

fun main() {
    val hash = sha256("Kotlin Secure Payload")
    println("SHA-256: $hash")
}

HMAC (Keyed-Hash Message Authentication Code)

HMAC signs a message with a shared secret to ensure both integrity and authenticity:

import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

class HmacSigner(secretKey: String) {
    private val keySpec = SecretKeySpec(secretKey.toByteArray(Charsets.UTF_8), "HmacSHA256")

    fun sign(data: String): ByteArray {
        val mac = Mac.getInstance("HmacSHA256")
        mac.init(keySpec)
        return mac.doFinal(data.toByteArray(Charsets.UTF_8))
    }

    fun verify(data: String, expectedSignature: ByteArray): Boolean {
        val actualSignature = sign(data)
        // Constant-time comparison prevents timing attacks!
        return MessageDigest.isEqual(actualSignature, expectedSignature)
    }
}

Symmetric Encryption with AES-GCM

When encrypting data at rest or in transit, AES-GCM (Galois/Counter Mode) is the gold standard because it provides Authenticated Encryption with Associated Data (AEAD). It protects against both eavesdropping and ciphertext tampering:

import java.security.SecureRandom
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

object AesGcmCrypto {
    private const val AES_KEY_SIZE = 256
    private const val GCM_IV_LENGTH = 12       // 96-bit IV recommended for GCM
    private const val GCM_TAG_LENGTH = 128     // 128-bit authentication tag

    fun generateSecretKey(): SecretKey {
        val keyGen = KeyGenerator.getInstance("AES")
        keyGen.init(AES_KEY_SIZE, SecureRandom())
        return keyGen.generateKey()
    }

    fun encrypt(plaintext: ByteArray, key: SecretKey): Pair<ByteArray, ByteArray> {
        val iv = ByteArray(GCM_IV_LENGTH).also { SecureRandom().nextBytes(it) }

        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(GCM_TAG_LENGTH, iv))

        val ciphertext = cipher.doFinal(plaintext)
        return Pair(iv, ciphertext)
    }

    fun decrypt(ciphertext: ByteArray, iv: ByteArray, key: SecretKey): ByteArray {
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_LENGTH, iv))
        return cipher.doFinal(ciphertext)
    }
}

fun main() {
    val key = AesGcmCrypto.generateSecretKey()
    val secretData = "TopSecretAccountDetails".toByteArray(Charsets.UTF_8)

    val (iv, ciphertext) = AesGcmCrypto.encrypt(secretData, key)
    println("Encrypted ciphertext base64: ${Base64.getEncoder().encodeToString(ciphertext)}")

    val decryptedBytes = AesGcmCrypto.decrypt(ciphertext, iv, key)
    println("Decrypted: ${String(decryptedBytes, Charsets.UTF_8)}")
}

Digital Signatures with ECDSA

Elliptic Curve Digital Signature Algorithm (ECDSA) produces compact digital signatures with high security and low CPU overhead:

import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.Signature
import java.security.spec.ECGenParameterSpec

object EcdsaSigner {
    fun generateKeyPair(): KeyPair {
        val keyPairGen = KeyPairGenerator.getInstance("EC")
        keyPairGen.initialize(ECGenParameterSpec("secp256r1"))
        return keyPairGen.generateKeyPair()
    }

    fun sign(data: ByteArray, pair: KeyPair): ByteArray {
        val signer = Signature.getInstance("SHA256withECDSA")
        signer.initSign(pair.private)
        signer.update(data)
        return signer.sign()
    }

    fun verify(data: ByteArray, signature: ByteArray, pair: KeyPair): Boolean {
        val verifier = Signature.getInstance("SHA256withECDSA")
        verifier.initVerify(pair.public)
        verifier.update(data)
        return verifier.verify(signature)
    }
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents