diff --git a/core/src/test/resources/net/kemitix/thorp/core/File-6964 b/core/src/test/resources/net/kemitix/thorp/core/File-6964 new file mode 100644 index 0000000..bd24b2b Binary files /dev/null and b/core/src/test/resources/net/kemitix/thorp/core/File-6964 differ diff --git a/domain/src/main/scala/net/kemitix/thorp/domain/HexEncoder.scala b/domain/src/main/scala/net/kemitix/thorp/domain/HexEncoder.scala index 17a8495..b6fbda8 100644 --- a/domain/src/main/scala/net/kemitix/thorp/domain/HexEncoder.scala +++ b/domain/src/main/scala/net/kemitix/thorp/domain/HexEncoder.scala @@ -4,19 +4,17 @@ import java.math.BigInteger trait HexEncoder { - def encode(bytes: Array[Byte]): String = { - val bigInteger = new BigInteger(1, bytes) - String.format("%0" + (bytes.length << 1) + "x", bigInteger) - } + def encode(bytes: Array[Byte]): String = + String + .format("%0" + (bytes.length << 1) + "x", new BigInteger(1, bytes)) + .toUpperCase - def decode(hexString: String): Array[Byte] = { - val byteArray = new BigInteger(hexString, 16).toByteArray - if (byteArray(0) == 0) { - val output = new Array[Byte](byteArray.length - 1) - System.arraycopy(byteArray, 1, output, 0, output.length) - output - } else byteArray - } + def decode(hexString: String): Array[Byte] = + hexString + .replaceAll("[^0-9A-Fa-f]", "") + .sliding(2, 2) + .toArray + .map(Integer.parseInt(_, 16).toByte) } diff --git a/domain/src/test/scala/net/kemitix/thorp/domain/HexEncoderTest.scala b/domain/src/test/scala/net/kemitix/thorp/domain/HexEncoderTest.scala new file mode 100644 index 0000000..93f8f59 --- /dev/null +++ b/domain/src/test/scala/net/kemitix/thorp/domain/HexEncoderTest.scala @@ -0,0 +1,23 @@ +package net.kemitix.thorp.domain + +import java.nio.charset.StandardCharsets + +import org.scalatest.FreeSpec + +class HexEncoderTest extends FreeSpec { + + val text = "test text to encode to hex" + val hex = "74657374207465787420746F20656E636F646520746F20686578" + + "can round trip a hash decode then encode" in { + val input = hex + val result = HexEncoder.encode(HexEncoder.decode(input)) + assertResult(input)(result) + } + "can round trip a hash encode then decode" in { + val input = hex.getBytes(StandardCharsets.UTF_8) + val result = HexEncoder.decode(HexEncoder.encode(input)) + assertResult(input)(result) + } + +}