ENT-1439 Use thread-local MessageDigest. (#541)

This commit is contained in:
Andrzej Cichocki 2018-03-13 10:20:22 +00:00 committed by GitHub
parent 5de831c1d3
commit 6b80072b18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 21 additions and 1 deletions

View File

@ -133,6 +133,9 @@ dependencies {
// required to use @Type annotation
compile "org.hibernate:hibernate-core:$hibernate_version"
// FastThreadLocal
compile "io.netty:netty-common:$netty_version"
}
// TODO Consider moving it to quasar-utils in the future (introduced with PR-1388)

View File

@ -10,6 +10,7 @@
package net.corda.core.crypto
import io.netty.util.concurrent.FastThreadLocal
import net.corda.core.serialization.CordaSerializable
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.parseAsHex
@ -63,12 +64,16 @@ sealed class SecureHash(bytes: ByteArray) : OpaqueBytes(bytes) {
}
}
private val threadLocalSha256MessageDigest = object : FastThreadLocal<MessageDigest>() {
override fun initialValue() = MessageDigest.getInstance("SHA-256")
}
/**
* Computes the SHA-256 hash value of the [ByteArray].
* @param bytes The [ByteArray] to hash.
*/
@JvmStatic
fun sha256(bytes: ByteArray) = SHA256(MessageDigest.getInstance("SHA-256").digest(bytes))
fun sha256(bytes: ByteArray) = SHA256(threadLocalSha256MessageDigest.get().digest(bytes))
/**
* Computes the SHA-256 hash of the [ByteArray], and then computes the SHA-256 hash of the hash.

View File

@ -0,0 +1,11 @@
package net.corda.core.crypto
import org.junit.Test
import kotlin.test.assertEquals
class SecureHashTest {
@Test
fun `sha256 does not retain state between same-thread invocations`() {
assertEquals(SecureHash.sha256("abc"), SecureHash.sha256("abc"))
}
}

View File

@ -33,6 +33,7 @@ configurations {
// We don't need these because we already include netty-all.
exclude group: 'io.netty', module: 'netty-transport'
exclude group: 'io.netty', module: 'netty-handler'
exclude group: 'io.netty', module: 'netty-common'
}
integrationTestCompile.extendsFrom testCompile