Skip to content

Commit

Permalink
Sample entropy from more sources
Browse files Browse the repository at this point in the history
  • Loading branch information
t-bast committed Apr 22, 2021
1 parent 5daa66d commit 1c31cf7
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions eclair-core/src/main/scala/fr/acinq/eclair/crypto/WeakRandom.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import org.bouncycastle.crypto.digests.{SHA1Digest, SHA256Digest}
import org.bouncycastle.crypto.engines.ChaCha7539Engine
import org.bouncycastle.crypto.params.{KeyParameter, ParametersWithIV}

import java.lang.management.ManagementFactory
import java.nio.ByteOrder

/**
Expand All @@ -36,36 +37,44 @@ class WeakRandom() {
private val seed = new Array[Byte](32)
private var opsSinceLastSample: Int = 0

private val memoryMXBean = ManagementFactory.getMemoryMXBean
private val runtimeMXBean = ManagementFactory.getRuntimeMXBean
private val threadMXBean = ManagementFactory.getThreadMXBean

// sample some initial entropy
sampleEntropy()

private def feedDigest(sha: SHA256Digest, i: Int): Unit = {
sha.update(i.toByte)
sha.update((i >> 8).toByte)
sha.update((i >> 16).toByte)
sha.update((i >> 24).toByte)
}

private def feedDigest(sha: SHA256Digest, l: Long): Unit = {
sha.update(l.toByte)
sha.update((l >> 8).toByte)
sha.update((l >> 16).toByte)
sha.update((l >> 24).toByte)
sha.update((l >> 32).toByte)
sha.update((l >> 40).toByte)
}

/** The entropy pool is regularly enriched with newly sampled entropy. */
private def sampleEntropy(): Unit = {
opsSinceLastSample = 0

val sha = new SHA256Digest()
sha.update(seed, 0, 32)

// Sample current time.
val now = System.currentTimeMillis()
sha.update(now.toByte)
sha.update((now >> 8).toByte)
sha.update((now >> 16).toByte)
sha.update((now >> 24).toByte)

// Sample memory allocator.
val addr = System.identityHashCode(new Array[Int](1))
sha.update(addr.toByte)
sha.update((addr >> 8).toByte)
sha.update((addr >> 16).toByte)
sha.update((addr >> 24).toByte)

// Sample available memory.
val memory = Runtime.getRuntime.freeMemory()
sha.update(memory.toByte)
sha.update((memory >> 8).toByte)
sha.update((memory >> 16).toByte)
sha.update((memory >> 24).toByte)
feedDigest(sha, System.currentTimeMillis())
feedDigest(sha, System.identityHashCode(new Array[Int](1)))
feedDigest(sha, memoryMXBean.getHeapMemoryUsage.getUsed)
feedDigest(sha, memoryMXBean.getNonHeapMemoryUsage.getUsed)
feedDigest(sha, runtimeMXBean.getPid)
feedDigest(sha, runtimeMXBean.getUptime)
feedDigest(sha, threadMXBean.getCurrentThreadCpuTime)
feedDigest(sha, threadMXBean.getCurrentThreadUserTime)
feedDigest(sha, threadMXBean.getPeakThreadCount)

sha.doFinal(seed, 0)
}
Expand Down

0 comments on commit 1c31cf7

Please sign in to comment.