diff options
| author | Nikolaus Gotsche <n@softwarefools.com> | 2018-02-21 03:25:05 +0100 |
|---|---|---|
| committer | Nikolaus Gotsche <n@softwarefools.com> | 2018-02-21 03:25:05 +0100 |
| commit | 27b333a73524b9a99145f0ca1f2a3a0181145351 (patch) | |
| tree | 23f26f7a9a31bd72b3664e684ed7d4a96441e8d3 /crypt.go | |
Diffstat (limited to 'crypt.go')
| -rw-r--r-- | crypt.go | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/crypt.go b/crypt.go new file mode 100644 index 0000000..662184c --- /dev/null +++ b/crypt.go @@ -0,0 +1,92 @@ +package main + +import ( + "encoding/base64" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "fmt" + "io" + "os" + //"strconv" +) + +func cryptexample() { + fmt.Println("Testing Cryptics") + //key := "123456789012345678901234" // Needs to be 32 bytes long + //key := "Have some of the beautiful ideas" + plaintext1 := "Hello! You Fool! I Love You" + plaintext2 := "Somefancy Password" + foo := Encrypt(plaintext1) + fook := Decrypt(foo) + fmt.Printf("%s -> %s\n",plaintext1,foo) + fmt.Printf("%s -> %s\n\n",foo,fook) + bar := Encrypt(plaintext2) + barn := Decrypt(bar) + fmt.Printf("%s -> %s\n",plaintext2,bar) + fmt.Printf("%s -> %s\n\n",bar,barn) + os.Exit(0) +} + + //key := "123456789012345678901234" // Needs to be 32 bytes long +var keystr string = "Have some of the beautiful ideas" + +func encodeBase64(inp string) string { + b := []byte(inp) + return base64.StdEncoding.EncodeToString(b) +} + +func decodeBase64(s string) string { + data, err := base64.StdEncoding.DecodeString(s) + if err != nil { panic(err) } + return string(data) +} + +func Encrypt(textstr string) string { + text := []byte(textstr) + key := []byte(keystr) + + //fmt.Println(text) + block, err := aes.NewCipher([]byte(key)) + checkErr(err) + + b := base64.StdEncoding.EncodeToString(text) + ciphertext := make([]byte, aes.BlockSize+len(b)) + iv := ciphertext[:aes.BlockSize] + _, err = io.ReadFull(rand.Reader, iv) + checkErr(err) + cfb := cipher.NewCFBEncrypter(block, iv) + cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b)) + return encodeBase64(string(ciphertext)) + +} + +func Decrypt(textstr string) string { + + text := []byte(decodeBase64(textstr)) + key := []byte(keystr) + //checkErr(err) + + block, err := aes.NewCipher(key) + checkErr(err) + if len(text) < aes.BlockSize { + return "GEEEH SCHIESSEN! ZU Kurz?" + //return nil, errors.New("ciphertext too short") + } + iv := text[:aes.BlockSize] + text = text[aes.BlockSize:] + cfb := cipher.NewCFBDecrypter(block, iv) + cfb.XORKeyStream(text, text) + //data, err := base64.StdEncoding.DecodeString(string(text[aes.BlockSize:])) + data, err := base64.StdEncoding.DecodeString(string(text)) + checkErr(err) + return string(data) + //if err != nil { panic(err) } + //ciphertext := decodeBase64(text) + //cfb := cipher.NewCFBEncrypter(block, iv) + //plaintext := make([]byte, len(ciphertext)) + //cfb.XORKeyStream(plaintext, ciphertext) + //return string(plaintext) +} + + |
