2018-09-22 05:17:57 +02:00
|
|
|
package crypt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/pbkdf2"
|
|
|
|
)
|
|
|
|
|
2019-04-28 01:49:00 +02:00
|
|
|
type encryption struct {
|
2019-04-27 20:15:38 +02:00
|
|
|
key []byte
|
|
|
|
passphrase []byte
|
2019-04-28 01:49:00 +02:00
|
|
|
salt []byte
|
2018-09-22 05:17:57 +02:00
|
|
|
}
|
|
|
|
|
2019-04-27 20:15:38 +02:00
|
|
|
// New generates a new encryption, using the supplied passphrase and
|
|
|
|
// an optional supplied salt.
|
2019-04-28 01:49:00 +02:00
|
|
|
func New(passphrase []byte, salt []byte) (e encryption, err error) {
|
2019-04-27 20:15:38 +02:00
|
|
|
e.passphrase = passphrase
|
|
|
|
if salt == nil {
|
2019-04-28 01:49:00 +02:00
|
|
|
e.salt = make([]byte, 8)
|
2019-04-27 20:15:38 +02:00
|
|
|
// http://www.ietf.org/rfc/rfc2898.txt
|
|
|
|
// Salt.
|
2019-04-28 01:49:00 +02:00
|
|
|
rand.Read(e.salt)
|
2019-04-27 20:15:38 +02:00
|
|
|
} else {
|
2019-04-28 01:49:00 +02:00
|
|
|
e.salt = salt
|
2018-09-24 21:52:19 +02:00
|
|
|
}
|
2019-04-28 01:49:00 +02:00
|
|
|
e.key = pbkdf2.Key([]byte(passphrase), e.salt, 100, 32, sha256.New)
|
2018-09-24 21:52:19 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-04-28 01:49:00 +02:00
|
|
|
func (e encryption) Salt() []byte {
|
|
|
|
return e.salt
|
|
|
|
}
|
|
|
|
|
2019-04-27 20:15:38 +02:00
|
|
|
// Encrypt will generate an encryption, prefixed with the IV
|
2019-04-28 01:49:00 +02:00
|
|
|
func (e encryption) Encrypt(plaintext []byte) []byte {
|
2019-04-27 20:15:38 +02:00
|
|
|
// generate a random iv each time
|
2018-09-22 05:17:57 +02:00
|
|
|
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
|
|
|
|
// Section 8.2
|
2019-04-27 20:15:38 +02:00
|
|
|
ivBytes := make([]byte, 12)
|
2018-09-22 05:17:57 +02:00
|
|
|
rand.Read(ivBytes)
|
2019-04-27 20:15:38 +02:00
|
|
|
b, _ := aes.NewCipher(e.key)
|
2018-09-22 05:17:57 +02:00
|
|
|
aesgcm, _ := cipher.NewGCM(b)
|
|
|
|
encrypted := aesgcm.Seal(nil, ivBytes, plaintext, nil)
|
2019-04-27 20:15:38 +02:00
|
|
|
return append(ivBytes, encrypted...)
|
2018-09-22 05:17:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Decrypt an encryption
|
2019-04-28 01:49:00 +02:00
|
|
|
func (e encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) {
|
2019-04-27 20:15:38 +02:00
|
|
|
b, _ := aes.NewCipher(e.key)
|
2018-09-22 05:17:57 +02:00
|
|
|
aesgcm, _ := cipher.NewGCM(b)
|
2019-04-27 20:15:38 +02:00
|
|
|
plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil)
|
2018-09-22 05:17:57 +02:00
|
|
|
return
|
|
|
|
}
|