Creates incorrect MD5 hash for some files (#103)

* [core] Add test file that we create incorrect hash for

By 'incorrect' we mean "not what AWS S3 think is correct" for this
file.

* [domain] HexEncoder rewritten to correctly decode hex

* [domain] HexEncoder encode to uppercase
This commit is contained in:
Paul Campbell 2019-07-19 20:54:39 +01:00 committed by GitHub
parent 515b896993
commit c33fa05d19
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 12 deletions

View file

@ -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)
}

View file

@ -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)
}
}