Skip to content

Commit

Permalink
output chi-square of the original text
Browse files Browse the repository at this point in the history
  • Loading branch information
xtaci committed Jul 24, 2024
1 parent 18df1f2 commit 17d50a7
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions qpp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,33 +204,46 @@ func TestEncryptionChiSquare(t *testing.T) {
}
defer f.Close()

// 1 MB structured data
original := make([]byte, 1024*1024)
msg := original

// fill original with bible text
for len(msg) > 0 {
n := copy(msg, bibleText)
msg = msg[n:]
}

t.Logf("Orignal text Chi-squared, %f:", chiSquare(original))
// write header to csv
f.WriteString("pads,chi-square\n")

// test chi-square for 1 to 255 pads, and output the result to a CSV file
for i := 1; i < 256; i++ {
chi := testChiSquare(t, uint16(i))
chi := testChiSquare(t, original, uint16(i))
f.WriteString(fmt.Sprintf("%d,%f\n", i, chi))
}

t.Log("chi-squared output to chi-square.csv")
}

func testChiSquare(t *testing.T, pads uint16) float64 {
func testChiSquare(t *testing.T, plaintext []byte, pads uint16) float64 {
seed := make([]byte, 32)
io.ReadFull(rand.Reader, seed)

sender := NewQPP(seed, pads)
original := make([]byte, 1024*1024)
msg := original

// fill original with bible text
for len(msg) > 0 {
n := copy(msg, bibleText)
msg = msg[n:]
}
// make a copy of plaintext
msg := make([]byte, len(plaintext))
copy(msg, plaintext)

msg = original
// encrypt and calc
sender.Encrypt(msg)
chi := chiSquare(msg)
return chi
}

// a function to calculate the chi-square value
func chiSquare(msg []byte) float64 {
// chi-square test
// 1. calculate frequency
freq := make([]int, 256)
Expand All @@ -244,7 +257,6 @@ func testChiSquare(t *testing.T, pads uint16) float64 {
for _, f := range freq {
chi += (float64(f) - expected) * (float64(f) - expected) / expected
}
t.Log("pads:", pads, "chi-square:", chi)
return chi

}
Expand Down

0 comments on commit 17d50a7

Please sign in to comment.