Skip to content
This repository has been archived by the owner on Dec 3, 2022. It is now read-only.

Commit

Permalink
Creates incorrect MD5 hash for some files (#103)
Browse files Browse the repository at this point in the history
* [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
  • Loading branch information
kemitix authored Jul 19, 2019
1 parent 515b896 commit c33fa05
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 12 deletions.
Binary file not shown.
22 changes: 10 additions & 12 deletions domain/src/main/scala/net/kemitix/thorp/domain/HexEncoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)

}

Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}

}

0 comments on commit c33fa05

Please sign in to comment.