implement HMAC PRNG

This commit is contained in:
2025-07-24 20:51:31 +02:00
parent abd9ff96f1
commit de4c18afe3
2 changed files with 51 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package com.infendro.random
import com.infendro.bytearray.toInt
import com.infendro.hash.SHA256
import com.infendro.mac.HMAC
import kotlin.random.Random
class HMAC internal constructor() : Random() {
private val random = Default
private val hmac = HMAC(SHA256)
private var K: ByteArray
private var V: ByteArray
init {
K = ByteArray(32).also {
random.nextBytes(it)
}
V = ByteArray(32).also {
random.nextBytes(it)
}
}
fun reseed(
entropy: ByteArray,
) {
K = hmac.hash(K, V + byteArrayOf(0x00) + entropy)
V = hmac.hash(K, V)
K = hmac.hash(K, V + byteArrayOf(0x01) + entropy)
V = hmac.hash(K, V)
}
override fun nextBits(
count: Int,
): Int {
if (count !in 0..32) throw Exception()
if (count == 0) return 0
val bytes = hmac.hash(K, V)
val bits = bytes.take(4).toInt() ushr (32 - count)
K = hmac.hash(K, V + byteArrayOf(0x00))
V = hmac.hash(K, V)
return bits
}
}