-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (71 loc) · 2.07 KB
/
main.go
File metadata and controls
87 lines (71 loc) · 2.07 KB
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
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
"net/http"
"os"
"github.com/gorilla/mux"
)
func encrypt(plainText []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(plainText))
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plainText)
return ciphertext, nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
return ciphertext, nil
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/decrypt/{key}/{cipherText}", DecryptHandler).Methods("GET")
router.HandleFunc("/encrypt/{key}/{plainText}", EncryptHandler).Methods("GET")
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
fmt.Println("Lintening http://localhost:", port)
http.ListenAndServe(":"+port, router)
}
func DecryptHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cipherText := vars["cipherText"]
key := vars["key"]
ciphertextBytes, _ := hex.DecodeString(cipherText)
result, err := decrypt(ciphertextBytes, []byte(key))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("Decrypt: " + cipherText + "\nIn:" + string(result))
fmt.Fprintln(w, string(result))
}
func EncryptHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
plainText := vars["plainText"]
key := vars["key"]
cipherText, err := encrypt([]byte(plainText), []byte(key))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("Encrypt: " + plainText + "\nIn:" + hex.EncodeToString(cipherText))
fmt.Fprintln(w, hex.EncodeToString(cipherText))
}