dc4bc/airgapped/encryption.go

69 lines
1.2 KiB
Go
Raw Permalink Normal View History

2020-09-17 05:03:10 -07:00
package airgapped
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
2020-11-10 04:26:59 -08:00
"math"
"golang.org/x/crypto/scrypt"
2020-09-17 05:03:10 -07:00
)
2020-11-10 04:26:59 -08:00
var N = int(math.Pow(2, 16))
2020-09-18 06:57:51 -07:00
func encrypt(key, salt, data []byte) ([]byte, error) {
2020-11-10 04:26:59 -08:00
derivedKey, err := scrypt.Key(key, salt, N, 8, 1, 32)
2020-09-17 05:03:10 -07:00
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 05:03:10 -07:00
}
2020-09-17 09:31:14 -07:00
c, err := aes.NewCipher(derivedKey)
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 09:31:14 -07:00
}
gcm, err := cipher.NewGCM(c)
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 05:03:10 -07:00
}
2020-09-17 09:31:14 -07:00
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 09:31:14 -07:00
}
return gcm.Seal(nonce, nonce, data, nil), nil
2020-09-17 05:03:10 -07:00
}
2020-09-18 06:57:51 -07:00
func decrypt(key, salt, data []byte) ([]byte, error) {
2020-11-10 04:26:59 -08:00
derivedKey, err := scrypt.Key(key, salt, N, 8, 1, 32)
2020-09-17 05:03:10 -07:00
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 05:03:10 -07:00
}
2020-09-17 09:31:14 -07:00
c, err := aes.NewCipher(derivedKey)
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 05:03:10 -07:00
}
2020-09-17 09:31:14 -07:00
gcm, err := cipher.NewGCM(c)
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 09:31:14 -07:00
}
2020-09-17 05:03:10 -07:00
2020-09-17 09:31:14 -07:00
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
2020-09-17 10:45:49 -07:00
return nil, fmt.Errorf("invalid data length")
2020-09-17 09:31:14 -07:00
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
decryptedData, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
2020-09-17 10:45:49 -07:00
return nil, err
2020-09-17 09:31:14 -07:00
}
2020-09-17 05:03:10 -07:00
2020-09-17 09:31:14 -07:00
return decryptedData, nil
2020-09-17 05:03:10 -07:00
}