-
Notifications
You must be signed in to change notification settings - Fork 3
/
crypto.go
49 lines (40 loc) · 1.39 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
// Implements secret-key authentication encryption using LibNacl's Golang interface.
package ghostpass
import (
"errors"
"github.com/awnumar/memguard"
"golang.org/x/crypto/nacl/secretbox"
"unsafe"
)
// Use symmetric authenticated encryption to generate a ciphertext given
// any plaintext byte buffer.
func BoxEncrypt(key []byte, plaintext []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("Length of key is not 32 bytes")
}
// get an unsafe reference to pointer
keyptr := (*[32]byte)(unsafe.Pointer(&key[0]))
// create nonce for HMAC seeding through memguard
var nonce [24]byte
memguard.ScrambleBytes(nonce[:])
// encrypt and return result
return secretbox.Seal(nonce[:], plaintext, &nonce, keyptr), nil
}
// Use symmetric authenticated encryption to decrypt a plaintext from a ciphertext
// given a ciphertext byte buffer.
func BoxDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("Length of key is not 32 bytes")
}
// retrieve nonce from ciphertext, which is appended at the end
var nonce [24]byte
copy(nonce[:], ciphertext[:24])
// get an unsafe reference to pointer
keyptr := (*[32]byte)(unsafe.Pointer(&key[0]))
// decrypt with error checking
plaintext, ok := secretbox.Open(nil, ciphertext[24:], &nonce, keyptr)
if !ok {
return nil, errors.New("Decryption on ciphertext failed")
}
return plaintext, nil
}