diff --git a/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto.go b/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto.go new file mode 100644 index 00000000..57755350 --- /dev/null +++ b/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto.go @@ -0,0 +1,35 @@ +package crypto + +import ( + "strings" +) + +// CaesarCipherEncode ... +func CaesarCipherEncode(input string, shift int) string { + var output strings.Builder + for _, c := range input { + var lowercaseFlag bool + if c >= 97 && c <= 122 { + c -= 32 + lowercaseFlag = true + } + if c >= 65 && c <= 90 { + c += rune(shift) + if c > 90 { + c = 65 + (c-90-1)%26 + } else if c < 65 { + c = 90 - (65-c-1)%26 + } + } + if lowercaseFlag { + c += 32 + } + output.WriteRune(c) + } + return output.String() +} + +// CaesarCipherDecode ... +func CaesarCipherDecode(input string, shift int) string { + return CaesarCipherEncode(input, -shift) +} diff --git a/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto_test.go b/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto_test.go new file mode 100644 index 00000000..3303877a --- /dev/null +++ b/Cryptography/src/Caesar/Simple_Caesar/caesarcrypto_test.go @@ -0,0 +1,64 @@ +package crypto + +import ( + "reflect" + "testing" +) + +func Test_CaesarCipherEncode(t *testing.T) { + tests := []struct { + name string + input string + shift int + expected string + }{ + { + name: "Encode 1", + input: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123", + shift: 3, + expected: "D txLfn EuRzQ IrA mXPsv RyHu wkH oDcB GrJ 123", + }, + { + name: "Encode 2", + input: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123", + shift: -3, + expected: "X nrFzh YoLtK ClU gRJmp LsBo qeB iXwV AlD 123", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := CaesarCipherEncode(tt.input, tt.shift); !reflect.DeepEqual(got, tt.expected) { + t.Errorf("CaesarCipherEncode() = %v, expected %v", got, tt.expected) + } + }) + } +} + +func Test_CaesarCipherDecode(t *testing.T) { + tests := []struct { + name string + input string + shift int + expected string + }{ + { + name: "Decode 1", + input: "D txLfn EuRzQ IrA mXPsv RyHu wkH oDcB GrJ 123", + shift: 3, + expected: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123", + }, + { + name: "Decode 2", + input: "X nrFzh YoLtK ClU gRJmp LsBo qeB iXwV AlD 123", + shift: -3, + expected: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := CaesarCipherDecode(tt.input, tt.shift); !reflect.DeepEqual(got, tt.expected) { + t.Errorf("CaesarCipherDecode() = %v, expected %v", got, tt.expected) + } + }) + } +}