ENT-1439: Hide the FastThreadLocal class behind a Supplier. (#550)

* Hide the FastThreadLocal class behind a Supplier.
* Add SHA256 to class and field names.
* Updates from code review: extra comment and class renamed.
This commit is contained in:
Chris Rankin 2018-03-14 14:27:43 +00:00 committed by GitHub
parent cd37f761ab
commit 1b02291321
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,6 +16,7 @@ import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.parseAsHex
import net.corda.core.utilities.toHexString
import java.security.MessageDigest
import java.util.function.Supplier
/**
* Container for a cryptographically secure hash value.
@ -64,16 +65,14 @@ sealed class SecureHash(bytes: ByteArray) : OpaqueBytes(bytes) {
}
}
private val threadLocalSha256MessageDigest = object : FastThreadLocal<MessageDigest>() {
override fun initialValue() = MessageDigest.getInstance("SHA-256")
}
private val sha256MessageDigest = SHA256DigestSupplier()
/**
* Computes the SHA-256 hash value of the [ByteArray].
* @param bytes The [ByteArray] to hash.
*/
@JvmStatic
fun sha256(bytes: ByteArray) = SHA256(threadLocalSha256MessageDigest.get().digest(bytes))
fun sha256(bytes: ByteArray) = SHA256(sha256MessageDigest.get().digest(bytes))
/**
* Computes the SHA-256 hash of the [ByteArray], and then computes the SHA-256 hash of the hash.
@ -119,4 +118,17 @@ fun ByteArray.sha256(): SecureHash.SHA256 = SecureHash.sha256(this)
*/
fun OpaqueBytes.sha256(): SecureHash.SHA256 = SecureHash.sha256(this.bytes)
/**
* Hide the [FastThreadLocal] class behind a [Supplier] interface
* so that we can remove it for core-deterministic.
*/
private class SHA256DigestSupplier : Supplier<MessageDigest> {
private val threadLocalSha256MessageDigest = LocalSHA256Digest()
override fun get(): MessageDigest = threadLocalSha256MessageDigest.get()
}
// Declaring this as "object : FastThreadLocal<>" would have
// created an extra public class in the API definition.
private class LocalSHA256Digest : FastThreadLocal<MessageDigest>() {
override fun initialValue(): MessageDigest = MessageDigest.getInstance("SHA-256")
}