How to use XOR to encrypt and decrypt a string in Go

1 Answer

0 votes
package main

import (
	"fmt"
)

// XORCipher encrypts or decrypts a string using a key
func XORCipher(input, key string) string {
	output := make([]byte, len(input))
	keyLen := len(key)

	for i := 0; i < len(input); i++ {
		output[i] = input[i] ^ key[i % keyLen]
	}

	return string(output)
}

func main() {
	// Original message
	str := "May the Force be with you." 
	// Key for encryption/decryption
	key := "Obelus"

	// Encrypt the message
	encrypted := XORCipher(str, key)
	fmt.Println("Encrypted:\n", encrypted)

	// Decrypt the message
	decrypted := XORCipher(encrypted, key)
	fmt.Println("Decrypted:\n", decrypted)
}



/*
run:

Encrypted:
L :L *B# *B U &
Decrypted:
 May the Force be with you.

*/

 



answered Aug 16, 2025 by avibootz

Related questions

1 answer 82 views
82 views asked Jul 11, 2025 by avibootz
1 answer 100 views
100 views asked Jul 12, 2025 by avibootz
2 answers 120 views
120 views asked Jul 12, 2025 by avibootz
...