-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendshit.go
98 lines (71 loc) · 1.82 KB
/
sendshit.go
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
93
94
95
96
97
98
package sendshit
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"io/ioutil"
"mime/multipart"
"net/http"
"github.com/keybase/go-triplesec"
"github.com/vincent-petithory/dataurl"
)
// Upload structure
type Upload struct {
URL string `json:"url"`
Name string `json:"name"`
}
// Response of API Upload
type Response struct {
ID string `json:"id"`
}
// GenerateRandomString Generates a random hex string
func GenerateRandomString(size int) (string, error) {
bytes := make([]byte, size)
_, err := rand.Read(bytes)
return hex.EncodeToString(bytes), err
}
// EncryptFile Encrypts a file with a key
func EncryptFile(name string, data []byte, key string) (string, error) {
var encodedStr string
cipher, err := triplesec.NewCipher([]byte(key), nil, 3)
if err != nil {
return encodedStr, err
}
dataURL := dataurl.EncodeBytes(data)
upload := &Upload{
URL: dataURL,
Name: name}
json, _ := json.Marshal(upload)
var encrypted []byte
encrypted, err = cipher.Encrypt(json)
if err != nil {
return encodedStr, err
}
encodedStr = hex.EncodeToString(encrypted)
return encodedStr, nil
}
// UploadFile Uploads the encrypted file data to the API
func UploadFile(encryptedData string) (Response, error) {
var response Response
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
fileWriter, err := bodyWriter.CreateFormFile("upload", "encrypted")
if err != nil {
return response, err
}
fileWriter.Write([]byte(encryptedData))
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
resp, err := http.Post("https://api.sendsh.it/upload", contentType, bodyBuf)
if err != nil {
return response, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response, err
}
json.Unmarshal(body, &response)
return response, nil
}