summaryrefslogtreecommitdiff
path: root/crypt.go
blob: 662184c4e12a4271c2dccce4e13bcbee4a2fce60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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)
}