Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tests(cipher/rsa): add fuzz test to rsa cipher #591

Merged
merged 4 commits into from
Oct 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions cipher/rsa/rsa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,30 +35,28 @@ var rsaTestData = []struct {
},
}

func TestEncryptDecrypt(t *testing.T) {
func testPrecondition(t *testing.T) (int64, int64, int64) {
// Both prime numbers
t.Helper()
p := int64(61)
q := int64(53)

n := p * q

delta := lcm.Lcm(p-1, q-1)

e := int64(17) // Coprime with delta

if gcd.Recursive(e, delta) != 1 {
t.Fatal("Algorithm failed in preamble stage:\n\tPrime numbers are chosen statically and it shouldn't fail at this stage")
t.Fatal("something went wrong: prime numbers are chosen statically and it shouldn't fail at this stage")
}

d, err := modular.Inverse(e, delta)

if err != nil {
t.Fatalf("Algorithm failed in preamble stage:\n\tProblem with a modular directory dependency: %v", err)
t.Fatalf("something went wrong: problem with %q: %v", "modular.Inverse", err)
}
return e, d, n
}

func TestEncryptDecrypt(t *testing.T) {
for _, test := range rsaTestData {
t.Run(test.description, func(t *testing.T) {

e, d, n := testPrecondition(t)
message := []rune(test.input)
encrypted, err := Encrypt(message, e, n)
if err != nil {
Expand All @@ -77,3 +75,23 @@ func TestEncryptDecrypt(t *testing.T) {
})
}
}

func FuzzRsa(f *testing.F) {
for _, rsaTestInput := range rsaTestData {
f.Add(rsaTestInput.input)
}
f.Fuzz(func(t *testing.T, input string) {
e, d, n := testPrecondition(t)
encrypted, err := Encrypt([]rune(input), e, n)
if err != nil {
t.Fatalf("failed to encrypt string: %v", err)
}
decrypted, err := Decrypt(encrypted, d, n)
if err != nil {
t.Fatalf("failed to decrypt string: %v", err)
}
if decrypted != input {
t.Fatalf("expected: %q, got: %q", input, decrypted)
}
})
}