Saturday, November 17, 2012

XOR Hex-Encoded Strings in Scala

It's been said that all cryptographers do is XOR things together. Although that's not entirely true, we do find ourselves XORing things quite a bit... maybe there is some truth to that after all. Anyway, the other day, while I was writing a two-time pad attack on stream ciphers, I needed a few utility methods to make the string operations a bit easier. One of the methods was performing XOR operations on two hex-encoded strings. Here's the utility method in Scala. I posted it here in case anybody else might find it useful.

def xorHexStrings(hexString1 : String, hexString2 : String) = {
    val iterator1 = hexString1.sliding(2, 2)
    val iterator2 = hexString2.sliding(2, 2)
    val result =  new StringBuilder
        
    if (hexString2.length > hexString1.length) {
        while (iterator1.hasNext) {
            val i = Integer.toString(Integer.parseInt(iterator1.next, 16) ^
                    Integer.parseInt(iterator2.next, 16), 16)

            if (i.length == 1) result.append("0")
            result.append(i)

        }
            
        while (iterator2.hasNext) result.append(iterator2.next)
    }
    else {
        while (iterator2.hasNext) {
            val i = Integer.toString(Integer.parseInt(iterator1.next, 16) ^
                    Integer.parseInt(iterator2.next, 16), 16)

            if (i.length == 1) result.append("0")
            result.append(i)

        }
          
        while (iterator1.hasNext) result.append(iterator1.next)
    }
        
    result.toString()
}

If we call this method within our main function, we can see the results.

def main(args : Array[String]) {
    val hexString1 = "1274560603"
    val hexString2 = "876429"

    //prints 95107f0603
    println(xorHexStrings(hexString1, hexString2))
}

2 comments:

  1. Can you explain how one would xor hex strings without programming? Thank you!

    ReplyDelete
    Replies
    1. You could either write the values out on paper and do the exclusive OR by hand, or you could use the calculator app on Windows using View -> Programmer (Alt+3). If neither of those methods work, let me know. I might need to know more about the problem you're up against.

      Delete