diff options
| author | Chris Lu <chris.lu@gmail.com> | 2020-03-06 00:49:47 -0800 |
|---|---|---|
| committer | Chris Lu <chris.lu@gmail.com> | 2020-03-06 00:49:47 -0800 |
| commit | 13e215ee5cb5f4c2873f89c263d8c970e9978b19 (patch) | |
| tree | 731a943d505c809ef73f9652df2ed868fa09b118 /weed/util/cipher.go | |
| parent | 31c481e3fce94a1a3872434a9907a574cb2679e1 (diff) | |
| download | seaweedfs-13e215ee5cb5f4c2873f89c263d8c970e9978b19.tar.xz seaweedfs-13e215ee5cb5f4c2873f89c263d8c970e9978b19.zip | |
filer: option to encrypt data on volume server
Diffstat (limited to 'weed/util/cipher.go')
| -rw-r--r-- | weed/util/cipher.go | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/weed/util/cipher.go b/weed/util/cipher.go new file mode 100644 index 000000000..f044c2ca3 --- /dev/null +++ b/weed/util/cipher.go @@ -0,0 +1,60 @@ +package util + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "errors" + "io" + + "github.com/chrislusf/seaweedfs/weed/glog" +) + +type CipherKey []byte + +func GenCipherKey() CipherKey { + key := make([]byte, 32) + if _, err := io.ReadFull(rand.Reader, key); err != nil { + glog.Fatalf("random key gen: %v", err) + } + return CipherKey(key) +} + +func Encrypt(plaintext []byte, key CipherKey) ([]byte, error) { + c, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + + gcm, err := cipher.NewGCM(c) + 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, plaintext, nil), nil +} + +func Decrypt(ciphertext []byte, key CipherKey) ([]byte, error) { + c, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + + gcm, err := cipher.NewGCM(c) + if err != nil { + return nil, err + } + + nonceSize := gcm.NonceSize() + if len(ciphertext) < nonceSize { + return nil, errors.New("ciphertext too short") + } + + nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] + return gcm.Open(nil, nonce, ciphertext, nil) +} |
