61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
|
package crypt
|
||
|
|
||
|
import (
|
||
|
"crypto/cipher"
|
||
|
"crypto/rand"
|
||
|
"log"
|
||
|
|
||
|
"golang.org/x/crypto/chacha20poly1305"
|
||
|
)
|
||
|
|
||
|
type Crypt struct {
|
||
|
key []byte
|
||
|
ads []byte
|
||
|
aead cipher.AEAD
|
||
|
}
|
||
|
|
||
|
func NewChacha20poly1305Key() []byte {
|
||
|
k := make([]byte, chacha20poly1305.KeySize)
|
||
|
if _, err := rand.Read(k); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return k
|
||
|
}
|
||
|
|
||
|
func NewCrypt(key []byte, ads []byte) *Crypt {
|
||
|
if len(key) == 0 {
|
||
|
// log.Printf(" == GENERATE NEW KEY ==\n")
|
||
|
key = NewChacha20poly1305Key()
|
||
|
}
|
||
|
aead, err := chacha20poly1305.New(key)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return &Crypt{key: key, ads: ads, aead: aead}
|
||
|
}
|
||
|
|
||
|
func (c *Crypt) GenNonce(length int) []byte {
|
||
|
nonce := make([]byte, c.aead.NonceSize(), c.aead.NonceSize()+length+c.aead.Overhead())
|
||
|
if _, err := rand.Read(nonce); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return nonce
|
||
|
}
|
||
|
|
||
|
func (c *Crypt) Encrypt(msg []byte) []byte {
|
||
|
nonce := c.GenNonce(len(msg))
|
||
|
encryptedMsg := c.aead.Seal(nonce, nonce, msg, c.ads)
|
||
|
return encryptedMsg
|
||
|
}
|
||
|
|
||
|
func (c *Crypt) Decrypt(encrypted []byte) ([]byte, bool) {
|
||
|
done := true
|
||
|
nonce, ciphertext := encrypted[:c.aead.NonceSize()], encrypted[c.aead.NonceSize():]
|
||
|
plaintext, err := c.aead.Open(nil, nonce, ciphertext, c.ads)
|
||
|
if err != nil {
|
||
|
done = false
|
||
|
log.Printf(" error decrypt data : %v\n", err)
|
||
|
}
|
||
|
return plaintext, done
|
||
|
}
|