Skip to content

Commit

Permalink
Refactor header serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabio Tacke committed Apr 3, 2020
1 parent 323cae3 commit 07b7031
Showing 1 changed file with 10 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,21 @@ class Message(val header: Header, val cipher: ByteArray)
class Header(val publicKey: Key, val numberOfMessagesInPreviousSendingChain: Int, val messageNumber: Int) {
fun bytes(): ByteArray {
var bytes = publicKey.asBytes.clone()
bytes += byteArray(numberOfMessagesInPreviousSendingChain, 8)
bytes += byteArray(messageNumber, 8)

if (numberOfMessagesInPreviousSendingChain < Int.MAX_VALUE) {
bytes += ByteArray(4) // Padding to be compatible with 64-bit
}
return bytes
}

bytes += BigInteger.valueOf(numberOfMessagesInPreviousSendingChain.toLong()).toByteArray()
private fun byteArray(value: Int, byteCount: Int): ByteArray {
val valueBytes = BigInteger.valueOf(value.toLong()).toByteArray()

if (messageNumber < Int.MAX_VALUE) {
bytes += ByteArray(4) // Padding to be compatible with 64-bit
if (valueBytes.size > byteCount) {
throw IllegalArgumentException("Binary representation of given value needs more bytes then specified by byteCount.")
}

bytes += BigInteger.valueOf(messageNumber.toLong()).toByteArray()
val paddingBytes = ByteArray(byteCount - valueBytes.size)

return bytes
return paddingBytes + valueBytes
}
}

0 comments on commit 07b7031

Please sign in to comment.