64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"errors"
|
|
"io"
|
|
)
|
|
|
|
var ErrShortCipherText = errors.New("ciphertext too short")
|
|
var ErrNoEncryptionKey = errors.New("encryption key is required")
|
|
|
|
func EncryptWithAESKey(data, key []byte) ([]byte, error) {
|
|
if key == nil {
|
|
return data, ErrNoEncryptionKey
|
|
}
|
|
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return gcm.Seal(nonce, nonce, data, nil), nil
|
|
}
|
|
|
|
func DecryptStringWithAESKey(data, key []byte) ([]byte, error) {
|
|
if key == nil {
|
|
return data, ErrNoEncryptionKey
|
|
}
|
|
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(data) < gcm.NonceSize() {
|
|
return nil, ErrShortCipherText
|
|
}
|
|
|
|
nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]
|
|
decrypted, err := gcm.Open(nil, nonce, ciphertext, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return decrypted, nil
|
|
}
|