Created
July 29, 2023 12:06
-
-
Save adityajoshi12/f94042ac2fd6566c534f775aec9b2625 to your computer and use it in GitHub Desktop.
Caesar Cipher is a simple substitution cipher that shifts characters in the plaintext by a fixed number of positions to generate ciphertext.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
// Function to perform Caesar Cipher encryption | |
func caesarEncrypt(plaintext string, shift int) string { | |
ciphertext := "" | |
for _, char := range plaintext { | |
if char >= 'A' && char <= 'Z' { | |
ciphertext += string((char-'A'+rune(shift))%26 + 'A') | |
} else if char >= 'a' && char <= 'z' { | |
ciphertext += string((char-'a'+rune(shift))%26 + 'a') | |
} else { | |
ciphertext += string(char) | |
} | |
} | |
return ciphertext | |
} | |
// Function to perform Caesar Cipher decryption | |
func caesarDecrypt(ciphertext string, shift int) string { | |
return caesarEncrypt(ciphertext, 26-shift) // Decryption is just the reverse shift | |
} | |
func main() { | |
plaintext := "Hello, World!" | |
shift := 3 | |
// Encryption | |
encryptedText := caesarEncrypt(plaintext, shift) | |
fmt.Println("Plaintext:", plaintext) | |
fmt.Println("Encrypted:", encryptedText) | |
// Decryption | |
decryptedText := caesarDecrypt(encryptedText, shift) | |
fmt.Println("Decrypted:", decryptedText) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment