croc/src/crypt/crypt.go

87 lines
1.8 KiB
Go
Raw Normal View History

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-09-07 18:46:04 +02:00
// Encryption is the basic type for storing
// the key, passphrase and salt
2019-04-30 01:58:37 +02:00
type Encryption struct {
key []byte
passphrase []byte
2019-04-28 01:49:00 +02:00
salt []byte
2018-09-22 05:17:57 +02:00
}
2019-04-30 01:58:37 +02:00
// New generates a new Encryption, using the supplied passphrase and
// an optional supplied salt.
2019-04-30 04:19:25 +02:00
// Passing nil passphrase will not use decryption.
2019-04-30 01:58:37 +02:00
func New(passphrase []byte, salt []byte) (e Encryption, err error) {
2019-04-30 04:19:25 +02:00
if passphrase == nil {
e = Encryption{nil, nil, nil}
return
}
e.passphrase = passphrase
if salt == nil {
2019-04-28 01:49:00 +02:00
e.salt = make([]byte, 8)
// http://www.ietf.org/rfc/rfc2898.txt
// Salt.
2019-04-28 01:49:00 +02:00
rand.Read(e.salt)
} else {
2019-04-28 01:49:00 +02:00
e.salt = salt
}
2019-04-28 01:49:00 +02:00
e.key = pbkdf2.Key([]byte(passphrase), e.salt, 100, 32, sha256.New)
return
}
2019-09-07 18:46:04 +02:00
// Salt returns the salt bytes
2019-04-30 01:58:37 +02:00
func (e Encryption) Salt() []byte {
2019-04-28 01:49:00 +02:00
return e.salt
}
2019-04-30 01:58:37 +02:00
// Encrypt will generate an Encryption, prefixed with the IV
func (e Encryption) Encrypt(plaintext []byte) (encrypted []byte, err error) {
2019-04-30 04:19:25 +02:00
if e.passphrase == nil {
encrypted = plaintext
return
}
// 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
ivBytes := make([]byte, 12)
2018-09-22 05:17:57 +02:00
rand.Read(ivBytes)
2019-04-28 02:03:05 +02:00
b, err := aes.NewCipher(e.key)
if err != nil {
return
}
aesgcm, err := cipher.NewGCM(b)
if err != nil {
return
}
encrypted = aesgcm.Seal(nil, ivBytes, plaintext, nil)
encrypted = append(ivBytes, encrypted...)
return
2018-09-22 05:17:57 +02:00
}
2019-04-30 01:58:37 +02:00
// Decrypt an Encryption
func (e Encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) {
2019-04-30 04:19:25 +02:00
if e.passphrase == nil {
plaintext = encrypted
return
}
2019-04-28 02:03:05 +02:00
b, err := aes.NewCipher(e.key)
if err != nil {
return
}
aesgcm, err := cipher.NewGCM(b)
if err != nil {
return
}
plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil)
2018-09-22 05:17:57 +02:00
return
}