-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.go
59 lines (52 loc) · 1.54 KB
/
encrypt.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"io/ioutil"
)
func main() {
fmt.Println("Encryption Program v0.01")
text := []byte("Sanchu Varkey")
key := []byte("passphrasewhichneedstobe32bytes!")
// generate a new aes cipher using our 32 byte long key
c, err := aes.NewCipher(key)
// if there are any errors, handle them
if err != nil {
fmt.Println(err)
}
// gcm or Galois/Counter Mode, is a mode of operation
// for symmetric key cryptographic block ciphers
// - https://en.wikipedia.org/wiki/Galois/Counter_Mode
gcm, err := cipher.NewGCM(c)
// if any error generating new GCM
// handle them
if err != nil {
fmt.Println(err)
}
// creates a new byte array the size of the nonce
// which must be passed to Seal
nonce := make([]byte, gcm.NonceSize())
// populates our nonce with a cryptographically secure
// random sequence
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
fmt.Println(err)
}
// here we encrypt our text using the Seal function
// Seal encrypts and authenticates plaintext, authenticates the
// additional data and appends the result to dst, returning the updated
// slice. The nonce must be NonceSize() bytes long and unique for all
// time, for a given key.
//fmt.Println(gcm.Seal(nonce, nonce, text, nil))
// the WriteFile method returns an error if unsuccessful
seal := gcm.Seal(nonce, nonce, text, nil)
fmt.Println(string(seal))
err = ioutil.WriteFile("/tmp/myfile.data", seal, 0777)
// handle this error
if err != nil {
// print it out
fmt.Println(err)
}
}