Instantly share code, notes, and snippets.

@scusi /xor.go
Last active May 18, 2017

Embed
What would you like to do?
rolling xor implementation in go
package main
import (
"container/ring"
"flag"
"io/ioutil"
"log"
)
var keyFile string
var keyString string
var inFile string
var outFile string
var keyData []byte
var err error
func init() {
flag.StringVar(&keyFile, "k", "key", "key file to use")
flag.StringVar(&keyString, "s", "", "key to use, as string")
flag.StringVar(&inFile, "f", "file", "file encrypt/decrypt")
flag.StringVar(&outFile, "o", "out", "output file")
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
flag.Parse()
if keyString == "" {
// load key file
keyData, err = ioutil.ReadFile(keyFile)
check(err)
} else {
keyData = []byte(keyString)
}
// setup ring buffer with key data
r := ring.New(len(keyData))
for i := 0; i < r.Len(); i++ {
r.Value = keyData[i]
r = r.Next()
}
// load encrypted data from file
data, err := ioutil.ReadFile(inFile)
check(err)
for i := 0; i < len(data); i++ { // foreach byte of data
data[i] = r.Value.(byte) ^ data[i] // xor data byte with current ring element
r = r.Next() // move ring forward
}
ioutil.WriteFile(outFile, data, 0700)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment