-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcrypto.go
57 lines (49 loc) · 1.16 KB
/
crypto.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
// aesgcm provides authenticated symmetric encryption using AES-GCM. It
// generates random nonces for each message, and prepends the nonce to
// the ciphertext.
package main
import (
"crypto/aes"
"crypto/cipher"
)
// aesGcmEncrypt applies the necessary padding to the message and encrypts it
// with AES-GCM.
func aesGcmEncrypt(plain, key, nonce, data []byte) (ct []byte) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}
ct = gcm.Seal(nil, nonce, plain, data)
return
}
// aesGcmDecrypt decrypts the message and removes any padding.
func aesGcmDecrypt(ct, key, nonce, data []byte) (plain []byte) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}
plain, err = gcm.Open(nil, nonce, ct, data)
if err != nil {
panic(err)
}
return
}
// aesCtr does encrypt and decrypt of aes_ctr mode
func aesCtr(in, key, iv []byte) (out []byte) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
out = make([]byte, len(in))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(out, in)
return
}