Crack XOR Encryption

In one of my last articles I showed how to crack a single-byte XOR encryption quickly and easily. Click here for the article. And for some exchange on reddit about that stuff, please click here. And for the source code, here.

But now let’s look at how we can crack a message that has been xor encrypted with a repeating key. To do this, we need to perform the following steps:

  • find the potential length of key
  • divide the encrypted message into equal sized blocks according to the key length
  • bruteforce the potential characters that was used in the original key

Let’s start by finding the original key length

Find the potential length of key

There is a good way to infer the original key length from the Hamming distance. But first let’s clarify what the Hamming Distance is, and how we calculate it.

The Hamming Distance

In really short words: It calculates the bit distances two objects. For example two strings with same length, two bytes, two floats,… – you know what I mean.

Short example

What is the Hamming Distance from “a” and “b” ? So, “a” in ASCII is 97 and “b” is 98 (decimal). Let’s take a look into the bits.

You can quickly get the bit difference of these two bytes by XOR them. The last thing we need to do is count how many bits are true(1). In this case, the Hamming Distance from “a” and “b” is 2.

Implementation in GO

// Compute Hamming Distance from two bytes
func HammingByteDistance(a byte, b byte) int {
    c := 0
    r := a ^ b
    for i := 0; i < 8; i++ {
        if (r & 0x01) == 1 {
        r = r >> 1

    return c

// Compute Hamming Distance of two strings
func HammingStringDistance(a string, b string) int {
    if len(a) != len(b) {
        log.Fatal("error in calc hamming distance from string. length of strings are not equal")

    d := 0
    for i := 0; i < len(a); i++ {
        d += HammingByteDistance(a[i], b[i])

    return d

Guessing the right key-length

With our hamming distance implementation we are now able to guess, what could be the possible key-length. Let’s assume that our key-length is at least greater than then 1 (otherwise, you know, it’s single-byte-xor…) and less than e.g. 10.

The “only” thing we have to do now is to test in a loop all possible key lengths and choose the one where the hamming distance is the smallest in relation to the key length.

// Input the message and m and the key-length kl
func ProcessInputMessage(m string, kl int) float32 {
    mf := []string{}

    splitMessageIntoParts(m, kl, &mf)
    return discoverMessageParts(mf, kl)

// Split the message in to parts, depending on the key-length l
func splitMessageIntoParts(m string, l int, fragments *[]string) {
    for i := 0; i < len(m); i += l {
        if (i + l) < len(m) {
            *fragments = append(*fragments, m[i:i+l])

// calculate the hamming distance for each part
func discoverMessageParts(p []string, kl int) float32 {
    s := 0
    for i := 0; i < 6; i++ {
        if (i + 1) < len(p) {
            s += HammingStringDistance(p[i], p[i+1])

    return (float32(s) / float32(kl))

Small note: Why do we only charge up to a limit of 6 (in the “discoverMessageParts” function) ? It has been shown that a value between 4 and 7 gives the best results.

Why: Good question, if you have an idea, write me!

Anyway, we are able to calculate a score for each key length (kl) and store the return value in a map.

    keyMap := make(map[int]float32)

    ms := string(m)

    fmt.Println("process input message")
    for i := 2; i < *maxKeyLength; i++ {
        keyMap[i] = core.ProcessInputMessage(ms, i)

And than, with a little helper implementation, we can extract the top 5 possible key-length’s from our map.

func GetTopValuesFromKeyMap(target map[int]float32, l int) []KeyScore {
    tv := make([]KeyScore, 0, len(target))

    for k, v := range target {
        tv = append(tv, KeyScore{k, v})

    for i, v := range tv {
        for a, x := range tv {
            // IMPORTANT: smallest score!
            if v.Score < x.Score {
                c := tv[i]
                tv[i] = x
                tv[a] = c

    return tv[:l]

Divide Message

Get relative message groups

The next step is to divide our message into equal sized blocks. This time, however, append the key length and its relative index. Here is an example:

Let’s say we have a key-length of 2 and the message “this is a secret!

If we input that into our “grouping” function:

func GetMessageGroups(m string, gl int) []string {
    p := []string{}

    for i := 0; i < gl; i++ {
        g := ""
        c := i
        for c < len(m) {
            g += string(m[c])
            c += gl

        p = append(p, g)

    return p

Then we get back the following to entries:


Crack / Bruteforce the key

Now we are done with all the preparations and can get down to the real work and try to find the right key.

We now take each of our text blocks from the previous example and go through all the bytes from 0x00 to 0xFF and perform an XOR. After each XOR we calculate a matching score for Natural Language (in this case English). And choose the result, that has the highest score. With a very high probability, we have found a correct sign from the original key.

Yes, I know that sounds very abstract. But just look at the code:

package core

// GroupAnalyse represents the score of an analysed group
type GroupAnalyse struct {
    ascii int
    score int

// CrackKey try to crack the key
func CrackKey(mg []string, rb []AnalyseStringResult, rl []AnalyseRuneResult) [][]GroupAnalyse {

    pkg := [][]GroupAnalyse{}

    for _, v := range mg {
        gpr := processGroup(v, rb, rl)
        pkg = append(pkg, gpr)

    return pkg

func processGroup(g string, rb []AnalyseStringResult, rl []AnalyseRuneResult) []GroupAnalyse {
    gr := []GroupAnalyse{}
    for i := 0x00; i < 0xFF; i++ {
        xg := xorGroup(g, i)
        gr = append(gr, GroupAnalyse{i, calcMatchScore(rb, rl, xg)})

    return gr[:2]

func sortGroupAnalyse(t *[]GroupAnalyse) {
    for i, v := range *t {
        for a, x := range *t {
            if v.score > x.score {
                c := (*t)[i]
                (*t)[i] = x
                (*t)[a] = c

func xorGroup(g string, k int) string {
    xm := []byte{}
    for _, c := range g {
        xm = append(xm, byte(c)^byte(k))

    return string(xm)

func calcMatchScore(rb []AnalyseStringResult, rl []AnalyseRuneResult, xg string) int {
    s := 0
    for i := 0; i < len(xg); i++ {
        if (i + 1) < len(xg) {
            for _, b := range rb {
                if string(xg[i:(i+2)]) == b.value {

        for _, l := range rl {
            if rune(xg[i]) == l.value {

    return s

Let’s test a real example

Let’s work with the following example text (it’s from the golang faq):

Robert Griesemer, Rob Pike and Ken Thompson started sketching the goals for a new language on the white board on September 21, 2007. Within a few days the goals had settled into a plan to do something and a fair idea of what it would be. Design continued part-time in parallel with unrelated work. By January 2008, Ken had started work on a compiler with which to explore ideas; it generated C code as its output. By mid-year the language had become a full-time project and had settled enough to attempt a production compiler. In May 2008, Ian Taylor independently started on a GCC front end for Go using the draft specification. Russ Cox joined in late 2008 and helped move the language and libraries from prototype to reality.

Now, I encrypt that text with the key “golang” and encode the encryption output in hexadecimal. Here you can quickly build your own test message.


I really recommend to play a little bit around with some parameters like the maximum key-length and the maximum hamming distance range in the “discoverMessageParts” function.

The whole project can be found on github.

I hope you had fun



One response

Leave a Reply

Your email address will not be published.